answer
stringlengths 17
10.2M
|
|---|
package florian_haas.lucas.model;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@Entity
public class Employment extends EntityBase {
private static final long serialVersionUID = 8794256029793389169L;
@ManyToOne(optional = false)
@JoinColumn(nullable = false)
@NotNull
private User user;
@ManyToOne(optional = false)
@JoinColumn(nullable = false)
@NotNull
private Company company;
@Basic(optional = false)
@Column(nullable = false)
@NotNull
private EnumEmployeePosition position;
@OneToOne(cascade = CascadeType.ALL, optional = true, orphanRemoval = true)
@Valid
private SalaryData salaryData;
Employment() {}
public Employment(User user, Company company, EnumEmployeePosition position) {
this(user, company, position, null, (EnumWorkShift[]) null);
}
public Employment(User user, Company company, EnumEmployeePosition position, EnumSalaryClass salaryClass, EnumWorkShift... workShifts) {
this.user = user;
this.company = company;
this.position = position;
if (salaryClass != null && workShifts != null) {
this.salaryData = new SalaryData(this, salaryClass, workShifts);
}
}
public User getUser() {
return this.user;
}
public Company getCompany() {
return this.company;
}
public EnumEmployeePosition getPosition() {
return this.position;
}
public void setPosition(EnumEmployeePosition position) {
this.position = position;
}
public SalaryData getSalaryData() {
return salaryData;
}
}
|
package org.neo4j.onlinebackup.ha;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.ServerSocketChannel;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.neo4j.kernel.impl.transaction.XaDataSourceManager;
import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource;
import org.neo4j.onlinebackup.net.AcceptJob;
import org.neo4j.onlinebackup.net.Callback;
import org.neo4j.onlinebackup.net.Connection;
import org.neo4j.onlinebackup.net.HandleIncommingSlaveJob;
import org.neo4j.onlinebackup.net.HandleSlaveConnection;
import org.neo4j.onlinebackup.net.Job;
import org.neo4j.onlinebackup.net.JobEater;
import org.neo4j.onlinebackup.net.SocketException;
public class Master implements Callback
{
private final EmbeddedGraphDatabase graphDb;
private final XaDataSourceManager xaDsMgr;
private final JobEater jobEater;
private final ServerSocketChannel serverChannel;
private final int port;
private List<HandleSlaveConnection> slaveList = new
CopyOnWriteArrayList<HandleSlaveConnection>();
public Master( String path, Map<String,String> params, int listenPort )
{
this.graphDb = new EmbeddedGraphDatabase( path, params );
this.xaDsMgr = graphDb.getConfig().getTxModule()
.getXaDataSourceManager();
for ( XaDataSource xaDs : xaDsMgr.getAllRegisteredDataSources() )
{
xaDs.keepLogicalLogs( true );
}
this.port = listenPort;
try
{
serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking( false );
serverChannel.socket().bind( new InetSocketAddress( listenPort ) );
}
catch ( IOException e )
{
throw new SocketException( "Unable to bind at port[" +
listenPort + "]", e );
}
jobEater = new JobEater();
jobEater.addJob( new AcceptJob( this, serverChannel ) );
jobEater.start();
}
public GraphDatabaseService getGraphDbService()
{
return graphDb;
}
public int getPort()
{
return this.port;
}
public void jobExecuted( Job job )
{
if ( job instanceof AcceptJob )
{
// handle incomming slave
AcceptJob acceptJob = (AcceptJob) job;
if ( acceptJob.getAcceptedChannel() != null )
{
Connection connection = new Connection(
((AcceptJob) job).getAcceptedChannel() );
jobEater.addJob(
new HandleIncommingSlaveJob( connection, this ) );
}
}
else if ( job instanceof HandleIncommingSlaveJob )
{
HandleSlaveConnection chainJob =
(HandleSlaveConnection) job.getChainJob();
if ( chainJob != null )
{
slaveList.add( chainJob );
}
else
{
System.out.println( "null chain job" );
}
}
}
public void shutdown()
{
jobEater.stopEating();
try
{
serverChannel.close();
}
catch ( IOException e )
{
e.printStackTrace();
}
graphDb.shutdown();
}
public long getIdentifier( String xaDsName )
{
XaDataSource xaDs = xaDsMgr.getXaDataSource( xaDsName );
if ( xaDs != null )
{
return xaDs.getRandomIdentifier();
}
return -1;
}
public long getCreationTime( String xaDsName )
{
XaDataSource xaDs = xaDsMgr.getXaDataSource( xaDsName );
if ( xaDs != null )
{
return xaDs.getCreationTime();
}
return -1;
}
public long getVersion( String xaDsName )
{
XaDataSource xaDs = xaDsMgr.getXaDataSource( xaDsName );
if ( xaDs != null )
{
return xaDs.getCurrentLogVersion();
}
return -1;
}
public ReadableByteChannel getLog( String xaDsName, long version )
throws IOException
{
XaDataSource xaDs = xaDsMgr.getXaDataSource( xaDsName );
if ( xaDs != null )
{
return xaDs.getLogicalLog( version );
}
return null;
}
public long getLogLength( String xaDsName, long version )
{
XaDataSource xaDs = xaDsMgr.getXaDataSource( xaDsName );
if ( xaDs != null )
{
return xaDs.getLogicalLogLength( version );
}
return -1l;
}
public boolean hasLog( String xaDsName, long version )
{
XaDataSource xaDs = xaDsMgr.getXaDataSource( xaDsName );
if ( xaDs != null )
{
return xaDs.hasLogicalLog( version );
}
return false;
}
public synchronized void rotateLogAndPushToSlaves() throws IOException
{
if ( slaveList.size() == 0 )
{
return;
}
for ( XaDataSource xaDs : xaDsMgr.getAllRegisteredDataSources() )
{
xaDs.rotateLogicalLog();
}
List<HandleSlaveConnection> newList =
new CopyOnWriteArrayList<HandleSlaveConnection>();
for ( HandleSlaveConnection slave : slaveList )
{
XaDataSource xaDs = xaDsMgr.getXaDataSource( slave.getXaDsName() );
if ( xaDs != null )
{
long version = xaDs.getCurrentLogVersion() - 1;
if ( !slave.offerLogToSlave( version ) )
{
System.out.println( "Failed to offer log to slave: " + slave );
}
else
{
newList.add( slave );
}
}
}
slaveList = newList;
}
}
|
// FormatReader.java
package loci.formats;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import loci.formats.meta.DummyMetadata;
import loci.formats.meta.MetadataStore;
public abstract class FormatReader extends FormatHandler
implements IFormatReader
{
// -- Constants --
/** Default thumbnail width and height. */
protected static final int THUMBNAIL_DIMENSION = 128;
// -- Fields --
/** Current file. */
protected RandomAccessStream in;
/** Hashtable containing metadata key/value pairs. */
protected Hashtable metadata;
/** The number of the current series. */
protected int series = 0;
/** Core metadata values. */
protected CoreMetadata core;
/** Whether or not to normalize float data. */
protected boolean normalizeData;
/** Whether or not to filter out invalid metadata. */
protected boolean filterMetadata;
/** Whether or not to collect metadata. */
protected boolean collectMetadata = true;
protected boolean saveOriginalMetadata = false;
/** Whether or not to group multi-file formats. */
protected boolean group = true;
/**
* Current metadata store. Should <b>never</b> be accessed directly as the
* semantics of {@link #getMetadataStore()} prevent "null" access.
*/
protected MetadataStore metadataStore = new DummyMetadata();
// -- Constructors --
/** Constructs a format reader with the given name and default suffix. */
public FormatReader(String format, String suffix) { super(format, suffix); }
/** Constructs a format reader with the given name and default suffixes. */
public FormatReader(String format, String[] suffixes) {
super(format, suffixes);
}
// -- Internal FormatReader API methods --
/**
* Initializes the given file (parsing header information, etc.).
* Most subclasses should override this method to perform
* initialization operations such as parsing metadata.
*/
protected void initFile(String id) throws FormatException, IOException {
if (currentId != null) {
String[] s = getUsedFiles();
for (int i=0; i<s.length; i++) {
if (id.equals(s[i])) return;
}
}
series = 0;
close();
currentId = id;
metadata = new Hashtable();
core = new CoreMetadata(1);
Arrays.fill(core.orderCertain, true);
// reinitialize the MetadataStore
// NB: critical for metadata conversion to work properly!
getMetadataStore().createRoot();
}
/**
* Opens the given file, reads in the first few KB and calls
* isThisType(byte[]) to check whether it matches this format.
*/
protected boolean checkBytes(String name, int maxLen) {
try {
RandomAccessStream ras = new RandomAccessStream(name);
long len = ras.length();
byte[] buf = new byte[len < maxLen ? (int) len : maxLen];
ras.readFully(buf);
ras.close();
return isThisType(buf);
}
catch (IOException exc) { return false; }
}
/** Returns true if the given file name is in the used files list. */
protected boolean isUsedFile(String file) {
String[] usedFiles = getUsedFiles();
for (int i=0; i<usedFiles.length; i++) {
if (usedFiles[i].equals(file) ||
usedFiles[i].equals(new Location(file).getAbsolutePath()))
{
return true;
}
}
return false;
}
/** Adds an entry to the metadata table. */
protected void addMeta(String key, Object value) {
if (key == null || value == null || !collectMetadata) return;
String val = value.toString();
if (filterMetadata) {
// verify key & value are not empty
if (key.length() == 0) return;
if (val.length() == 0) return;
// verify key & value are reasonable length
int maxLen = 8192;
if (key.length() > maxLen) return;
if (val.length() > maxLen) return;
// remove all non-printable characters
StringBuffer keyBuffer = new StringBuffer(key);
StringBuffer valBuffer = new StringBuffer(val);
for (int i=0; i<keyBuffer.length(); i++) {
char c = keyBuffer.charAt(i);
if (c != '\t' && c != '\n' && (c < ' ' || c > '~')) {
keyBuffer = keyBuffer.deleteCharAt(i--); // recheck this index
}
}
for (int i=0; i<valBuffer.length(); i++) {
char c = valBuffer.charAt(i);
if (c != '\t' && c != '\n' && (c < ' ' || c > '~')) {
valBuffer = valBuffer.deleteCharAt(i--); // recheck this index
}
}
key = keyBuffer.toString();
val = valBuffer.toString();
// verify key contains at least one alphabetic character
if (!key.matches(".*[a-zA-Z].*")) return;
}
if (saveOriginalMetadata) {
MetadataStore store = getMetadataStore();
if (MetadataTools.isOMEXMLMetadata(store)) {
MetadataTools.populateOriginalMetadata(store, key, val);
}
}
metadata.put(key, val);
}
/** Gets a value from the metadata table. */
protected Object getMeta(String key) {
return metadata.get(key);
}
// -- IFormatReader API methods --
/* @see IFormatReader#getImageCount() */
public int getImageCount() {
FormatTools.assertId(currentId, true, 1);
return core.imageCount[series];
}
/* @see IFormatReader#isRGB() */
public boolean isRGB() {
FormatTools.assertId(currentId, true, 1);
return core.rgb[series];
}
/* @see IFormatReader#getSizeX() */
public int getSizeX() {
FormatTools.assertId(currentId, true, 1);
return core.sizeX[series];
}
/* @see IFormatReader#getSizeY() */
public int getSizeY() {
FormatTools.assertId(currentId, true, 1);
return core.sizeY[series];
}
/* @see IFormatReader#getSizeZ() */
public int getSizeZ() {
FormatTools.assertId(currentId, true, 1);
return core.sizeZ[series];
}
/* @see IFormatReader#getSizeC() */
public int getSizeC() {
FormatTools.assertId(currentId, true, 1);
return core.sizeC[series];
}
/* @see IFormatReader#getSizeT() */
public int getSizeT() {
FormatTools.assertId(currentId, true, 1);
return core.sizeT[series];
}
/* @see IFormatReader#getPixelType() */
public int getPixelType() {
FormatTools.assertId(currentId, true, 1);
return core.pixelType[series];
}
/* @see IFormatReader#getEffectiveSizeC() */
public int getEffectiveSizeC() {
// NB: by definition, imageCount == effectiveSizeC * sizeZ * sizeT
return getImageCount() / (getSizeZ() * getSizeT());
}
/* @see IFormatReader#getRGBChannelCount() */
public int getRGBChannelCount() {
return getSizeC() / getEffectiveSizeC();
}
/* @see IFormatReader#isIndexed() */
public boolean isIndexed() {
FormatTools.assertId(currentId, true, 1);
return core.indexed[series];
}
/* @see IFormatReader#isFalseColor() */
public boolean isFalseColor() {
FormatTools.assertId(currentId, true, 1);
return core.falseColor[series];
}
/* @see IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
return null;
}
/* @see IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
return null;
}
/* @see IFormatReader#getChannelDimLengths() */
public int[] getChannelDimLengths() {
FormatTools.assertId(currentId, true, 1);
if (core.cLengths[series] == null) {
core.cLengths[series] = new int[] {core.sizeC[series]};
}
return core.cLengths[series];
}
/* @see IFormatReader#getChannelDimTypes() */
public String[] getChannelDimTypes() {
FormatTools.assertId(currentId, true, 1);
if (core.cTypes[series] == null) {
core.cTypes[series] = new String[] {FormatTools.CHANNEL};
}
return core.cTypes[series];
}
/* @see IFormatReader#getThumbSizeX() */
public int getThumbSizeX() {
FormatTools.assertId(currentId, true, 1);
if (core.thumbSizeX[series] == 0) {
int sx = getSizeX();
int sy = getSizeY();
core.thumbSizeX[series] =
sx > sy ? THUMBNAIL_DIMENSION : sx * THUMBNAIL_DIMENSION / sy;
}
return core.thumbSizeX[series];
}
/* @see IFormatReader#getThumbSizeY() */
public int getThumbSizeY() {
FormatTools.assertId(currentId, true, 1);
if (core.thumbSizeY[series] == 0) {
int sx = getSizeX();
int sy = getSizeY();
core.thumbSizeY[series] =
sy > sx ? THUMBNAIL_DIMENSION : sy * THUMBNAIL_DIMENSION / sx;
}
return core.thumbSizeY[series];
}
/* @see IFormatReader.isLittleEndian() */
public boolean isLittleEndian() {
FormatTools.assertId(currentId, true, 1);
return core.littleEndian[series];
}
/* @see IFormatReader#getDimensionOrder() */
public String getDimensionOrder() {
FormatTools.assertId(currentId, true, 1);
return core.currentOrder[series];
}
/* @see IFormatReader#isOrderCertain() */
public boolean isOrderCertain() {
FormatTools.assertId(currentId, true, 1);
return core.orderCertain[series];
}
/* @see IFormatReader#isInterleaved() */
public boolean isInterleaved() {
return isInterleaved(0);
}
/* @see IFormatReader#isInterleaved(int) */
public boolean isInterleaved(int subC) {
FormatTools.assertId(currentId, true, 1);
return core.interleaved[series];
}
/* @see IFormatReader#openBytes(int) */
public byte[] openBytes(int no) throws FormatException, IOException {
return openBytes(no, 0, 0, getSizeX(), getSizeY());
}
/* @see IFormatReader#openImage(int) */
public BufferedImage openImage(int no) throws FormatException, IOException {
return openImage(no, 0, 0, getSizeX(), getSizeY());
}
/* @see IFormatReader#openImage(int, int, int, int, int) */
public BufferedImage openImage(int no, int x, int y, int w, int h)
throws FormatException, IOException
{
return ImageTools.openImage(openBytes(no, x, y, w, h), this, w, h);
}
/* @see IFormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
return openBytes(no, buf, 0, 0, getSizeX(), getSizeY());
}
/* @see IFormatReader#openBytes(int, int, int, int, int) */
public byte[] openBytes(int no, int x, int y, int w, int h)
throws FormatException, IOException
{
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int ch = getRGBChannelCount();
byte[] newBuffer = new byte[w * h * ch * bpp];
return openBytes(no, newBuffer, x, y, w, h);
}
/* @see IFormatReader#openBytes(int, byte[], int, int, int, int) */
public abstract byte[] openBytes(int no, byte[] buf, int x, int y,
int w, int h) throws FormatException, IOException;
/* @see IFormatReader#openThumbImage(int) */
public BufferedImage openThumbImage(int no)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
return ImageTools.scale(openImage(no), getThumbSizeX(),
getThumbSizeY(), false);
}
/* @see IFormatReader#openThumbBytes(int) */
public byte[] openThumbBytes(int no) throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
BufferedImage img = openThumbImage(no);
byte[][] bytes = ImageTools.getPixelBytes(img, core.littleEndian[series]);
if (bytes.length == 1) return bytes[0];
byte[] rtn = new byte[getRGBChannelCount() * bytes[0].length];
for (int i=0; i<getRGBChannelCount(); i++) {
System.arraycopy(bytes[i], 0, rtn, bytes[0].length * i, bytes[i].length);
}
return rtn;
}
/* @see IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
if (fileOnly) {
if (in != null) in.close();
}
else close();
}
/* @see IFormatReader#getSeriesCount() */
public int getSeriesCount() {
FormatTools.assertId(currentId, true, 1);
return core.sizeX.length;
}
/* @see IFormatReader#setSeries(int) */
public void setSeries(int no) {
if (no < 0 || no >= getSeriesCount()) {
throw new IllegalArgumentException("Invalid series: " + no);
}
series = no;
}
/* @see IFormatReader#getSeries() */
public int getSeries() {
return series;
}
/* @see IFormatReader#setGroupFiles(boolean) */
public void setGroupFiles(boolean groupFiles) {
FormatTools.assertId(currentId, false, 1);
group = groupFiles;
}
/* @see IFormatReader#isGroupFiles() */
public boolean isGroupFiles() {
return group;
}
/* @see IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id)
throws FormatException, IOException
{
return FormatTools.CANNOT_GROUP;
}
/* @see IFormatReader#isMetadataComplete() */
public boolean isMetadataComplete() {
FormatTools.assertId(currentId, true, 1);
return core.metadataComplete[series];
}
/* @see IFormatReader#setNormalized(boolean) */
public void setNormalized(boolean normalize) {
FormatTools.assertId(currentId, false, 1);
normalizeData = normalize;
}
/* @see IFormatReader#isNormalized() */
public boolean isNormalized() {
return normalizeData;
}
/* @see IFormatReader#setMetadataCollected(boolean) */
public void setMetadataCollected(boolean collect) {
FormatTools.assertId(currentId, false, 1);
collectMetadata = collect;
}
/* @see IFormatReader#isMetadataCollected() */
public boolean isMetadataCollected() {
return collectMetadata;
}
/* @see IFormatReader#setOriginalMetadataPopulated(boolean) */
public void setOriginalMetadataPopulated(boolean populate) {
FormatTools.assertId(currentId, false, 1);
saveOriginalMetadata = populate;
}
/* @see IFormatReader#isOriginalMetadataPopulated() */
public boolean isOriginalMetadataPopulated() {
return saveOriginalMetadata;
}
/* @see IFormatReader#getUsedFiles() */
public String[] getUsedFiles() {
FormatTools.assertId(currentId, true, 1);
return new String[] {currentId};
}
/* @see IFormatReader#getCurrentFile() */
public String getCurrentFile() {
return currentId == null ? "" : currentId;
}
/* @see IFormatReader#getIndex(int, int, int) */
public int getIndex(int z, int c, int t) {
FormatTools.assertId(currentId, true, 1);
return FormatTools.getIndex(this, z, c, t);
}
/* @see IFormatReader#getZCTCoords(int) */
public int[] getZCTCoords(int index) {
FormatTools.assertId(currentId, true, 1);
return FormatTools.getZCTCoords(this, index);
}
/* @see IFormatReader#getMetadataValue(String) */
public Object getMetadataValue(String field) {
FormatTools.assertId(currentId, true, 1);
return getMeta(field);
}
/* @see IFormatReader#getMetadata() */
public Hashtable getMetadata() {
FormatTools.assertId(currentId, true, 1);
return metadata;
}
/* @see IFormatReader#getCoreMetadata() */
public CoreMetadata getCoreMetadata() {
FormatTools.assertId(currentId, true, 1);
return core;
}
/* @see IFormatReader#setMetadataFiltered(boolean) */
public void setMetadataFiltered(boolean filter) {
FormatTools.assertId(currentId, false, 1);
filterMetadata = filter;
}
/* @see IFormatReader#isMetadataFiltered() */
public boolean isMetadataFiltered() {
return filterMetadata;
}
/* @see IFormatReader#setMetadataStore(MetadataStore) */
public void setMetadataStore(MetadataStore store) {
FormatTools.assertId(currentId, false, 1);
if (store == null) {
throw new IllegalArgumentException("Metadata object cannot be null; " +
"use loci.formats.meta.DummyMetadata instead");
}
metadataStore = store;
}
/* @see IFormatReader#getMetadataStore() */
public MetadataStore getMetadataStore() {
return metadataStore;
}
/* @see IFormatReader#getMetadataStoreRoot() */
public Object getMetadataStoreRoot() {
FormatTools.assertId(currentId, true, 1);
return getMetadataStore().getRoot();
}
/* @see IFormatReader#getUnderlyingReaders() */
public IFormatReader[] getUnderlyingReaders() {
return null;
}
// -- IFormatHandler API methods --
/* @see IFormatHandler#setId(String, boolean) */
public void setId(String id, boolean force)
throws FormatException, IOException
{
if (!id.equals(currentId) || force) initFile(id);
}
/* @see IFormatHandler#close() */
public void close() throws IOException {
if (in != null) in.close();
in = null;
currentId = null;
}
// -- Deprecated IFormatReader API methods --
/** @deprecated Replaced by {@link #getImageCount()} */
public int getImageCount(String id) throws FormatException, IOException {
setId(id);
return getImageCount();
}
/** @deprecated Replaced by {@link #isRGB()} */
public boolean isRGB(String id) throws FormatException, IOException {
return getRGBChannelCount(id) > 1;
}
/** @deprecated Replaced by {@link #getSizeX()} */
public int getSizeX(String id) throws FormatException, IOException {
setId(id);
return core.sizeX[series];
}
/** @deprecated Replaced by {@link #getSizeY()} */
public int getSizeY(String id) throws FormatException, IOException {
setId(id);
return core.sizeY[series];
}
/** @deprecated Replaced by {@link #getSizeZ()} */
public int getSizeZ(String id) throws FormatException, IOException {
setId(id);
return core.sizeZ[series];
}
/** @deprecated Replaced by {@link #getSizeC()} */
public int getSizeC(String id) throws FormatException, IOException {
setId(id);
return core.sizeC[series];
}
/** @deprecated Replaced by {@link #getSizeT()} */
public int getSizeT(String id) throws FormatException, IOException {
setId(id);
return core.sizeT[series];
}
/** @deprecated Replaced by {@link #getPixelType()} */
public int getPixelType(String id) throws FormatException, IOException {
setId(id);
return core.pixelType[series];
}
/** @deprecated Replaced by {@link #getEffectiveSizeC()} */
public int getEffectiveSizeC(String id) throws FormatException, IOException {
// NB: by definition, imageCount == effectiveSizeC * sizeZ * sizeT
return getImageCount(id) / (getSizeZ(id) * getSizeT(id));
}
/** @deprecated Replaced by {@link #getRGBChannelCount()} */
public int getRGBChannelCount(String id) throws FormatException, IOException {
return getSizeC(id) / getEffectiveSizeC(id);
}
/** @deprecated Replaced by {@link #getChannelDimLengths()} */
public int[] getChannelDimLengths(String id)
throws FormatException, IOException
{
setId(id);
if (core.cLengths[series] == null) {
core.cLengths[series] = new int[] {core.sizeC[series]};
}
return core.cLengths[series];
}
/** @deprecated Replaced by {@link #getChannelDimTypes()} */
public String[] getChannelDimTypes(String id)
throws FormatException, IOException
{
setId(id);
if (core.cTypes[series] == null) {
core.cTypes[series] = new String[] {FormatTools.CHANNEL};
}
return core.cTypes[series];
}
/** @deprecated Replaced by {@link #getThumbSizeX()} */
public int getThumbSizeX(String id) throws FormatException, IOException {
int sx = getSizeX(id);
int sy = getSizeY(id);
return sx > sy ? THUMBNAIL_DIMENSION : sx * THUMBNAIL_DIMENSION / sy;
}
/** @deprecated Replaced by {@link #getThumbSizeY()} */
public int getThumbSizeY(String id) throws FormatException, IOException {
int sx = getSizeX(id);
int sy = getSizeY(id);
return sy > sx ? THUMBNAIL_DIMENSION : sy * THUMBNAIL_DIMENSION / sx;
}
/** @deprecated Replaced by {@link #isLittleEndian()} */
public boolean isLittleEndian(String id) throws FormatException, IOException {
setId(id);
return isLittleEndian();
}
/** @deprecated Replaced by {@link #getDimensionOrder()} */
public String getDimensionOrder(String id) throws FormatException, IOException
{
setId(id);
return core.currentOrder[series];
}
/** @deprecated Replaced by {@link #isOrderCertain()} */
public boolean isOrderCertain(String id) throws FormatException, IOException {
setId(id);
return core.orderCertain[series];
}
/** @deprecated Replaced by {@link #isInterleaved()} */
public boolean isInterleaved(String id)
throws FormatException, IOException
{
return isInterleaved(id, 0);
}
/** @deprecated Replaced by {@link #isInterleaved(int)} */
public boolean isInterleaved(String id, int subC)
throws FormatException, IOException
{
setId(id);
return isInterleaved(subC);
}
/** @deprecated Replaced by {@link #openImage(int)} */
public BufferedImage openImage(String id, int no)
throws FormatException, IOException
{
setId(id);
return openImage(no);
}
/** @deprecated Replaced by {@link #openBytes(int)} */
public byte[] openBytes(String id, int no)
throws FormatException, IOException
{
setId(id);
return openBytes(no);
}
/** @deprecated Replaced by {@link #openBytes(int, byte[])} */
public byte[] openBytes(String id, int no, byte[] buf)
throws FormatException, IOException
{
return openBytes(id, no);
}
/** @deprecated Replaced by {@link #openThumbImage(int)} */
public BufferedImage openThumbImage(String id, int no)
throws FormatException, IOException
{
return ImageTools.scale(openImage(id, no),
getThumbSizeX(id), getThumbSizeY(id), false);
}
/** @deprecated Replaced by {@link #openThumbBytes(int)} */
public byte[] openThumbBytes(String id, int no)
throws FormatException, IOException
{
BufferedImage img = openThumbImage(id, no);
byte[][] bytes = ImageTools.getBytes(img);
if (bytes.length == 1) return bytes[0];
byte[] rtn = new byte[getRGBChannelCount(id) * bytes[0].length];
for (int i=0; i<getRGBChannelCount(id); i++) {
System.arraycopy(bytes[i], 0, rtn, bytes[0].length * i, bytes[i].length);
}
return rtn;
}
/** @deprecated Replaced by {@link #getSeriesCount()} */
public int getSeriesCount(String id) throws FormatException, IOException {
setId(id);
return 1;
}
/** @deprecated Replaced by {@link #setSeries(int)} */
public void setSeries(String id, int no) throws FormatException, IOException {
if (no < 0 || no >= getSeriesCount(id)) {
throw new FormatException("Invalid series: " + no);
}
series = no;
}
/** @deprecated Replaced by {@link #getSeries()} */
public int getSeries(String id) throws FormatException, IOException {
setId(id);
return series;
}
/** @deprecated Replaced by {@link #getUsedFiles()} */
public String[] getUsedFiles(String id) throws FormatException, IOException {
setId(id);
return new String[] {id};
}
/** @deprecated Replaced by {@link #getIndex(int, int, int)} */
public int getIndex(String id, int z, int c, int t)
throws FormatException, IOException
{
setId(id);
return FormatTools.getIndex(this, z, c, t);
}
/** @deprecated Replaced by {@link #getZCTCoords(int)} */
public int[] getZCTCoords(String id, int index)
throws FormatException, IOException
{
setId(id);
return FormatTools.getZCTCoords(this, index);
}
/** @deprecated Replaced by {@link #getMetadataValue(String)} */
public Object getMetadataValue(String id, String field)
throws FormatException, IOException
{
setId(id);
return getMeta(field);
}
/** @deprecated Replaced by {@link #getMetadata()} */
public Hashtable getMetadata(String id) throws FormatException, IOException {
setId(id);
return metadata;
}
/** @deprecated Replaced by {@link #getCoreMetadata()} */
public CoreMetadata getCoreMetadata(String id)
throws FormatException, IOException
{
setId(id);
return core;
}
/** @deprecated Replaced by {@link #getMetadataStore()} */
public MetadataStore getMetadataStore(String id)
throws FormatException, IOException
{
setId(id);
return metadataStore;
}
/** @deprecated Replaced by {@link #getMetadataStoreRoot()} */
public Object getMetadataStoreRoot(String id)
throws FormatException, IOException
{
setId(id);
return getMetadataStore().getRoot();
}
}
|
package io.straas.android.sdk.streaming.demo.camera;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.session.MediaControllerCompat.Callback;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import java.util.ArrayList;
import io.straas.android.sdk.demo.R;
import io.straas.android.sdk.media.StraasMediaCore;
import io.straas.android.sdk.streaming.CameraController;
import io.straas.android.sdk.streaming.LiveEventConfig;
import io.straas.android.sdk.streaming.StreamConfig;
import io.straas.android.sdk.streaming.StreamManager;
import io.straas.android.sdk.streaming.StreamStatsReport;
import io.straas.android.sdk.streaming.demo.Utils;
import io.straas.android.sdk.streaming.demo.filter.GPUImageSupportFilter;
import io.straas.android.sdk.streaming.demo.filter.GrayImageFilter;
import io.straas.android.sdk.streaming.demo.qrcode.QrcodeActivity;
import io.straas.android.sdk.streaming.error.StreamException.LiveCountLimitException;
import io.straas.android.sdk.streaming.interfaces.EventListener;
import io.straas.sdk.demo.MemberIdentity;
import jp.co.cyberagent.android.gpuimage.GPUImageColorInvertFilter;
import static io.straas.android.sdk.demo.R.id.filter;
import static io.straas.android.sdk.demo.R.id.flash;
import static io.straas.android.sdk.demo.R.id.switch_camera;
import static io.straas.android.sdk.demo.R.id.trigger;
import static io.straas.android.sdk.streaming.StreamManager.STATE_CONNECTING;
import static io.straas.android.sdk.streaming.StreamManager.STATE_STREAMING;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Streaming";
private StreamManager mStreamManager;
private CameraController mCameraController;
private TextureView mTextureView;
private RadioGroup mStreamWaySwitcher;
private EditText mEditTitle;
private FrameLayout mStreamKeyPanel;
private EditText mEditStreamKey;
private TextView mStreamStats;
private Button btn_trigger, btn_switch, btn_flash, btn_filter;
private int mFilter = 0;
private static final String[] STREAM_PERMISSIONS = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO
};
private static final int STREAM_PERMISSION_REQUEST = 1;
// remove StraasMediaCore if you don't need to receive live event, e.g. CCU
private StraasMediaCore mStraasMediaCore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_streaming);
StreamManager.initialize(MemberIdentity.ME)
.addOnCompleteListener(new OnCompleteListener<StreamManager>() {
@Override
public void onComplete(@NonNull Task<StreamManager> task) {
if (!task.isSuccessful()) {
Log.e(TAG, "init fail " + task.getException());
}
mStreamManager = task.getResult();
mStreamManager.addEventListener(mEventListener);
preview();
}
});
mTextureView = findViewById(R.id.preview);
mTextureView.setKeepScreenOn(true);
btn_trigger = findViewById(trigger);
btn_switch = findViewById(switch_camera);
btn_flash = findViewById(flash);
btn_filter = findViewById(filter);
mEditTitle = findViewById(R.id.edit_title);
mStreamStats = findViewById(R.id.stream_stats);
mStreamWaySwitcher = findViewById(R.id.stream_way);
mEditStreamKey = findViewById(R.id.edit_stream_key);
mStreamKeyPanel = findViewById(R.id.stream_key_panel);
initEditStreamKey();
initStreamWaySwitcher();
checkPermissions();
}
private void initEditStreamKey() {
final ImageView clearButton = findViewById(R.id.clear);
final ImageView scanButton = findViewById(R.id.scan);
mEditStreamKey.addTextChangedListener(new TextWatcher() {
@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 void afterTextChanged(Editable s) {
if (s.length() == 0) {
clearButton.setVisibility(View.GONE);
scanButton.setVisibility(View.VISIBLE);
} else {
scanButton.setVisibility(View.GONE);
clearButton.setVisibility(View.VISIBLE);
}
}
});
}
private void initStreamWaySwitcher() {
onCheckedStreamWay(mStreamWaySwitcher.getCheckedRadioButtonId());
mStreamWaySwitcher.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
onCheckedStreamWay(checkedId);
}
});
}
@Override
protected void onStart() {
super.onStart();
if (checkPermissions() == 0) {
preview();
}
}
@Override
public void onStop() {
super.onStop();
destroy();
}
private int checkPermissions() {
String[] requestPermissions = getPermissionsRequestArray(STREAM_PERMISSIONS);
if (requestPermissions.length != 0) {
ActivityCompat.requestPermissions(MainActivity.this, requestPermissions,
STREAM_PERMISSION_REQUEST);
}
return requestPermissions.length;
}
private String[] getPermissionsRequestArray(String[] permissions) {
ArrayList<String> requestArray = new ArrayList<>();
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, permission) !=
PackageManager.PERMISSION_GRANTED) {
requestArray.add(permission);
}
}
return requestArray.toArray(new String[0]);
}
private StreamConfig getConfig() {
return new StreamConfig.Builder()
.camera(StreamConfig.CAMERA_FRONT)
.fitAllCamera(true)
.build();
}
private Task<CameraController> preview() {
if (mStreamManager != null && mStreamManager.getStreamState() == StreamManager.STATE_IDLE) {
return mStreamManager.prepare(getConfig(), mTextureView)
.addOnCompleteListener(this, new OnCompleteListener<CameraController>() {
@Override
public void onComplete(@NonNull Task<CameraController> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Prepare succeeds");
mCameraController = task.getResult();
enableAllButtons();
} else {
Log.e(TAG, "Prepare fails " + task.getException());
}
}
});
}
return Tasks.forException(new IllegalStateException());
}
private void enableAllButtons() {
btn_trigger.setEnabled(true);
btn_switch.setEnabled(true);
btn_flash.setEnabled(true);
btn_filter.setEnabled(true);
}
private void createLiveEventAndStartStreaming(String title) {
mStreamManager.createLiveEvent(new LiveEventConfig.Builder()
.title(title)
.build())
.addOnSuccessListener(new OnSuccessListener<String>() {
@Override
public void onSuccess(String liveId) {
Log.d(TAG, "Create live event succeeds: " + liveId);
startStreamingWithLiveId(liveId);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception error) {
if (error instanceof LiveCountLimitException){
String liveId = ((LiveCountLimitException)error).getLiveId();
Log.d(TAG, "Existing live event: " + liveId);
startStreamingWithLiveId(liveId);
} else {
Log.e(TAG, "Create live event fails: " + error);
showError(error);
btn_trigger.setText(getResources().getString(R.string.start));
mStreamStats.setText("");
}
}
});
}
private void startStreamingWithLiveId(final String liveId) {
mStreamManager.startStreamingWithLiveId(liveId).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Start streaming succeeds");
// remove StraasMediaCore if you don't need to receive live event, e.g. CCU
mStraasMediaCore = new StraasMediaCore(MemberIdentity.ME, new MediaBrowserCompat.ConnectionCallback() {
@Override
public void onConnected() {
mStraasMediaCore.getMediaController().getTransportControls()
.prepareFromMediaId(StraasMediaCore.LIVE_ID_PREFIX + liveId, null);
mStraasMediaCore.getMediaController().registerCallback(new Callback() {
@Override
public void onSessionEvent(String event, Bundle extras) {
switch (event) {
case StraasMediaCore.LIVE_EXTRA_STATISTICS_CCU:
Log.d(TAG, "ccu: " + extras.getInt(event));
break;
case StraasMediaCore.LIVE_EXTRA_STATISTICS_HIT_COUNT:
Log.d(TAG, "hit count: " + extras.getInt(event));
break;
}
}
});
}
});
mStraasMediaCore.getMediaBrowser().connect();
} else {
Log.e(TAG, "Start streaming fails " + task.getException());
showError(task.getException());
btn_trigger.setText(getResources().getString(R.string.start));
mStreamStats.setText("");
}
}
});
}
private void startStreamingWithStreamKey(String streamKey) {
mStreamManager.startStreamingWithStreamKey(streamKey).addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Start streaming succeeds");
} else {
Log.e(TAG, "Start streaming fails " + task.getException());
showError(task.getException());
btn_trigger.setText(getResources().getString(R.string.start));
mStreamStats.setText("");
}
}
});
}
private void stopStreaming() {
// remove StraasMediaCore if you don't need to receive live event, e.g. CCU
if (mStraasMediaCore != null && mStraasMediaCore.getMediaBrowser().isConnected()) {
mStraasMediaCore.getMediaBrowser().disconnect();
}
mStreamManager.stopStreaming().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Stop succeeds");
resetViews();
} else {
Log.e(TAG, "Stop fails: " + task.getException());
}
}
});
}
private void destroy() {
if (mStreamManager != null) {
mStreamManager.destroy().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
resetViews();
}
});
}
}
private void endLiveEvent(final String liveId) {
if (mStreamManager != null || !TextUtils.isEmpty(liveId)) {
mStreamManager.endLiveEvent(liveId).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "End live event succeeds: " + liveId);
}
});
}
}
public void trigger(View view) {
if (btn_trigger.getText().equals(getResources().getString(R.string.start))) {
if (mStreamManager != null) {
btn_trigger.setText(getResources().getString(R.string.stop));
switch (mStreamWaySwitcher.getCheckedRadioButtonId()) {
case R.id.stream_way_live_event:
createLiveEventAndStartStreaming(mEditTitle.getText().toString());
break;
case R.id.stream_way_stream_key:
startStreamingWithStreamKey(mEditStreamKey.getText().toString());
break;
}
}
} else {
btn_trigger.setEnabled(false);
if (mStreamManager != null) {
stopStreaming();
}
}
}
public void switchCamera(View view) {
if (mCameraController != null) {
mCameraController.switchCamera();
}
}
public void flash(View view) {
if (mCameraController != null) {
mCameraController.toggleFlash();
}
}
public void changeFilter(View view) {
if (mStreamManager != null) {
switch(mFilter) {
case 0:
mFilter += mStreamManager.setFilter(new GrayImageFilter()) ? 1 : 0;
break;
case 1:
mFilter += mStreamManager.setFilter(new GPUImageSupportFilter<>(new GPUImageColorInvertFilter())) ? 1 : 0;
break;
case 2:
mFilter += mStreamManager.setFilter(null) ? 1 : 0;
break;
}
mFilter %= 3;
}
}
public void scanQrcode(View view) {
if (checkPermissions() != 0) {
return;
}
destroy();
Intent intent = new Intent(this, QrcodeActivity.class);
startActivityForResult(intent, 1);
}
public void clearStreamKey(View view) {
mEditStreamKey.getText().clear();
}
private void onCheckedStreamWay(int checkedId) {
switch (checkedId) {
case R.id.stream_way_live_event:
mStreamKeyPanel.setVisibility(View.GONE);
mEditTitle.setVisibility(View.VISIBLE);
break;
case R.id.stream_way_stream_key:
mEditTitle.setVisibility(View.GONE);
mStreamKeyPanel.setVisibility(View.VISIBLE);
break;
}
}
private void resetViews() {
btn_trigger.setText(getResources().getString(R.string.start));
btn_trigger.setEnabled(true);
mStreamStats.setText("");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
String streamKey = data.getStringExtra(QrcodeActivity.KEY_QR_CODE_VALUE);
if (!isPureText(streamKey)) {
Toast.makeText(this, R.string.error_wrong_format, Toast.LENGTH_LONG).show();
return;
}
mEditStreamKey.setText(streamKey);
}
}
private static boolean isPureText(String string) {
return string.matches("[A-Za-z0-9]+");
}
private void showError(Exception exception) {
Toast.makeText(this, exception.toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == STREAM_PERMISSION_REQUEST) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, getResources().getString(R.string.hint_need_permission), Toast.LENGTH_SHORT).show();
return;
}
}
preview();
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private EventListener mEventListener = new EventListener() {
@Override
public void onStreamStatsReportUpdate(StreamStatsReport streamStatsReport) {
if (mStreamManager.getStreamState() == STATE_CONNECTING ||
mStreamManager.getStreamState() == STATE_STREAMING) {
mStreamStats.setText(Utils.toDisplayText(MainActivity.this, streamStatsReport));
}
}
@Override
public void onError(Exception error, @Nullable String liveId) {
Log.e(TAG, "onError " + error);
btn_trigger.setText(getResources().getString(R.string.start));
mStreamStats.setText("");
}
};
}
|
package me.jessyan.art.http;
import android.support.annotation.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Singleton;
import me.jessyan.art.utils.CharactorHandler;
import me.jessyan.art.utils.ZipHelper;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import timber.log.Timber;
@Singleton
public class RequestInterceptor implements Interceptor {
private GlobalHttpHandler mHandler;
@Inject
public RequestInterceptor(@Nullable GlobalHttpHandler handler) {
this.mHandler = handler;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
boolean hasRequestBody = request.body() != null;
Timber.tag(getTag(request, "Request_Info")).w("Params : %s %nConnection : %s %nHeaders : %n %s "
, hasRequestBody ? parseParams(request.newBuilder().build().body()) : "Null"
, chain.connection()
, request.headers());
long t1 = System.nanoTime();
Response originalResponse;
try {
originalResponse = chain.proceed(request);
} catch (Exception e) {
Timber.w("Http Error: " + e);
throw e;
}
long t2 = System.nanoTime();
String bodySize = originalResponse.body().contentLength() != -1 ? originalResponse.body().contentLength() + "-byte" : "unknown-length";
Timber.tag(getTag(request, "Response_Info")).w("Received response in [ %d-ms ] , [ %s ]%n%s"
, TimeUnit.NANOSECONDS.toMillis(t2 - t1), bodySize, originalResponse.headers());
String bodyString = printResult(request, originalResponse.newBuilder().build());
if (mHandler != null)//,,token,
return mHandler.onHttpResultResponse(bodyString, chain, originalResponse);
return originalResponse;
}
/**
*
*
* @param request
* @param response
* @return
* @throws IOException
*/
@Nullable
private String printResult(Request request, Response response) throws IOException {
ResponseBody responseBody = response.body();
String bodyString = null;
if (isParseable(responseBody.contentType())) {
try {
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
//content
String encoding = response
.headers()
.get("Content-Encoding");
Buffer clone = buffer.clone();
//response content
bodyString = parseContent(responseBody, encoding, clone);
} catch (IOException e) {
e.printStackTrace();
}
Timber.tag(getTag(request, "Response_Result")).w(isJson(responseBody.contentType()) ?
CharactorHandler.jsonFormat(bodyString) : isXml(responseBody.contentType()) ?
CharactorHandler.xmlFormat(bodyString) : bodyString);
} else {
Timber.tag(getTag(request, "Response_Result")).w("This result isn't parsed");
}
return bodyString;
}
private String getTag(Request request, String tag) {
return String.format(" [%s] %s >>> %s", request.method(), request.url().toString(), tag);
}
/**
*
*
* @param responseBody
* @param encoding
* @param clone
* @return
*/
private String parseContent(ResponseBody responseBody, String encoding, Buffer clone) {
Charset charset = Charset.forName("UTF-8");
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(charset);
}
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {//contentgzip
return ZipHelper.decompressForGzip(clone.readByteArray(), convertCharset(charset));
} else if (encoding != null && encoding.equalsIgnoreCase("zlib")) {//contentzlib
return ZipHelper.decompressToStringForZlib(clone.readByteArray(), convertCharset(charset));
} else {//content
return clone.readString(charset);
}
}
public static String parseParams(RequestBody body) throws UnsupportedEncodingException {
if (isParseable(body.contentType())) {
try {
Buffer requestbuffer = new Buffer();
body.writeTo(requestbuffer);
Charset charset = Charset.forName("UTF-8");
MediaType contentType = body.contentType();
if (contentType != null) {
charset = contentType.charset(charset);
}
return URLDecoder.decode(requestbuffer.readString(charset), convertCharset(charset));
} catch (IOException e) {
e.printStackTrace();
}
}
return "This params isn't parsed";
}
public static boolean isParseable(MediaType mediaType) {
if (mediaType == null) return false;
return mediaType.toString().toLowerCase().contains("text")
|| isJson(mediaType) || isForm(mediaType)
|| isHtml(mediaType) || isXml(mediaType);
}
public static boolean isJson(MediaType mediaType) {
return mediaType.toString().toLowerCase().contains("json");
}
public static boolean isXml(MediaType mediaType) {
return mediaType.toString().toLowerCase().contains("xml");
}
public static boolean isHtml(MediaType mediaType) {
return mediaType.toString().toLowerCase().contains("html");
}
public static boolean isForm(MediaType mediaType) {
return mediaType.toString().toLowerCase().contains("x-www-form-urlencoded");
}
public static String convertCharset(Charset charset) {
String s = charset.toString();
int i = s.indexOf("[");
if (i == -1)
return s;
return s.substring(i + 1, s.length() - 1);
}
}
|
// FEITiffReader.java
package loci.formats.in;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import loci.common.DateTools;
import loci.common.IniList;
import loci.common.IniParser;
import loci.common.IniTable;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import ome.xml.model.primitives.PositiveFloat;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffParser;
public class FEITiffReader extends BaseTiffReader {
// -- Constants --
public static final int SFEG_TAG = 34680;
public static final int HELIOS_TAG = 34682;
private static final String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss a";
private static final double MAG_MULTIPLIER = 0.0024388925;
// -- Fields --
private String imageName;
private String imageDescription;
private String date;
private String userName;
private String microscopeModel;
private Double stageX, stageY, stageZ;
private Double sizeX, sizeY, timeIncrement;
private ArrayList<String> detectors;
// -- Constructor --
public FEITiffReader() {
super("FEI TIFF", new String[] {"tif", "tiff"});
suffixSufficient = false;
domains = new String[] {FormatTools.SEM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
return ifd.containsKey(SFEG_TAG) || ifd.containsKey(HELIOS_TAG);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
imageName = null;
imageDescription = null;
date = null;
userName = null;
microscopeModel = null;
stageX = stageY = stageZ = null;
sizeX = sizeY = timeIncrement = null;
detectors = null;
}
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
boolean helios = ifds.get(0).containsKey(HELIOS_TAG);
addGlobalMeta("Software", helios ? "Helios NanoLab" : "S-FEG");
String tag = ifds.get(0).getIFDTextValue(helios ? HELIOS_TAG : SFEG_TAG);
IniParser parser = new IniParser();
IniList ini = parser.parseINI(new BufferedReader(new StringReader(tag)));
detectors = new ArrayList<String>();
// store metadata for later conversion to OME-XML
if (helios) {
IniTable userTable = ini.getTable("User");
date = userTable.get("Date") + " " + userTable.get("Time");
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
userName = userTable.get("User");
IniTable systemTable = ini.getTable("System");
if (systemTable == null) {
systemTable = ini.getTable("SYSTEM");
}
if (systemTable != null) {
microscopeModel = systemTable.get("SystemType");
}
IniTable beamTable = ini.getTable("Beam");
if (beamTable != null) {
String beamTableName = beamTable.get("Beam");
if (beamTableName != null) {
beamTable = ini.getTable(beamTableName);
}
}
if (beamTable != null) {
String beamX = beamTable.get("StageX");
String beamY = beamTable.get("StageY");
String beamZ = beamTable.get("StageZ");
IniTable stageTable = ini.getTable("Stage");
if (beamX != null) {
stageX = new Double(beamX);
}
else if (stageTable != null) {
stageX = new Double(stageTable.get("StageX"));
}
if (beamY != null) {
stageY = new Double(beamY);
}
else if (stageTable != null) {
stageY = new Double(stageTable.get("StageY"));
}
if (beamZ != null) {
stageZ = new Double(beamZ);
}
else if (stageTable != null) {
stageZ = new Double(stageTable.get("StageZ"));
}
}
IniTable scanTable = ini.getTable("Scan");
// physical sizes are stored in meters
sizeX = new Double(scanTable.get("PixelWidth")) * 1000000;
sizeY = new Double(scanTable.get("PixelHeight")) * 1000000;
timeIncrement = new Double(scanTable.get("FrameTime"));
}
}
else {
IniTable dataTable = ini.getTable("DatabarData");
imageName = dataTable.get("ImageName");
imageDescription = dataTable.get("szUserText");
String magnification = ini.getTable("Vector").get("Magnification");
sizeX = new Double(magnification) * MAG_MULTIPLIER;
sizeY = new Double(magnification) * MAG_MULTIPLIER;
IniTable scanTable = ini.getTable("Vector.Sysscan");
stageX = new Double(scanTable.get("PositionX"));
stageY = new Double(scanTable.get("PositionY"));
IniTable detectorTable = ini.getTable("Vector.Video.Detectors");
int detectorCount =
Integer.parseInt(detectorTable.get("NrDetectorsConnected"));
for (int i=0; i<detectorCount; i++) {
detectors.add(detectorTable.get("Detector_" + i + "_Name"));
}
}
// store everything else in the metadata hashtable
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
HashMap<String, String> iniMap = ini.flattenIntoHashMap();
metadata.putAll(iniMap);
}
}
/* @see BaseTiffReader#initMetadataStore() */
protected void initMetadataStore() throws FormatException {
super.initMetadataStore();
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
if (date != null) {
store.setImageAcquiredDate(DateTools.formatDate(date, DATE_FORMAT), 0);
}
else MetadataTools.setDefaultCreationDate(store, currentId, 0);
if (imageName != null) {
store.setImageName(imageName, 0);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (imageDescription != null) {
store.setImageDescription(imageDescription, 0);
}
if (userName != null) {
store.setExperimenterID(MetadataTools.createLSID("Experimenter", 0), 0);
store.setExperimenterDisplayName(userName, 0);
}
if (microscopeModel != null) {
String instrument = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrument, 0);
store.setImageInstrumentRef(instrument, 0);
store.setMicroscopeModel(microscopeModel, 0);
}
if (detectors.size() > 0) {
String instrument = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrument, 0);
store.setImageInstrumentRef(instrument, 0);
for (int i=0; i<detectors.size(); i++) {
String detectorID = MetadataTools.createLSID("Detector", 0, i);
store.setDetectorID(detectorID, 0, i);
store.setDetectorModel(detectors.get(i), 0, i);
store.setDetectorType(getDetectorType("Other"), 0, i);
}
}
store.setStageLabelX(stageX, 0);
store.setStageLabelY(stageY, 0);
store.setStageLabelZ(stageZ, 0);
store.setStageLabelName("", 0);
store.setPixelsPhysicalSizeX(new PositiveFloat(sizeX), 0);
store.setPixelsPhysicalSizeY(new PositiveFloat(sizeY), 0);
store.setPixelsTimeIncrement(timeIncrement, 0);
}
}
}
|
package gov.nih.nci.calab.service.search;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.dto.search.WorkflowResultBean;
import gov.nih.nci.calab.service.util.CalabComparators;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.log4j.Logger;
/**
* This class implements middle-tier methods for the search workflow page
*
* @author pansu
*
*/
/* CVS $Id: SearchWorkflowService.java,v 1.21 2006-04-26 21:35:04 pansu Exp $ */
public class SearchWorkflowService {
private static Logger logger = Logger
.getLogger(SearchWorkflowService.class);
/**
*
* @return all file submitters
*/
public List<String> getAllFileSubmitters() throws Exception {
SortedSet<String> submitters = new TreeSet<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString1 = "select distinct createdBy from InputFile order by createdBy";
List results1 = ida.search(hqlString1);
for (Object obj : results1) {
submitters.add((String) obj);
}
String hqlString2 = "select distinct createdBy from OutputFile order by createdBy";
List results2 = ida.search(hqlString2);
for (Object obj : results2) {
submitters.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all file submitters", e);
throw new RuntimeException(
"Error in retrieving all file submitters");
} finally {
ida.close();
}
return new ArrayList<String>(submitters);
}
public List<WorkflowResultBean> searchWorkflows(String assayName,
String assayType, Date assayRunDateBegin, Date assayRunDateEnd,
String aliquotName, boolean includeMaskedAliquots, String fileName,
boolean isFileIn, boolean isFileOut, Date fileSubmissionDateBegin,
Date fileSubmissionDateEnd, String fileSubmitter,
boolean includeMaskedFiles, String criteriaJoin) throws Exception {
List<WorkflowResultBean> workflows = null;
// construct where clause and parameter list
Object[] whereParams = constructWhereParams(assayName, assayType,
assayRunDateBegin, assayRunDateEnd, aliquotName, fileName,
fileSubmissionDateBegin, fileSubmissionDateEnd, fileSubmitter,
criteriaJoin);
String hqlString = "select distinct file.path, assay.assayType, assay.name, run.name, run.createdDate, aliquot.name, aliquotStatus.status, file.createdDate, file.createdBy, fileStatus.status ";
// get inputFile workflows first
SortedSet<WorkflowResultBean> workflowSet = new TreeSet<WorkflowResultBean>(
new CalabComparators.WorkflowResultBeanComparator());
String inHqlString = hqlString
+ ", '"
+ CalabConstants.INPUT
+ "' from Assay assay join assay.runCollection run left join run.inputFileCollection file left join file.dataStatus fileStatus left join run.runSampleContainerCollection runSampleContainer left join runSampleContainer.sampleContainer aliquot left join aliquot.dataStatus aliquotStatus ";
inHqlString += whereParams[0];
List<WorkflowResultBean> inWorkflows = getWorkflows(inHqlString,
(List) whereParams[1]);
workflowSet.addAll(inWorkflows);
// get outputFile workflows next
String outHqlString = hqlString
+ ", '"
+ CalabConstants.OUTPUT
+ "' from Assay assay join assay.runCollection run left join run.outputFileCollection file left join file.dataStatus fileStatus left join run.runSampleContainerCollection runSampleContainer left join runSampleContainer.sampleContainer aliquot left join aliquot.dataStatus aliquotStatus ";
outHqlString += whereParams[0];
List<WorkflowResultBean> outWorkflows = getWorkflows(outHqlString,
(List) whereParams[1]);
workflowSet.addAll(outWorkflows);
workflows = filterWorkflows(new ArrayList<WorkflowResultBean>(
workflowSet), isFileIn, isFileOut, includeMaskedAliquots,
includeMaskedFiles);
return workflows;
}
private Object[] constructWhereParams(String assayName, String assayType,
Date assayRunDateBegin, Date assayRunDateEnd, String aliquotName,
String fileName, Date fileSubmissionDateBegin,
Date fileSubmissionDateEnd, String fileSubmitter, String join) {
List<Object> paramList = new ArrayList<Object>();
List<String> whereList = new ArrayList<String>();
String where = "";
if (assayName.length() > 0) {
if (assayName.indexOf("*") != -1) {
assayName = assayName.replace('*', '%');
whereList.add("assay.name like ?");
} else {
whereList.add("assay.name=?");
}
paramList.add(assayName);
where = "where ";
}
if (assayType.length() > 0) {
if (assayType.indexOf("*") != -1) {
assayType = assayType.replace('*', '%');
whereList.add("assay.assayType like ?");
} else {
whereList.add("assay.assayType =?");
}
paramList.add(assayType);
where = "where ";
}
if (assayRunDateBegin != null && assayRunDateEnd != null) {
paramList.add(assayRunDateBegin);
paramList.add(assayRunDateEnd);
whereList.add("run.runDate>=? and run.runDate<=?");
where = "where ";
} else if (assayRunDateEnd != null) {
paramList.add(assayRunDateEnd);
whereList.add("run.runDate<=?");
where = "where ";
} else if (assayRunDateBegin != null) {
paramList.add(assayRunDateBegin);
whereList.add("run.runDate>=?");
where = "where ";
}
if (aliquotName.length() > 0) {
if (aliquotName.indexOf("*") != -1) {
aliquotName = aliquotName.replace('*', '%');
whereList.add("aliquot.name like ?");
} else {
whereList.add("aliquot.name=?");
}
paramList.add(aliquotName);
where = "where ";
}
if (fileName.length() > 0) {
if (fileName.indexOf("*") != -1) {
fileName = fileName.replace('*', '%');
whereList.add("file.path like ?");
} else {
whereList.add("file.path=?");
}
paramList.add(fileName);
where = "where ";
}
if (fileSubmissionDateBegin != null) {
paramList.add(fileSubmissionDateBegin);
whereList.add("file.createdDate>=?");
where = "where ";
}
if (fileSubmissionDateEnd != null) {
paramList.add(fileSubmissionDateEnd);
whereList.add("file.createdDate<=?");
where = "where ";
}
if (fileSubmitter.length() > 0) {
paramList.add(fileSubmitter);
whereList.add("file.createdBy=?");
where = "where ";
}
String whereStr = "";
if (join.equals("and")) {
whereStr = StringUtils.join(whereList, " and ");
} else {
whereStr = StringUtils.join(whereList, " or ");
}
where = where + whereStr;
Object[] objs = new Object[] { where, paramList };
return objs;
}
private List<WorkflowResultBean> getWorkflows(String hqlString,
List paramList) throws Exception {
List<WorkflowResultBean> workflows = new ArrayList<WorkflowResultBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
List results = ida.searchByParam(hqlString, paramList);
for (Object obj : results) {
Object[] items = (Object[]) obj;
String theFilePath = StringUtils.convertToString(items[0]);
String theAssayType = StringUtils.convertToString(items[1]);
String theAssayName = StringUtils.convertToString(items[2]);
String theAssayRunName = StringUtils.convertToString(items[3]);
String theAssayRunDate = StringUtils.convertDateToString(
(Date) items[4], CalabConstants.DATE_FORMAT);
String theAliquotName = StringUtils.convertToString(items[5]);
String theAliquotStatus = StringUtils.convertToString(items[6]);
String theFileSubmissionDate = StringUtils.convertDateToString(
(Date) items[7], CalabConstants.DATE_FORMAT);
String theFileSubmitter = StringUtils.convertToString(items[8]);
String theFileStatus = StringUtils.convertToString(items[9]);
// set inout type to empty string when file path is emtpy
String theFileInoutType = StringUtils
.convertToString(items[10]);
// filter out rows with inouttype=out and empty file path
if (!theFileInoutType.equals(CalabConstants.OUTPUT)
|| theFilePath.length() > 0) {
// set inout type=in to empty when no filePath
theFileInoutType = (theFilePath.length() == 0) ? ""
: theFileInoutType;
workflows.add(new WorkflowResultBean(theFilePath,
theAssayType, theAssayName, theAssayRunName,
theAssayRunDate, theAliquotName, theAliquotStatus,
theFileSubmissionDate, theFileSubmitter,
theFileStatus, theFileInoutType));
}
}
} catch (Exception e) {
logger.error("Error in searching aliquots by the given parameters",
e);
throw new RuntimeException(
"Error in searching aliquots by the given parameters");
} finally {
ida.close();
}
return workflows;
}
private List<WorkflowResultBean> filterWorkflows(
List<WorkflowResultBean> origWorkflows, boolean isFileIn,
boolean isFileOut, boolean includedMaskedAliquots,
boolean includeMaskedFiles) {
// no filtering
if (!isFileIn && !isFileOut && includedMaskedAliquots
&& includeMaskedFiles) {
return origWorkflows;
}
String selectFileType = null;
if (isFileIn && isFileOut) {
selectFileType = "both";
} else if (isFileIn) {
selectFileType = CalabConstants.INPUT;
} else if (isFileOut) {
selectFileType = CalabConstants.OUTPUT;
} else {
selectFileType = "";
}
List<WorkflowResultBean> workflows = new ArrayList<WorkflowResultBean>();
for (WorkflowResultBean workflow : origWorkflows) {
String fileInOut = workflow.getFile().getInoutType();
String fileStatus = workflow.getFile().getFileMaskStatus();
String aliquotStatus = workflow.getAliquot().getMaskStatus();
// filter out workflows when not satisfying masking criteria
if (!includeMaskedFiles
&& (fileStatus.equals(CalabConstants.MASK_STATUS))
|| !includedMaskedAliquots
&& aliquotStatus.equals(CalabConstants.MASK_STATUS)) {
}
// and filter out workflows when not satisfying in out criteria
else if (selectFileType.equals("both")
&& fileInOut.length() > 0
|| selectFileType.equals("")
|| (selectFileType.equals(CalabConstants.INPUT) || selectFileType
.equals(CalabConstants.OUTPUT))
&& selectFileType.equals(fileInOut)
&& fileInOut.length() > 0) {
workflows.add(workflow);
}
}
return workflows;
}
}
|
package org.cinchapi.concourse;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.annotation.Nullable;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.cinchapi.concourse.config.ConcourseConfiguration;
import org.cinchapi.concourse.security.ClientSecurity;
import org.cinchapi.concourse.thrift.AccessToken;
import org.cinchapi.concourse.thrift.ConcourseService;
import org.cinchapi.concourse.thrift.Operator;
import org.cinchapi.concourse.thrift.TObject;
import org.cinchapi.concourse.thrift.TransactionToken;
import org.cinchapi.concourse.time.Time;
import org.cinchapi.concourse.time.Timestamp;
import org.cinchapi.concourse.util.Convert;
import org.cinchapi.concourse.util.Transformers;
import org.cinchapi.concourse.util.TLinkedHashMap;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
/**
* <p>
* Concourse is a schemaless and distributed version control database with
* optimistic availability, serializable transactions and full-text search.
* Concourse provides a more intuitive approach to data management that is easy
* to deploy, access and scale with minimal tuning while also maintaining the
* referential integrity and ACID characteristics of traditional database
* systems.
* </p>
* <h2>Data Model</h2>
* <p>
* The Concourse data model is lightweight and flexible which enables it to
* support any kind of data at very large scales. Concourse trades unnecessary
* structural notions of schemas, tables and indexes for a more natural modeling
* of data based solely on the following concepts:
* </p>
* <p>
* <ul>
* <li><strong>Record</strong> — A logical grouping of data about a single
* person, place, or thing (i.e. an object). Each {@code record} is a collection
* of key/value pairs that are together identified by a unique primary key.
* <li><strong>Key</strong> — An attribute that maps to a set of
* <em>one or more</em> distinct {@code values}. A {@code record} can have many
* different {@code keys}, and the {@code keys} in one {@code record} do not
* affect the those in another {@code record}.
* <li><strong>Value</strong> — A dynamically typed quantity that is
* mapped from a {@code key} in a {@code record}.
* </ul>
* </p>
* <h4>Data Types</h4>
* <p>
* Concourse natively stores most of the Java primitives: boolean, double,
* float, integer, long, and string (UTF-8). Otherwise, the value of the
* {@link #toString()} method for the Object is stored.
* </p>
* <h4>Links</h4>
* <p>
* Concourse supports linking a {@code key} in one {@code record} to another
* {@code record}. Links are one-directional, but it is possible to add two
* links that are the inverse of each other to simulate bi-directionality (i.e.
* link "friend" in Record 1 to Record 2 and link "friend" in Record 2 to Record
* 1).
* </p>
* <h2>Transactions</h2>
* <p>
* By default, Concourse conducts every operation in {@code autocommit} mode
* where every change is immediately written. Concourse also supports the
* ability to stage a group of operations in transactions that are atomic,
* consistent, isolated, and durable using the {@link #stage()},
* {@link #commit()} and {@link #abort()} methods.
*
* </p>
*
* @author jnelson
*/
public abstract class Concourse {
/**
* Create a new Client connection to the default Concourse server (or the
* one specified in {@code concourse_client.prefs} if it exists) and return
* a handler to facilitate database interaction.
*/
public static Concourse connect() {
return new Client();
}
/**
* Create a new Client connection to a Concourse server and return a
* handler to facilitate database interaction.
*
* @param host
* @param port
* @param username
* @param password
*/
public static Concourse connect(String host, int port, String username,
String password) {
return new Client(host, port, username, password);
}
/**
* Discard any changes that are currently staged for commit.
* <p>
* After this function returns, Concourse will return to {@code autocommit}
* mode and all subsequent changes will be immediately written to the
* database.
* </p>
*/
public abstract void abort();
/**
* Add {@code key} as {@code value} to {@code record} and return
* {@code true} if the mapping does not currently exist in {@code record}
* and is successfully added.
*
* @param key
* @param value
* @param record
* @return {@code true} if the mapping is added
*/
public abstract <T> boolean add(String key, T value, long record);
/**
* Audit {@code record} and return a log of revisions.
*
* @param record
* @return a mapping of timestamps to revision descriptions
*/
public abstract Map<Timestamp, String> audit(long record);
/**
* Audit {@code key} in {@code record} and return a log of revisions.
*
* @param key
* @param record
* @return a mapping of timestamps to revision descriptions
*/
public abstract Map<Timestamp, String> audit(String key, long record);
/**
* Atomically clear {@code key} in {@code record} and remove every mapping
* from {@code key} that currently exists in {@code record}.
*
* @param record
*/
public abstract void clear(String key, long record);
/**
* Attempt to permanently commit all the currently staged changes. This
* function returns {@code true} if and only if all the changes can be
* successfully applied to the database. Otherwise, this function returns
* {@code false} and all the changes are aborted.
* <p>
* After this function returns, Concourse will return to {@code autocommit}
* mode and all subsequent changes will be immediately written to the
* database.
* </p>
*/
public abstract boolean commit();
/**
* Create a new Record and return its Primary Key.
*
* @return the Primary Key of the new Record
*/
public abstract long create();
/**
* Describe {@code record} and return its set of keys that currently map to
* at least one value.
*
* @param record
* @return the populated keys
*/
public abstract Set<String> describe(long record);
/**
* Describe {@code record} at {@code timestamp} and return its set of keys
* that mapped to at least one value.
*
* @param record
* @param timestamp
* @return the keys for populated keys
*/
public abstract Set<String> describe(long record, Timestamp timestamp);
/**
* Disconnect from the remote Concourse server.
*/
public abstract void exit();
/**
* Fetch {@code key} from {@code record} and return the set of currently
* mapped values.
*
* @param key
* @param record
* @return the contained values
*/
public abstract Set<Object> fetch(String key, long record);
/**
* Fetch {@code key} from {@code record} at {@code timestamp} and return the
* set of values that were mapped.
*
* @param key
* @param record
* @param timestamp
* @return the contained values
*/
public abstract Set<Object> fetch(String key, long record,
Timestamp timestamp);
/**
* Find {@code key} {@code operator} {@code value} and return the set of
* records that satisfy the criteria. This is analogous to the SELECT action
* in SQL.
*
* @param key
* @param operator
* @param value
* @return the records that match the criteria
*/
public abstract Set<Long> find(String key, Operator operator, Object value);
/**
* Find {@code key} {@code operator} {@code value} and {@code value2} and
* return the set of records that satisfy the criteria. This is analogous to
* the SELECT action in SQL.
*
* @param key
* @param operator
* @param value
* @param value2
* @return the records that match the criteria
*/
public abstract Set<Long> find(String key, Operator operator, Object value,
Object value2);
/**
* Find {@code key} {@code operator} {@code value} and {@code value2} at
* {@code timestamp} and return the set of records that satisfy the
* criteria. This is analogous to the SELECT action in SQL.
*
* @param key
* @param operator
* @param value
* @param value2
* @param timestamp
* @return the records that match the criteria
*/
public abstract Set<Long> find(String key, Operator operator, Object value,
Object value2, Timestamp timestamp);
/**
* Find {@code key} {@code operator} {@code value} at {@code timestamp} and
* return the set of records that satisfy the criteria. This is analogous to
* the SELECT action in SQL.
*
* @param key
* @param operator
* @param value
* @return the records that match the criteria
*/
public abstract Set<Long> find(String key, Operator operator, Object value,
Timestamp timestamp);
/**
* Get {@code key} from {@code record} and return the first mapped value or
* {@code null} if there is none. Compared to {@link #fetch(String, long)},
* this method is suited for cases when the caller is certain that
* {@code key} in {@code record} maps to a single value of type {@code T}.
*
* @param key
* @param record
* @return the first mapped value
*/
public abstract <T> T get(String key, long record);
/**
* Get {@code key} from {@code record} at {@code timestamp} and return the
* first mapped value or {@code null} if there was none. Compared to
* {@link #fetch(String, long, long)}, this method is suited for cases when
* the caller is certain that {@code key} in {@code record} mapped to a
* single value of type {@code T} at {@code timestamp}.
*
* @param key
* @param record
* @param timestamp
* @return the first mapped value
*/
public abstract <T> T get(String key, long record, Timestamp timestamp);
/**
* Return the version of the server to which this client is currently
* connected.
*
* @return the server version
*/
public abstract String getServerVersion();
/**
* Link {@code key} in {@code source} to {@code destination}. In other
* words, add {@code key} as {@link Link#to(destination)} in {@code source}.
*
* @param key
* @param source
* @param destination
* @return {@code true} if the one way link is added
*/
public abstract boolean link(String key, long source, long destination);
/**
* Ping {@code record} and return {@code true} if there is currently at
* least one populated key.
*
* @param record
* @return {@code true} if {@code record} currently contains data
*/
public abstract boolean ping(long record);
/**
* Remove {@code key} as {@code value} from {@code record} and return
* {@code true} if the mapping currently exists in {@code record} and is
* successfully removed.
*
* @param key
* @param value
* @param record
* @return {@code true} if the mapping is removed
*/
public abstract <T> boolean remove(String key, T value, long record);
/**
* Atomically revert {@code key} in {@code record} to {@code timestamp}.
* This method restores the key to its state at {@code timestamp} by
* reversing all revisions that have occurred since.
* <p>
* Please note that this method <strong>does not</strong> {@code rollback}
* any revisions, but creates <em>new</em> revisions that are the inverse of
* all revisions since {@code timestamp} in reverse order.
* </p>
* <p>
* <table>
* <tr>
* <th>Time</th>
* <th>Revision</th>
* </tr>
* <tr>
* <td>T1</td>
* <td>ADD A</td>
* </tr>
* <tr>
* <td>T2</td>
* <td>ADD B</td>
* </tr>
* <tr>
* <td>T3</td>
* <td>REMOVE A</td>
* </tr>
* <tr>
* <td>T4</td>
* <td>ADD C</td>
* </tr>
* <tr>
* <td>T5</td>
* <td>REMOVE C</td>
* </tr>
* <tr>
* <td>T6</td>
* <td>REMOVE B</td>
* </tr>
* <tr>
* <td>T7</td>
* <td>ADD D</td>
* </tr>
* </table>
* In the example above, after {@code T7}, the field contains value
* {@code D}. If the field is reverted to T3, the following new revisions
* are added:
* <table>
* <tr>
* <th>Time</th>
* <th>Revision</th>
* </tr>
* <tr>
* <td>T8</td>
* <td>REMOVE D</td>
* </tr>
* <tr>
* <td>T9</td>
* <td>ADD B</td>
* </tr>
* <tr>
* <td>T10</td>
* <td>ADD C</td>
* </tr>
* <tr>
* <td>T11</td>
* <td>REMOVE C</td>
* </tr>
* </table>
* After {@code T11}, the field contains value {@code B}. Regardless of the
* current state, ever revision to the field exists in history so it is
* possible to revert to any previous state, even after reverting to a much
* earlier state (i.e. after reverting to {@code T3} it is possible to
* revert to {@code T5}).
* </p>
*
* @param key
* @param record
* @param timestamp
*/
public abstract void revert(String key, long record, Timestamp timestamp);
/**
* Search {@code key} for {@code query} and return the set of records that
* match the fulltext query.
*
* @param key
* @param query
* @return the records that match the query
*/
public abstract Set<Long> search(String key, String query);
/**
* Atomically set {@code key} as {@code value} in {@code record}. This is a
* convenience method that clears the values currently mapped from
* {@code key} and adds a new mapping to {@code value}.
*
* @param key
* @param value
* @param record
*/
public abstract <T> void set(String key, T value, long record);
/**
* Turn on {@code staging} mode so that all subsequent changes are
* collected in a staging area before possibly being committed to the
* database. Staged operations are guaranteed to be reliable, all or nothing
* units of work that allow correct recovery from failures and provide
* isolation between clients so the database is always in a consistent state
* (i.e. a transaction).
* <p>
* After this method returns, all subsequent operations will be done in
* {@code staging} mode until either {@link #abort()} or {@link #commit()}
* is invoked.
* </p>
*/
public abstract void stage();
/**
* Unlink {@code key} in {@code source} to {@code destination}. In other
* words, remove{@code key} as {@link Link#to(destination)} in
* {@code source}.
*
* @param key
* @param source
* @param destination
* @return {@code true} if the one way link is removed
*/
public abstract boolean unlink(String key, long source, long destination);
/**
* Verify {@code key} equals {@code value} in {@code record} and return
* {@code true} if {@code value} is currently mapped from {@code key} in
* {@code record}.
*
* @param key
* @param value
* @param record
* @return {@code true} if the mapping exists
*/
public abstract boolean verify(String key, Object value, long record);
/**
* Verify {@code key} equaled {@code value} in {@code record} at
* {@code timestamp} and return {@code true} if {@code value} was mapped
* from {@code key} in {@code record}.
*
* @param key
* @param value
* @param record
* @param timestamp
* @return {@code true} if the mapping existed
*/
public abstract boolean verify(String key, Object value, long record,
Timestamp timestamp);
/**
* Atomically verify {@code key} equals {@code expected} in {@code record}
* and swap with {@code replacement}.
*
* @param key
* @param expected
* @param record
* @param replacement
* @return {@code true} if the swap is successful
*/
public abstract boolean verifyAndSwap(String key, TObject expected,
long record, TObject replacement);
/**
* The implementation of the {@link Concourse} interface that establishes a
* connection with the remote server and handles communication. This class
* is a more user friendly wrapper around a Thrift
* {@link ConcourseService.Client}.
*
* @author jnelson
*/
private final static class Client extends Concourse {
// NOTE: The configuration variables are static because we want to
// guarantee that they are set before the client connection is
// constructed. Even though these variables are static, it is still the
// case that any changes to the configuration will be picked up
// immediately for new client connections.
private static String SERVER_HOST;
private static int SERVER_PORT;
private static String USERNAME;
private static String PASSWORD;
static {
ConcourseConfiguration config;
try {
config = ConcourseConfiguration
.loadConfig("concourse_client.prefs");
}
catch (Exception e) {
config = null;
}
SERVER_HOST = "localhost";
SERVER_PORT = 1717;
USERNAME = "admin";
PASSWORD = "admin";
if(config != null) {
SERVER_HOST = config.getString("host", SERVER_HOST);
SERVER_PORT = config.getInt("port", SERVER_PORT);
USERNAME = config.getString("username", USERNAME);
PASSWORD = config.getString("password", PASSWORD);
}
}
/**
* Represents a request to respond to a query using the current state as
* opposed to the history.
*/
private static Timestamp now = Timestamp.fromMicros(0);
/**
* An encrypted copy of the username passed to the constructor.
*/
private final ByteBuffer username;
/**
* An encrypted copy of the password passed to the constructor.
*/
private final ByteBuffer password;
/**
* The host of the connection.
*/
private final String host;
/**
* The port of the connection.
*/
private final int port;
/**
* The Thrift client that actually handles all RPC communication.
*/
private final ConcourseService.Client client;
/**
* The client keeps a copy of its {@link AccessToken} and passes it to
* the
* server for each remote procedure call. The client will
* re-authenticate
* when necessary using the username/password read from the prefs file.
*/
private AccessToken creds = null;
/**
* Whenever the client starts a Transaction, it keeps a
* {@link TransactionToken} so that the server can stage the changes in
* the
* appropriate place.
*/
private TransactionToken transaction = null;
/**
* Create a new Client connection to the Concourse server specified in
* {@code concourse.prefs} and return a handler to facilitate database
* interaction.
*/
public Client() {
this(SERVER_HOST, SERVER_PORT, USERNAME, PASSWORD);
}
/**
* Create a new Client connection to a Concourse server and return a
* handler to facilitate database interaction.
*
* @param host
* @param port
* @param username
* @param password
*/
public Client(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = ClientSecurity.encrypt(username);
this.password = ClientSecurity.encrypt(password);
final TTransport transport = new TSocket(host, port);
try {
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
client = new ConcourseService.Client(protocol);
authenticate();
Runtime.getRuntime().addShutdownHook(new Thread("shutdown") {
@Override
public void run() {
if(transaction != null && transport.isOpen()) {
abort();
}
}
});
}
catch (TTransportException e) {
throw Throwables.propagate(e);
}
}
@Override
public String getServerVersion() {
return execute(new Callable<String>() {
@Override
public String call() throws Exception {
return client.getServerVersion();
}
});
}
@Override
public void abort() {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
if(transaction != null) {
final TransactionToken token = transaction;
transaction = null;
client.abort(creds, token);
}
return null;
}
});
}
@Override
public <T> boolean add(final String key, final T value,
final long record) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.add(key, Convert.javaToThrift(value), record,
creds, transaction);
}
});
}
@Override
public Map<Timestamp, String> audit(final long record) {
return execute(new Callable<Map<Timestamp, String>>() {
@Override
public Map<Timestamp, String> call() throws Exception {
Map<Long, String> audit = client.audit(record, null, creds,
transaction);
return ((TLinkedHashMap<Timestamp, String>) Transformers
.transformMap(audit,
new Function<Long, Timestamp>() {
@Override
public Timestamp apply(Long input) {
return Timestamp.fromMicros(input);
}
})).setKeyName("DateTime").setValueName(
"Revision");
}
});
}
@Override
public Map<Timestamp, String> audit(final String key, final long record) {
return execute(new Callable<Map<Timestamp, String>>() {
@Override
public Map<Timestamp, String> call() throws Exception {
Map<Long, String> audit = client.audit(record, key, creds,
transaction);
return ((TLinkedHashMap<Timestamp, String>) Transformers
.transformMap(audit,
new Function<Long, Timestamp>() {
@Override
public Timestamp apply(Long input) {
return Timestamp.fromMicros(input);
}
})).setKeyName("DateTime").setValueName(
"Revision");
}
});
}
@Override
public void clear(final String key, final long record) {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
client.clear(key, record, creds, transaction);
return null;
}
});
}
@Override
public boolean commit() {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
final TransactionToken token = transaction;
transaction = null;
return client.commit(creds, token);
}
});
}
@Override
public long create() {
return Time.now(); // TODO get a primary key using a plugin
}
@Override
public Set<String> describe(long record) {
return describe(record, now);
}
@Override
public Set<String> describe(final long record, final Timestamp timestamp) {
return execute(new Callable<Set<String>>() {
@Override
public Set<String> call() throws Exception {
return client.describe(record, timestamp.getMicros(),
creds, transaction);
}
});
}
@Override
public void exit() {
client.getInputProtocol().getTransport().close();
client.getOutputProtocol().getTransport().close();
}
@Override
public Set<Object> fetch(String key, long record) {
return fetch(key, record, now);
}
@Override
public Set<Object> fetch(final String key, final long record,
final Timestamp timestamp) {
return execute(new Callable<Set<Object>>() {
@Override
public Set<Object> call() throws Exception {
Set<TObject> values = client.fetch(key, record,
timestamp.getMicros(), creds, transaction);
return Transformers.transformSet(values,
new Function<TObject, Object>() {
@Override
public Object apply(TObject input) {
return Convert.thriftToJava(input);
}
});
}
});
}
@Override
public Set<Long> find(String key, Operator operator, Object value) {
return find(key, operator, value, now);
}
@Override
public Set<Long> find(String key, Operator operator, Object value,
Object value2) {
return find(key, operator, value, value2, now);
}
@Override
public Set<Long> find(final String key, final Operator operator,
final Object value, final Object value2,
final Timestamp timestamp) {
return execute(new Callable<Set<Long>>() {
@Override
public Set<Long> call() throws Exception {
return client.find(key, operator, Lists.transform(
Lists.newArrayList(value, value2),
new Function<Object, TObject>() {
@Override
public TObject apply(Object input) {
return Convert.javaToThrift(input);
}
}), timestamp.getMicros(), creds, transaction);
}
});
}
@Override
public Set<Long> find(final String key, final Operator operator,
final Object value, final Timestamp timestamp) {
return execute(new Callable<Set<Long>>() {
@Override
public Set<Long> call() throws Exception {
return client.find(key, operator, Lists.transform(
Lists.newArrayList(value),
new Function<Object, TObject>() {
@Override
public TObject apply(Object input) {
return Convert.javaToThrift(input);
}
}), timestamp.getMicros(), creds, transaction);
}
});
}
@Override
@Nullable
public <T> T get(String key, long record) {
return get(key, record, now);
}
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T get(String key, long record, Timestamp timestamp) {
Set<Object> values = fetch(key, record, timestamp);
if(!values.isEmpty()) {
return (T) values.iterator().next();
}
return null;
}
@Override
public boolean link(String key, long source, long destination) {
return add(key, Link.to(destination), source);
}
@Override
public boolean ping(final long record) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.ping(record, creds, transaction);
}
});
}
@Override
public boolean remove(final String key, final Object value,
final long record) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.remove(key, Convert.javaToThrift(value),
record, creds, transaction);
}
});
}
@Override
public void revert(final String key, final long record,
final Timestamp timestamp) {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
client.revert(key, record, timestamp.getMicros(), creds,
transaction);
return null;
}
});
}
@Override
public Set<Long> search(final String key, final String query) {
return execute(new Callable<Set<Long>>() {
@Override
public Set<Long> call() throws Exception {
return client.search(key, query, creds, transaction);
}
});
}
@Override
public <T> void set(final String key, final T value, final long record) {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
client.set0(key, Convert.javaToThrift(value), record,
creds, transaction);
return null;
}
});
}
@Override
public void stage() {
execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
transaction = client.stage(creds);
return null;
}
});
}
@Override
public String toString() {
return "Connected to " + host + ":" + port + " as "
+ new String(ClientSecurity.decrypt(username).array());
}
@Override
public boolean unlink(String key, long source, long destination) {
return remove(key, Link.to(destination), source);
}
@Override
public boolean verify(String key, Object value, long record) {
return verify(key, value, record, now);
}
@Override
public boolean verify(final String key, final Object value,
final long record, final Timestamp timestamp) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.verify(key, Convert.javaToThrift(value),
record, timestamp.getMicros(), creds, transaction);
}
});
}
@Override
public boolean verifyAndSwap(final String key, final TObject expected,
final long record, final TObject replacement) {
return execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return client.verifyAndSwap(key,
Convert.javaToThrift(expected), record,
Convert.javaToThrift(replacement), creds,
transaction);
}
});
}
/**
* Authenticate the {@link #username} and {@link #password} and populate
* {@link #creds} with the appropriate AccessToken.
*/
private void authenticate() {
try {
creds = client.login(ClientSecurity.decrypt(username),
ClientSecurity.decrypt(password));
}
catch (TException e) {
throw Throwables.propagate(e);
}
}
/**
* Execute the task defined in {@code callable}. This method contains
* retry logic to handle cases when {@code creds} expires and must be
* updated.
*
* @param callable
* @return the task result
*/
private <T> T execute(Callable<T> callable) {
try {
return callable.call();
}
catch (SecurityException e) {
authenticate();
return execute(callable);
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
}
|
package org.dellroad.stuff.vaadin;
import com.vaadin.Application;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.SourceFilteringListener;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
@SuppressWarnings("serial")
public abstract class SpringContextApplication extends ContextApplication {
/**
* Optional servlet initialization parameter (<code>{@value #VAADIN_CONTEXT_LOCATION_PARAMETER}</code>) used to specify
* the location(s) of the application context XML file(s). Multiple XML files may be separated by whitespace.
* If this parameter is not defined, then the XML file location is built using {@code /WEB-INF/} as a prefix,
* the string from {@link #getApplicationName}, and {@code .xml} as a suffix.
*/
public static final String VAADIN_CONTEXT_LOCATION_PARAMETER = "vaadinContextConfigLocation";
private static final AtomicLong UNIQUE_INDEX = new AtomicLong();
private transient ConfigurableWebApplicationContext context;
/**
* Get this instance's associated Spring application context.
*/
public ConfigurableWebApplicationContext getApplicationContext() {
return this.context;
}
public static SpringContextApplication get() {
return ContextApplication.get(SpringContextApplication.class);
}
/**
* Initializes the associated {@link ConfigurableWebApplicationContext}.
*
* <p>
* After initializing the associated Spring application context, this method delegates to {@link #initSpringApplication}.
*/
@Override
protected final void initApplication() {
// Load the context
this.loadContext();
// Initialize subclass
this.initSpringApplication(context);
}
/**
* Initialize the application. Sub-classes of {@link SpringContextApplication} must implement this method.
*
* @param context the associated {@link WebApplicationContext} just created and refreshed
* @see #destroySpringApplication
*/
protected abstract void initSpringApplication(ConfigurableWebApplicationContext context);
/**
* Perform any application-specific shutdown work. This will be invoked at shutdown after this Vaadin application and the
* associated {@link WebApplicationContext} have both been closed.
*
* <p>
* The implementation in {@link SpringContextApplication} does nothing. Subclasses may override as necessary.
* </p>
*
* <p>
* Note that if a {@link SpringContextApplication} instance is exposed in the application context and configured
* with a Spring {@linkplain org.springframework.beans.factory.DisposableBean#destroy destroy method}, then that
* method will also be invoked when the application is closed. In such cases overriding this method is not necessary.
* </p>
*
* @see #initSpringApplication
*/
protected void destroySpringApplication() {
}
/**
* Post-process the given {@link WebApplicationContext} after initial creation but before the initial
* {@link org.springframework.context.ConfigurableApplicationContext#refresh refresh()}.
*
* <p>
* The implementation in {@link SpringContextApplication} does nothing. Subclasses may override as necessary.
* </p>
*
* @param context the associated {@link WebApplicationContext} just refreshed
* @see #onRefresh
* @see ConfigurableWebApplicationContext#refresh()
*/
protected void postProcessWebApplicationContext(ConfigurableWebApplicationContext context) {
}
/**
* Perform any application-specific work after a successful application context refresh.
*
* <p>
* The implementation in {@link SpringContextApplication} does nothing. Subclasses may override as necessary.
* </p>
*
* @param context the associated {@link WebApplicationContext} just refreshed
* @see #postProcessWebApplicationContext
* @see org.springframework.context.ConfigurableApplicationContext#refresh
*/
protected void onRefresh(ApplicationContext context) {
}
/**
* Get the name for this application. This is used as the name of the XML file in {@code WEB-INF/} that
* defines the Spring application context associated with this instance, unless the
* {@link #VAADIN_CONTEXT_LOCATION_PARAMETER} servlet parameter is set.
*
* <p>
* The implementation in {@link SpringContextApplication} returns this instance's class'
* {@linkplain Class#getSimpleName simple name}.
* </p>
*/
protected String getApplicationName() {
return this.getClass().getSimpleName();
}
// ApplicationContext setup
private void loadContext() {
// Logging
this.log.info("loading application context for Vaadin application " + this.getApplicationName());
// Sanity check
if (this.context != null)
throw new IllegalStateException("context already loaded");
// Find the application context associated with the servlet; it will be the parent
String contextPath = ContextApplication.currentRequest().getContextPath() + "/";
ServletContext servletContext = ContextApplication.currentRequest().getSession().getServletContext();
WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// Create and configure a new application context for this Application instance
this.context = new XmlWebApplicationContext();
this.context.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
+ contextPath + this.getApplicationName() + "-" + UNIQUE_INDEX.incrementAndGet());
if (parent != null)
context.setParent(parent);
if (servletContext != null)
context.setServletContext(servletContext);
//context.setServletConfig(??);
this.context.setNamespace(this.getApplicationName());
// Set explicit config location(s) if set by parameter
String configLocationValue = this.getProperty(VAADIN_CONTEXT_LOCATION_PARAMETER);
if (configLocationValue != null)
this.context.setConfigLocation(configLocationValue);
// Register listener so we can notify subclass on refresh events
this.context.addApplicationListener(new SourceFilteringListener(this.context, new RefreshListener()));
// Register this instance as an implicitly resolvable dependency
this.context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.registerResolvableDependency(Application.class, SpringContextApplication.this);
}
});
// Invoke any subclass setup
this.postProcessWebApplicationContext(context);
// Refresh context
this.context.refresh();
// Get notified of application shutdown so we can shut down the context as well
this.addListener(new ContextCloseListener());
}
// Serialization
private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
this.loadContext();
}
// Nested classes
// My refresh listener
private class RefreshListener implements ApplicationListener<ContextRefreshedEvent>, Serializable {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
SpringContextApplication.this.onRefresh(event.getApplicationContext());
}
}
// My close listener
private class ContextCloseListener implements CloseListener, Serializable {
@Override
public void applicationClosed(CloseEvent closeEvent) {
SpringContextApplication.this.log.info("closing application context associated with Vaadin application "
+ SpringContextApplication.this.getApplicationName());
SpringContextApplication.this.context.close();
SpringContextApplication.this.destroySpringApplication();
}
}
}
|
package org.jboss.remoting3.jmx.common;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.Security;
import javax.management.MBeanServer;
import javax.management.remote.JMXConnectorServer;
import org.jboss.logging.Logger;
import org.jboss.remoting3.Endpoint;
import org.jboss.remoting3.Remoting;
import org.jboss.remoting3.jmx.RemotingConnectorServer;
import org.jboss.remoting3.jmx.Version;
import org.jboss.remoting3.remote.RemoteConnectionProviderFactory;
import org.jboss.remoting3.security.SimpleServerAuthenticationProvider;
import org.jboss.remoting3.spi.NetworkServerProvider;
import org.jboss.sasl.JBossSaslProvider;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Sequence;
import org.xnio.Xnio;
import org.xnio.channels.AcceptingChannel;
import org.xnio.channels.ConnectedStreamChannel;
/**
* A test server to test exposing the local MBeanServer using Remoting.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
public class JMXRemotingServer {
private static final Logger log = Logger.getLogger(JMXRemotingServer.class);
static {
Security.insertProviderAt(new JBossSaslProvider(), 1);
}
private final int listenerPort;
private final MBeanServer mbeanServer;
private Endpoint endpoint;
// TODO - This may not live here - maybe in the RemotingConnectorServer
private AcceptingChannel<? extends ConnectedStreamChannel> server;
private JMXConnectorServer connectorServer;
/**
* Constructor to instantiate a JMXRemotingServer with a specified listener port.
*
* @param port
*/
public JMXRemotingServer(final int port) {
this(port, ManagementFactory.getPlatformMBeanServer());
}
public JMXRemotingServer(final int port, final MBeanServer mbeanServer) {
this.listenerPort = port;
this.mbeanServer = mbeanServer;
}
public void start() throws IOException {
log.infof("Starting JMX Remoting Server %s", Version.getVersionString());
// Initialise general Remoting - this step would be implemented elsewhere when
// running within an application server.
final Xnio xnio = Xnio.getInstance();
endpoint = Remoting.createEndpoint("JMXRemoting", xnio, OptionMap.EMPTY);
endpoint.addConnectionProvider("remote", new RemoteConnectionProviderFactory(),
OptionMap.create(Options.SSL_ENABLED, false));
final NetworkServerProvider nsp = endpoint.getConnectionProviderInterface("remote", NetworkServerProvider.class);
final SocketAddress bindAddress = new InetSocketAddress(InetAddress.getLocalHost(), listenerPort);
final SimpleServerAuthenticationProvider authenticationProvider = new SimpleServerAuthenticationProvider();
final OptionMap serverOptions = OptionMap.create(Options.SASL_MECHANISMS, Sequence.of("ANONYMOUS"),
Options.SASL_POLICY_NOANONYMOUS, Boolean.FALSE);
server = nsp.createServer(bindAddress, serverOptions, authenticationProvider, null);
// Initialise the components that will provide JMX connectivity.
connectorServer = new RemotingConnectorServer(mbeanServer, endpoint);
connectorServer.start();
}
public void stop() throws IOException {
log.infof("Stopping JMX Remoting Server %s", Version.getVersionString());
// Services using an existing Remoting installation only need to stop the JMXConnectorServer
// to disassociate it from Remoting.
connectorServer.stop();
// TODO - Also tear down the remoting portion as that was specific to the test case.
}
public static void main(String[] args) throws IOException {
int port = 12345;
if (args.length == 1) {
port = Integer.parseInt(args[0]);
}
JMXRemotingServer server = new JMXRemotingServer(port);
server.start();
}
}
|
package vaeke.restcountries.v1;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import org.junit.Rule;
import org.junit.runner.RunWith;
import vaeke.restcountries.v1.domain.DesCountry;
import com.eclipsesource.restfuse.Assert;
import com.eclipsesource.restfuse.Destination;
import com.eclipsesource.restfuse.HttpJUnitRunner;
import com.eclipsesource.restfuse.Method;
import com.eclipsesource.restfuse.Response;
import com.eclipsesource.restfuse.annotation.Context;
import com.eclipsesource.restfuse.annotation.HttpTest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
@RunWith(HttpJUnitRunner.class)
public class CountryRestTest {
@Rule
public Destination destination = new Destination(this, "http://localhost:8081/rest/v1");
@Context
private Response response;
@HttpTest(method = Method.GET, path = "/")
public void checkOnlineStatus() {
Assert.assertOk(response);
}
@HttpTest(method = Method.GET, path = "/alpha/co")
public void alpha2() {
Assert.assertOk(response);
DesCountry country = deserialize(response.getBody());
org.junit.Assert.assertEquals("CO", country.getAlpha2Code());
}
@HttpTest(method = Method.GET, path = "/alpha/col")
public void alpha3() {
Assert.assertOk(response);
DesCountry country = deserialize(response.getBody());
org.junit.Assert.assertEquals("COL", country.getAlpha3Code());
}
@HttpTest(method = Method.GET, path = "/currency/eur")
public void currency() {
Assert.assertOk(response);
List<DesCountry> countries = deserializeList(response.getBody());
org.junit.Assert.assertFalse(countries.isEmpty());
for(DesCountry country : countries) {
org.junit.Assert.assertTrue(country.getCurrencies().contains("EUR"));
}
}
@HttpTest(method = Method.GET, path = "/callingcode/1")
public void callingcode() {
Assert.assertOk(response);
List<DesCountry> countries = deserializeList(response.getBody());
org.junit.Assert.assertFalse(countries.isEmpty());
for(DesCountry country : countries) {
org.junit.Assert.assertTrue(country.getCallingCodes().contains("1"));
}
}
@HttpTest(method = Method.GET, path = "/capital/washington")
public void capital() {
Assert.assertOk(response);
List<DesCountry> countries = deserializeList(response.getBody());
org.junit.Assert.assertFalse(countries.isEmpty());
for(DesCountry country : countries) {
org.junit.Assert.assertEquals("washington d.c.", country.getCapital().toLowerCase());
}
}
@HttpTest(method = Method.GET, path = "/region/europe")
public void region() {
Assert.assertOk(response);
List<DesCountry> countries = deserializeList(response.getBody());
for(DesCountry country : countries) {
org.junit.Assert.assertEquals("europe", country.getRegion().toLowerCase());
}
}
@HttpTest(method = Method.GET, path = "/lang/et")
public void language() {
Assert.assertOk(response);
List<DesCountry> countries = deserializeList(response.getBody());
for(DesCountry country : countries) {
org.junit.Assert.assertTrue(country.getLanguages().contains("et"));
System.out.println(country.getName());
}
}
@HttpTest(method = Method.GET, path = "/alpha?codes=ar;be;fr;it")
public void alphaList() {
Assert.assertOk(response);
List<DesCountry> countries = deserializeList(response.getBody());
org.junit.Assert.assertFalse(countries.isEmpty());
org.junit.Assert.assertEquals(4, countries.size());
org.junit.Assert.assertEquals("AR", countries.get(0).getAlpha2Code());
org.junit.Assert.assertEquals("BE", countries.get(1).getAlpha2Code());
org.junit.Assert.assertEquals("FR", countries.get(2).getAlpha2Code());
org.junit.Assert.assertEquals("IT", countries.get(3).getAlpha2Code());
}
@HttpTest(method = Method.GET, path = "/name/russia")
public void name() {
Assert.assertOk(response);
List<DesCountry> countries = deserializeList(response.getBody());
org.junit.Assert.assertFalse(countries.isEmpty());
for(DesCountry c : countries) {
org.junit.Assert.assertEquals("Russia", c.getName());
}
}
@HttpTest(method = Method.GET, path = "/alpha/co")
public void getBorders() {
Assert.assertOk(response);
DesCountry country = deserialize(response.getBody());
org.junit.Assert.assertFalse(country == null);
List<String> bordercountry = country.getBorders();
org.junit.Assert.assertTrue(bordercountry.size() == 5);
Collection<String> c = new HashSet<String>();
c.add("BRA");
c.add("ECU");
c.add("PAN");
c.add("PER");
c.add("VEN");
org.junit.Assert.assertTrue(bordercountry.containsAll(c));
}
private DesCountry deserialize(String json) {
Gson gson = new Gson();
DesCountry country = gson.fromJson(json, DesCountry.class);
return country;
}
private List<DesCountry> deserializeList(String json) {
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<DesCountry>>() {}.getType();
List<DesCountry> countries = gson.fromJson(json, listType);
return countries;
}
}
|
package gov.nih.nci.cananolab.ui.protocol;
import gov.nih.nci.cananolab.dto.common.ProtocolFileBean;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException;
import gov.nih.nci.cananolab.service.common.FileService;
import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl;
import gov.nih.nci.cananolab.service.protocol.ProtocolService;
import gov.nih.nci.cananolab.service.protocol.impl.ProtocolServiceLocalImpl;
import gov.nih.nci.cananolab.service.protocol.impl.ProtocolServiceRemoteImpl;
import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction;
import gov.nih.nci.cananolab.ui.core.InitSetup;
import gov.nih.nci.cananolab.util.CaNanoLabComparators;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
/**
* Search protocol file and protocol
*
* @author pansu
*
*/
public class SearchProtocolAction extends BaseAnnotationAction {
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
HttpSession session = request.getSession();
UserBean user = (UserBean) session.getAttribute("user");
DynaValidatorForm theForm = (DynaValidatorForm) form;
String fileTitle = (String) theForm.get("fileTitle");
String protocolType = (String) theForm.get("protocolType");
String protocolName = (String) theForm.get("protocolName");
String[] searchLocations = new String[0];
if (theForm.get("searchLocations") != null) {
searchLocations = (String[]) theForm.getStrings("searchLocations");
} else {
String gridNodeHostStr = (String) request
.getParameter("searchLocations");
if (gridNodeHostStr != null) {
searchLocations = gridNodeHostStr.split("~");
}
}
List<ProtocolFileBean> foundProtocolFiles = new ArrayList<ProtocolFileBean>();
ProtocolService service = null;
for (String location : searchLocations) {
if (location.equals("local")) {
service = new ProtocolServiceLocalImpl();
} else {
String serviceUrl = InitSetup.getInstance().getGridServiceUrl(
request, location);
service = new ProtocolServiceRemoteImpl(serviceUrl);
}
List<ProtocolFileBean> protocolFiles = service.findProtocolFilesBy(
protocolType, protocolName, fileTitle);
for (ProtocolFileBean protocolFile : protocolFiles) {
protocolFile.setLocation(location);
}
if (location.equals("local")) {
List<ProtocolFileBean> filteredProtocolFiles = new ArrayList<ProtocolFileBean>();
// retrieve visibility
FileService fileService = new FileServiceLocalImpl();
for (ProtocolFileBean protocolFile : protocolFiles) {
fileService.retrieveVisibility(protocolFile, user);
if (!protocolFile.isHidden()) {
filteredProtocolFiles.add(protocolFile);
}
}
foundProtocolFiles.addAll(filteredProtocolFiles);
} else {
foundProtocolFiles.addAll(protocolFiles);
}
}
if (foundProtocolFiles != null && !foundProtocolFiles.isEmpty()) {
Collections
.sort(
foundProtocolFiles,
new CaNanoLabComparators.ProtocolFileBeanNameVersionComparator());
request.getSession().setAttribute("protocolFiles",
foundProtocolFiles);
forward = mapping.findForward("success");
} else {
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage(
"message.searchProtocol.noresult");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
forward = mapping.getInputForward();
}
return forward;
}
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
InitProtocolSetup.getInstance().setProtocolDropdowns(request);
String gridNodeHostStr = (String) request
.getParameter("searchLocations");
if (gridNodeHostStr != null && gridNodeHostStr.length() > 0) {
String[] selectedLocations = gridNodeHostStr.split("~");
DynaValidatorForm theForm = (DynaValidatorForm) form;
theForm.set("searchLocations", selectedLocations);
}
return mapping.getInputForward();
}
public boolean loginRequired() {
return false;
}
public boolean canUserExecute(UserBean user)
throws CaNanoLabSecurityException {
return true;
}
}
|
package org.jivesoftware.messenger.handler;
import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.disco.ServerFeaturesProvider;
import org.jivesoftware.messenger.roster.Roster;
import org.jivesoftware.messenger.roster.RosterItem;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.UserManager;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Implements the TYPE_IQ jabber:iq:roster protocol. Clients
* use this protocol to retrieve, update, and rosterMonitor roster
* entries (buddy lists). The server manages the basics of
* roster subscriptions and roster updates based on presence
* and iq:roster packets, while the client maintains the user
* interface aspects of rosters such as organizing roster
* entries into groups.
* <p/>
* A 'get' query retrieves a snapshot of the roster.
* A 'set' query updates the roster (typically with new group info).
* The server sends 'set' updates asynchronously when roster
* entries change status.
* <p/>
* Currently an empty implementation to allow usage with normal
* clients. Future implementation needed.
* <p/>
* <h2>Assumptions</h2>
* This handler assumes that the request is addressed to the server.
* An appropriate TYPE_IQ tag matcher should be placed in front of this
* one to route TYPE_IQ requests not addressed to the server to
* another channel (probably for direct delivery to the recipient).
* <p/>
* <h2>Warning</h2>
* There should be a way of determining whether a session has
* authorization to access this feature. I'm not sure it is a good
* idea to do authorization in each handler. It would be nice if
* the framework could assert authorization policies across channels.
*
* @author Iain Shigeoka
*/
public class IQRosterHandler extends IQHandler implements ServerFeaturesProvider {
private IQHandlerInfo info;
private UserManager userManager;
private XMPPServer localServer;
private SessionManager sessionManager;
private PacketRouter router;
public IQRosterHandler() {
super("XMPP Roster Handler");
info = new IQHandlerInfo("query", "jabber:iq:roster");
}
/**
* Handles all roster queries. There are two major types of queries:
*
* <ul>
* <li>Roster remove - A forced removal of items from a roster. Roster
* removals are the only roster queries allowed to
* directly affect the roster from another user.
* </li>
* <li>Roster management - A local user looking up or updating their
* roster.
* </li>
* </ul>
*
* @param packet The update packet
* @return The reply or null if no reply
*/
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
try {
IQ returnPacket = null;
org.xmpp.packet.Roster roster = (org.xmpp.packet.Roster)packet;
JID recipientJID = packet.getTo();
// The packet is bound for the server and must be roster management
if (recipientJID == null || recipientJID.getNode() == null) {
returnPacket = manageRoster(roster);
}
// The packet must be a roster removal from a foreign domain user.
else {
removeRosterItem(roster);
}
return returnPacket;
}
catch (SharedGroupException e) {
IQ result = IQ.createResultIQ(packet);
result.setError(PacketError.Condition.not_acceptable);
return result;
}
catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
return null;
}
/**
* Remove a roster item. At this stage, this is recipient who has received
* a roster update. We must check that it is a removal, and if so, remove
* the roster item based on the sender's id rather than what is in the item
* listing itself.
*
* @param packet The packet suspected of containing a roster removal
*/
private void removeRosterItem(org.xmpp.packet.Roster packet) throws UnauthorizedException,
SharedGroupException {
JID recipientJID = packet.getTo();
JID senderJID = packet.getFrom();
try {
for (org.xmpp.packet.Roster.Item packetItem : packet.getItems()) {
if (packetItem.getSubscription() == org.xmpp.packet.Roster.Subscription.remove) {
Roster roster = userManager.getUser(recipientJID.getNode()).getRoster();
RosterItem item = roster.getRosterItem(senderJID);
roster.deleteRosterItem(senderJID, true);
item.setSubStatus(RosterItem.SUB_REMOVE);
item.setSubStatus(RosterItem.SUB_NONE);
Packet itemPacket = packet.createCopy();
sessionManager.userBroadcast(recipientJID.getNode(), itemPacket);
}
}
}
catch (UserNotFoundException e) {
throw new UnauthorizedException(e);
}
}
/**
* The packet is a typical 'set' or 'get' update targeted at the server.
* Notice that the set could be a roster removal in which case we have to
* generate a local roster removal update as well as a new roster removal
* to send to the the roster item's owner.
*
* @param packet The packet that triggered this update
* @return Either a response to the roster update or null if the packet is corrupt and the session was closed down
*/
private IQ manageRoster(org.xmpp.packet.Roster packet) throws UnauthorizedException,
UserAlreadyExistsException, SharedGroupException {
IQ returnPacket = null;
ClientSession session = sessionManager.getSession(packet.getFrom());
IQ.Type type = packet.getType();
try {
User sessionUser = userManager.getUser(session.getUsername());
Roster cachedRoster = sessionUser.getRoster();
if (IQ.Type.get == type) {
returnPacket = cachedRoster.getReset();
returnPacket.setType(IQ.Type.result);
returnPacket.setTo(session.getAddress());
returnPacket.setID(packet.getID());
// Force delivery of the response because we need to trigger
// a presence probe from all contacts
deliverer.deliver(returnPacket);
returnPacket = null;
}
else if (IQ.Type.set == type) {
for (org.xmpp.packet.Roster.Item item : packet.getItems()) {
if (item.getSubscription() == org.xmpp.packet.Roster.Subscription.remove) {
removeItem(cachedRoster, packet.getFrom(), item);
}
else {
if (cachedRoster.isRosterItem(item.getJID())) {
// existing item
RosterItem cachedItem = cachedRoster.getRosterItem(item.getJID());
cachedItem.setAsCopyOf(item);
cachedRoster.updateRosterItem(cachedItem);
}
else {
// new item
cachedRoster.createRosterItem(item);
}
}
}
returnPacket = IQ.createResultIQ(packet);
}
}
catch (UserNotFoundException e) {
throw new UnauthorizedException(e);
}
return returnPacket;
}
/**
* Remove the roster item from the sender's roster (and possibly the recipient's).
* Actual roster removal is done in the removeItem(Roster,RosterItem) method.
*
* @param roster The sender's roster.
* @param sender The JID of the sender of the removal request
* @param item The removal item element
*/
private void removeItem(org.jivesoftware.messenger.roster.Roster roster, JID sender,
org.xmpp.packet.Roster.Item item) throws SharedGroupException {
JID recipient = item.getJID();
// Remove recipient from the sender's roster
roster.deleteRosterItem(item.getJID(), true);
// Forward set packet to the subscriber
if (localServer.isLocal(recipient)) { // Recipient is local so let's handle it here
try {
Roster recipientRoster = userManager.getUser(recipient.getNode()).getRoster();
recipientRoster.deleteRosterItem(sender, true);
}
catch (UserNotFoundException e) {
}
}
else {
// Recipient is remote so we just forward the packet to them
String serverDomain = localServer.getServerInfo().getName();
// Check if the recipient may be hosted by this server
if (!recipient.getDomain().contains(serverDomain)) {
// TODO Implete when s2s is implemented
}
else {
Packet removePacket = createRemoveForward(sender, recipient);
router.route(removePacket);
}
}
}
/**
* Creates a forwarded removal packet.
*
* @param from The sender address to use
* @param to The recipient address to use
* @return The forwarded packet generated
*/
private Packet createRemoveForward(JID from, JID to) {
org.xmpp.packet.Roster response = new org.xmpp.packet.Roster(IQ.Type.set);
response.setFrom(from);
response.setTo(to);
response.addItem(from, org.xmpp.packet.Roster.Subscription.remove);
return response;
}
public void initialize(XMPPServer server) {
super.initialize(server);
localServer = server;
userManager = server.getUserManager();
router = server.getPacketRouter();
sessionManager = server.getSessionManager();
}
public IQHandlerInfo getInfo() {
return info;
}
public Iterator getFeatures() {
ArrayList features = new ArrayList();
features.add("jabber:iq:roster");
return features.iterator();
}
}
|
package gov.nih.nci.rembrandt.web.struts.action;
import gov.nih.nci.caarray.domain.file.FileType;
import gov.nih.nci.caarray.services.ServerConnectionException;
import gov.nih.nci.caintegrator.application.download.caarray.CaArrayFileDownloadManager;
import gov.nih.nci.caintegrator.application.lists.ListItem;
import gov.nih.nci.caintegrator.application.lists.UserListBeanHelper;
import gov.nih.nci.caintegrator.application.zip.FileNameGenerator;
import gov.nih.nci.caintegrator.dto.de.InstitutionDE;
import gov.nih.nci.rembrandt.download.caarray.RembrandtCaArrayFileDownloadManager;
import gov.nih.nci.rembrandt.dto.lookup.DownloadFileLookup;
import gov.nih.nci.rembrandt.dto.lookup.LookupManager;
import gov.nih.nci.rembrandt.web.helper.GroupRetriever;
import gov.nih.nci.rembrandt.web.helper.InsitutionAccessHelper;
import gov.nih.nci.rembrandt.web.struts.form.DownloadForm;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.security.auth.login.LoginException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.util.LabelValueBean;
public class DownloadAction extends DispatchAction {
private static Logger logger = Logger.getLogger(RefineQueryAction.class);
private CaArrayFileDownloadManager rbtCaArrayFileDownloadManager;
public ActionForward setup(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
//prepopulate the fields for BRB downloads
List fileList = LookupManager.getDownloadBRBFileList();
if (fileList == null || fileList.isEmpty()) {
request.setAttribute("downloadFileList", new ArrayList());
return mapping.findForward("success");
}
List<DownloadFileLookup> downloadFileList = new ArrayList<DownloadFileLookup>();
Collection<InstitutionDE> collection = InsitutionAccessHelper.getInsititutionCollection(request.getSession());
for (int i = 0; i < fileList.size(); i++){
DownloadFileLookup lookup = (DownloadFileLookup)fileList.get(i);
if (lookup.getAccessCode().equals(new Long(8))){
downloadFileList.add(lookup);
continue;
}
for (Iterator it = collection.iterator(); it.hasNext();){
InstitutionDE de = (InstitutionDE)it.next();
if (lookup.getAccessCode().equals((Long)de.getValue())){
downloadFileList.add(lookup);
}
}
}
request.getSession().setAttribute("downloadFileList", downloadFileList);
//prepopulate the fields for caArray
GroupRetriever groupRetriever = new GroupRetriever();
List<LabelValueBean> al = new ArrayList<LabelValueBean>();
al.addAll(groupRetriever.getClinicalGroupsCollectionNoPath(request.getSession()));
//specifically remove only these values, not to effect the groupRetriever
// LabelValueBean tmp = new LabelValueBean("UNKNOWN", "UNKNOWN");
// al.remove(tmp);
// tmp = new LabelValueBean("ALL", "ALL");
// al.remove(tmp);
// tmp = new LabelValueBean("NON_TUMOR", "NON_TUMOR");
// al.remove(tmp);
request.getSession().setAttribute("sampleGroupsList", al);
return mapping.findForward("success");
}
public ActionForward caarray(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
try {
rbtCaArrayFileDownloadManager = RembrandtCaArrayFileDownloadManager.getInstance();
} catch (MalformedURLException e) {
logger.error(new IllegalStateException("caArray URL error" ));
logger.error(e.getMessage());
logger.error(e);
} catch (LoginException e) {
logger.error(new IllegalStateException("caArray username/pwd error" ));
logger.error(e.getMessage());
logger.error(e);
} catch (ServerConnectionException e) {
logger.error(new IllegalStateException("caArray server connecrtion error" ));
logger.error(e.getMessage());
logger.error(e);
}
//Necessary for cache clean up
request.getSession().setAttribute(CaArrayFileDownloadManager.ZIP_FILE_PATH,RembrandtCaArrayFileDownloadManager.getInstance().getOutputZipDirectory());
DownloadForm dlForm = (DownloadForm)form;
String groupNameList = dlForm.getGroupNameCompare();
UserListBeanHelper helper = new UserListBeanHelper(request.getSession().getId());
Set<String> patientIdset = new HashSet<String>();
List<ListItem> listItemts = helper.getUserList(groupNameList).getListItems();
List<String> specimenNames = null;
for (ListItem item : listItemts) {
patientIdset.add(item.getName());
}
if(patientIdset != null && patientIdset.size()>0) {
// need to convert pt dids to the specimen ids
specimenNames = LookupManager.getSpecimenNames(patientIdset);
}// end of if
String tempName = groupNameList.toLowerCase();
tempName = FileNameGenerator.generateUniqueFileName(tempName);
String taskId = tempName ;
FileType type = null;
if (dlForm.getFileType().equals("CEL"))
type = FileType.AFFYMETRIX_CEL;
else if (dlForm.getFileType().equals("CHP"))
type = FileType.AFFYMETRIX_CHP;
rbtCaArrayFileDownloadManager.executeDownloadStrategy(
request.getSession().getId(),
taskId,
tempName + ".zip",
specimenNames,
type);
return mapping.findForward("success");
}
public ActionForward download(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
String dir = System.getProperty(RembrandtCaArrayFileDownloadManager.OUTPUT_ZIP_DIR);
String fileName = request.getParameter("file");
String filePath = dir + "/"+ fileName;
final ServletOutputStream out = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader( "Content-Disposition", "attachment; filename=\"" + fileName + "\"" );
File file = null;
try {
file = new File(filePath);
response.setContentLength( (int)file.length() );
BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
is.close();
out.close();
}catch (IOException ioe){
logger.error("IO exception in sending file " + file.toString() + ioe.getMessage());
}
return null;
}
}
|
package alluxio.collections;
import com.google.common.base.Preconditions;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.concurrent.ThreadSafe;
/**
* A set of objects that are indexed and thus can be queried by specific fields of the object.
* Different {@link IndexedSet} instances may specify different fields to index. The field type
* must be comparable. The field value must not be changed after an object is added to the set,
* otherwise, behavior for all operations is not specified.
*
* <p>
* Example usage:
*
* We have a set of puppies:
* <pre>
* class Puppy {
* private final String mName;
* private final long mId;
*
* public Puppy(String name, long id) {
* mName = name;
* mId = id;
* }
*
* public String name() {
* return mName;
* }
*
* public long id() {
* return mId;
* }
* }
* </pre>
*
* We want to be able to retrieve the set of puppies via a puppy's id or name, one way is to have
* two maps like {@code Map<String, Puppy> nameToPuppy} and {@code Map<Long, Puppy> idToPuppy},
* another way is to use a single instance of {@link IndexedSet}!
*
* First, define the fields to be indexed:
* <pre>
* FieldIndex<Puppy> idIndex = new FieldIndex<Puppy> {
* {@literal @Override}
* Object getFieldValue(Puppy o) {
* return o.id();
* }
* }
*
* FieldIndex<Puppy> nameIndex = new FieldIndex<Puppy> {
* {@literal @Override}
* Object getFieldValue(Puppy o) {
* return o.name();
* }
* }
* </pre>
*
* Then create an {@link IndexedSet} and add puppies:
* <pre>
* IndexedSet<Puppy> puppies = new IndexedSet<Puppy>(idIndex, nameIndex);
* puppies.add(new Puppy("sweet", 0));
* puppies.add(new Puppy("heart", 1));
* </pre>
*
* Then retrieve the puppy named sweet:
* <pre>
* Puppy sweet = puppies.getFirstByField(nameIndex, "sweet");
* </pre>
* and retrieve the puppy with id 1:
* <pre>
* Puppy heart = puppies.getFirstByField(idIndex, 1L);
* </pre>
*
* @param <T> the type of object
*/
@ThreadSafe
public class IndexedSet<T> implements Iterable<T> {
/** All objects in the set. */
private final ConcurrentHashSet<T> mObjects = new ConcurrentHashSet<>(1024, 0.75f, 32);
/**
* Map from {@link FieldIndex} to the index. An index is a map from index value to set of
* objects with that index value.
*/
private final Map<FieldIndex<T>, ConcurrentHashMap<Object, ConcurrentHashSet<T>>> mIndexMap;
/**
* An interface representing an index for this {@link IndexedSet}, each index for this set must
* implement the interface to define how to get the value of the field chosen as the index. Users
* must use the same instance of the implementation of this interface as the parameter in all
* methods of {@link IndexedSet} to represent the same index.
*
* @param <T> type of objects in this {@link IndexedSet}
*/
public interface FieldIndex<T> {
/**
* Gets the value of the field that serves as index.
*
* @param o the instance to get the field value from
* @return the field value, which is just an Object
*/
Object getFieldValue(T o);
}
/**
* Constructs a new {@link IndexedSet} instance with at least one field as the index.
*
* @param field at least one field is needed to index the set of objects
* @param otherFields other fields to index the set
*/
public IndexedSet(FieldIndex<T> field, FieldIndex<T>... otherFields) {
Map<FieldIndex<T>, ConcurrentHashMap<Object, ConcurrentHashSet<T>>> indexMap =
new HashMap<>(otherFields.length + 1);
indexMap.put(field, new ConcurrentHashMap<Object, ConcurrentHashSet<T>>());
for (int i = 1; i <= otherFields.length; i++) {
indexMap.put(otherFields[i - 1], new ConcurrentHashMap<Object, ConcurrentHashSet<T>>());
}
// read only, so it is thread safe and allows concurrent access.
mIndexMap = Collections.unmodifiableMap(indexMap);
}
/**
* Removes all the entries in this set.
*/
// TODO(gpang): clear() does not play well with other concurrent operations. Currently, it is
// ok, since the only use of clear() is a context without concurrent access.
public void clear() {
// Clear the indexes first, so objects cannot be found via index.
for (Map<Object, ConcurrentHashSet<T>> mapping : mIndexMap.values()) {
mapping.clear();
}
// Remove all the objects.
mObjects.clear();
}
/**
* Adds an object o to the set if there is no other object o2 such that
* {@code (o == null ? o2 == null : o.equals(o2))}. If this set already contains the object, the
* call leaves the set unchanged.
*
* @param object the object to add
* @return true if the object is successfully added to all indexes, otherwise false
*/
public boolean add(T object) {
Preconditions.checkNotNull(object);
synchronized (object) {
if (!mObjects.addIfAbsent(object)) {
// This object is already added, possibly by another concurrent thread.
return true;
}
// Update the indexes.
for (Map.Entry<FieldIndex<T>, ConcurrentHashMap<Object, ConcurrentHashSet<T>>> fieldInfo :
mIndexMap
.entrySet()) {
// For this field, retrieve the value to index
Object fieldValue = fieldInfo.getKey().getFieldValue(object);
// Get the index for this field
ConcurrentHashMap<Object, ConcurrentHashSet<T>> index = fieldInfo.getValue();
ConcurrentHashSet<T> objSet = index.get(fieldValue);
while (objSet == null) {
// TODO(gpang): without clear(), this while-clause can be an if-clause.
index.putIfAbsent(fieldValue, new ConcurrentHashSet<T>());
objSet = index.get(fieldValue);
}
if (!objSet.addIfAbsent(object)) {
// this call can never return false because:
// a. the second-level sets in the indices are all
// {@link java.util.Set} instances of unbounded space
// b. We have already successfully added object on mObjects,
// meaning that it cannot be already in any of the sets.
// (mObjects is exactly the set-union of all the other second-level sets)
throw new IllegalStateException("Indexed Set is in an illegal state");
}
}
}
return true;
}
/**
* Returns an iterator over the elements in this set. The elements are returned in no particular
* order. It is to implement {@link Iterable} so that users can foreach the {@link IndexedSet}
* directly.
*
* Note that the behaviour of the iterator is unspecified if the underlying collection is
* modified while a thread is going through the iterator.
*
* @return an iterator over the elements in this {@link IndexedSet}
*/
@Override
public Iterator<T> iterator() {
return new IndexedSetIterator();
}
/**
* Specialized iterator for {@link IndexedSet}.
*
* This is needed to support consistent removal from the set and the indices.
*/
private class IndexedSetIterator implements Iterator<T> {
private final Iterator<T> mSetIterator;
private T mObject;
public IndexedSetIterator() {
mSetIterator = mObjects.iterator();
mObject = null;
}
@Override
public boolean hasNext() {
return mSetIterator.hasNext();
}
@Override
public T next() {
final T next = mSetIterator.next();
mObject = next;
return next;
}
@Override
public void remove() {
if (mObject != null) {
IndexedSet.this.remove(mObject);
mObject = null;
} else {
throw new IllegalStateException("next() was not called before remove()");
}
}
}
/**
* Whether there is an object with the specified field value in the set.
*
* @param index the field index
* @param value the field value
* @return true if there is one such object, otherwise false
*/
public boolean contains(FieldIndex<T> index, Object value) {
ConcurrentHashSet<T> set = getByFieldInternal(index, value);
return set != null && !set.isEmpty();
}
/**
* Gets a subset of objects with the specified field value. If there is no object with the
* specified field value, a newly created empty set is returned. Otherwise, the returned set is
* backed up by an internal set, so changes in internal set will be reflected in returned set and
* vice-versa.
*
* @param index the field index
* @param value the field value to be satisfied
* @return the set of objects or an empty set if no such object exists
*/
public Set<T> getByField(FieldIndex<T> index, Object value) {
Set<T> set = getByFieldInternal(index, value);
return set == null ? new HashSet<T>() : set;
}
/**
* Gets the first object from the set of objects with the specified field value.
*
* @param index the field index
* @param value the field value
* @return the object or null if there is no such object
*/
public T getFirstByField(FieldIndex<T> index, Object value) {
Set<T> all = getByFieldInternal(index, value);
try {
return all == null || !all.iterator().hasNext() ? null : all.iterator().next();
} catch (NoSuchElementException e) {
return null;
}
}
/**
* Removes an object from the set.
*
* @param object the object to remove
* @return true if the object is in the set and removed successfully, otherwise false
*/
public boolean remove(T object) {
synchronized (object) {
if (mObjects.contains(object)) {
removeFromIndices(object);
return mObjects.remove(object);
} else {
return false;
}
}
}
/**
* Helper method that removes an object from the indices.
*
* @param object the object to be removed
*/
private void removeFromIndices(T object) {
for (Map.Entry<FieldIndex<T>, ConcurrentHashMap<Object, ConcurrentHashSet<T>>> fieldInfo :
mIndexMap.entrySet()) {
Object fieldValue = fieldInfo.getKey().getFieldValue(object);
ConcurrentHashMap<Object, ConcurrentHashSet<T>> index = fieldInfo.getValue();
ConcurrentHashSet<T> objSet = index.get(fieldValue);
if (objSet != null) {
objSet.remove(object);
}
}
}
/**
* Removes the subset of objects with the specified field value.
*
* @param index the field index
* @param value the field value
* @return the number of objects removed
*/
public int removeByField(FieldIndex<T> index, Object value) {
ConcurrentHashSet<T> toRemove = getByFieldInternal(index, value);
if (toRemove == null) {
return 0;
}
int removed = 0;
for (T o : toRemove) {
if (remove(o)) {
removed++;
}
}
return removed;
}
/**
* @return the number of objects in this indexed set (O(1) time)
*/
public int size() {
return mObjects.size();
}
/**
* Gets the set of objects with the specified field value - internal function.
*
* @param index the field index
* @param value the field value
* @return the set of objects with the specified field value
*/
private ConcurrentHashSet<T> getByFieldInternal(FieldIndex<T> index, Object value) {
return mIndexMap.get(index).get(value);
}
}
|
package edu.brandeis.cs.steele.wn;
import java.util.*;
import static edu.brandeis.cs.steele.wn.PointerTypeFlag.*;
public enum PointerType {
// Nouns and Verbs
HYPERNYM("hypernym", "@", 2, N | V, "Hypernyms (%s is a kind of ...)", "Hypernyms (%s is one way to ...)"),
/** aka "instance of" */
INSTANCE_HYPERNYM("instance hypernym", "@i", 38, N | V, "Instance Hypernyms (%s is an instance of ...)"),
HYPONYM("hyponym", "~", 3, N | V, "Hyponyms (... is a kind of %s)", "Troponyms (... are particular ways to %s)"),
/** aka "instances" */
INSTANCE_HYPONYM("instance hyponym", "~i", 39, N | V, "Instance Hyponyms (... is an instance of %s)"),
/** aka "derivation" */
DERIVATIONALLY_RELATED("derivationally related", "+", 20, N | V, "Derivationally related forms"),
// Nouns and Adjectives
//FIXME "=" or "\=" ?
ATTRIBUTE("attribute", "=", 18, N | ADJ, "Attribute (%s is a value of ...)"),
/** aka "also see" */
SEE_ALSO("also see", "^", 16, N | ADJ | LEXICAL),
// Verbs
ENTAILMENT("entailment", "*", 4, V, "%s entails doing ..."),
/** aka "cause to" */
CAUSE("cause", ">", 14, V, null, "%s causes ..."),
VERB_GROUP("verb group", "$", 19, V),
// Nouns
/**
* A word that names a part of a larger whole, aka "part name".
* Pure-virtual PointerType.
* @see PointerType#MEMBER_MERONYM
* @see PointerType#SUBSTANCE_MERONYM
* @see PointerType#PART_MERONYM
*/
MERONYM("meronym", "%" /* non-existent */, 12, N),
/** aka "is member". */
MEMBER_MERONYM("member meronym", "#m", 6, N, "Member Meronyms (... are members of %s)"),
/** aka "is stuff". */
SUBSTANCE_MERONYM("substance meronym", "#s", 7, N, "Substance Meronyms (... are substances of %s)"),
/** aka "is part". */
PART_MERONYM("part meronym", "#p", 8, N, "Part Meronyms (... are parts of %s)"),
/**
* A word that names the whole of which a given word is a part.
* Pure-virtual PointerType.
* @see PointerType#MEMBER_HOLONYM
* @see PointerType#SUBSTANCE_HOLONYM
* @see PointerType#PART_HOLONYM
*/
HOLONYM("holonym", "#" /* non-existent */, 13, N),
/** aka "has member". */
MEMBER_HOLONYM("member holonym", "%m", 9, N, "Member Holonyms (%s is a member of ...)"),
/** aka "has stuff". */
SUBSTANCE_HOLONYM("substance holonym", "%s", 10, N, "Substance Holonyms (%s is a substance of ...)"),
/** aka "has part". */
PART_HOLONYM("part holonym", "%p", 11, N, "Part Holonyms (%s is a part of ...)"),
/** aka "topic term" */
MEMBER_OF_TOPIC_DOMAIN("Member of TOPIC domain", "-c", 35, N),
/** aka "usage term" */
MEMBER_OF_USAGE_DOMAIN("Member of USAGE domain", "-u", 36, N),
/** aka "regiona term" */
MEMBER_OF_REGION_DOMAIN("Member of REGION domain", "-r", 37, N),
// Adjectives
SIMILAR_TO("similar to", "&", 5, ADJ),
PARTICIPLE_OF("participle of", "<", 15, ADJ | LEXICAL),
/** aka "pertains to noun" */
PERTAINYM("pertainym", "\\", 17, ADJ | LEXICAL, "... are nouns related to %s"),
// Adverbs
/** aka "derived from adjective" */
DERIVED("derived from", "\\", 17, ADV), // from adjective
// All parts of speech
ANTONYM("antonym", "!", 1, N | V | ADJ | ADV | LEXICAL, "Antonyms (... is the opposite of %s)"),
/** aka "a topic/domain" */
DOMAIN_OF_TOPIC("Domain of synset - TOPIC", ";c", 32, N | V | ADJ | ADV),
/** aka "a usage type" */
DOMAIN_OF_USAGE("Domain of synset - USAGE", ";u", 33, N | V | ADJ | ADV),
/** aka "a region" */
DOMAIN_OF_REGION("Domain of synset - REGION", ";r", 34, N | V | ADJ | ADV),
/**
* aka "class"<br>
* Pure-virtual PointerType.
* @see PointerType#MEMBER_OF_TOPIC_DOMAIN
* @see PointerType#MEMBER_OF_REGION_DOMAIN
* @see PointerType#MEMBER_OF_USAGE_DOMAIN
*/
DOMAIN_MEMBER("Domain Member", "-", 22, N | V | ADJ | ADV),
/**
* aka "classification"<br>
* Pure-virtual PointerType.
* @see PointerType#DOMAIN_OF_TOPIC
* @see PointerType#DOMAIN_OF_REGION
* @see PointerType#DOMAIN_OF_USAGE
*/
DOMAIN("Domain", ";", 21, N | V | ADJ | ADV);
private static final int[] POS_MASK = {N, V, ADJ, ADV, SAT_ADJ, LEXICAL};
/** A list of all <code>PointerType</code>s. */
public static final EnumSet<PointerType> TYPES = EnumSet.of(
ANTONYM, HYPERNYM, HYPONYM, ATTRIBUTE, SEE_ALSO,
ENTAILMENT, CAUSE, VERB_GROUP,
MEMBER_MERONYM, SUBSTANCE_MERONYM, PART_MERONYM,
MEMBER_HOLONYM, SUBSTANCE_HOLONYM, PART_HOLONYM,
SIMILAR_TO, PARTICIPLE_OF, PERTAINYM, DERIVED,
DOMAIN_OF_TOPIC, DOMAIN_OF_USAGE, DOMAIN_OF_REGION,
MEMBER_OF_TOPIC_DOMAIN, MEMBER_OF_REGION_DOMAIN, MEMBER_OF_USAGE_DOMAIN,
DERIVATIONALLY_RELATED,
INSTANCE_HYPERNYM, INSTANCE_HYPONYM
);
//XXX this seems to indicate DOMAIN implies DOMAIN_PART
//XXX SAT_ADJ seems to be an index-only POS
public static final Set<PointerType> INDEX_ONLY = EnumSet.of(DOMAIN_MEMBER, DOMAIN, HOLONYM, MERONYM);
static {
assert EnumSet.complementOf(TYPES).equals(INDEX_ONLY);
}
static private void setSymmetric(final PointerType a, final PointerType b) {
a.symmetricType = b;
b.symmetricType = a;
}
/**
* A "pure-virtual" concept (ie one that cannot be directly instantiated).
* Index-only pointer types are used only for parsing index file records.
* <code>isIndexOnly</code> <code>PointerType</code>s are not used to determine relationships between words.
* @param pointerType
* @return <code>true</code> if the <code>pointerType</code> is an index-only pointer type, otherwise <code>false</code>.
*/
public static boolean isIndexOnly(final PointerType pointerType) {
return INDEX_ONLY.contains(pointerType);
}
static {
setSymmetric(ANTONYM, ANTONYM);
setSymmetric(HYPERNYM, HYPONYM);
setSymmetric(INSTANCE_HYPERNYM, INSTANCE_HYPONYM);
setSymmetric(MEMBER_MERONYM, MEMBER_HOLONYM);
setSymmetric(SUBSTANCE_MERONYM, SUBSTANCE_HOLONYM);
setSymmetric(PART_MERONYM, PART_HOLONYM);
setSymmetric(SIMILAR_TO, SIMILAR_TO);
setSymmetric(ATTRIBUTE, ATTRIBUTE);
setSymmetric(DERIVATIONALLY_RELATED, DERIVATIONALLY_RELATED);
setSymmetric(DOMAIN_OF_TOPIC, MEMBER_OF_TOPIC_DOMAIN);
setSymmetric(DOMAIN_OF_REGION, MEMBER_OF_REGION_DOMAIN);
setSymmetric(DOMAIN_OF_USAGE, MEMBER_OF_USAGE_DOMAIN);
setSymmetric(DOMAIN_OF_TOPIC, DOMAIN_MEMBER);
setSymmetric(DOMAIN_OF_REGION, DOMAIN_MEMBER);
setSymmetric(DOMAIN_OF_USAGE, DOMAIN_MEMBER);
setSymmetric(VERB_GROUP, VERB_GROUP);
/**
* Some PointerTypes are "abstract/virtual/meta", though most are concrete.<br>
* "virtual" means has superTypes and/or subTypes.<br>
* Compare to "concrete" (isolated) and "pure virtual" (incomplete) types.<br>
* It does not make sense to search for a pure-virtual type.<br>
* <br>
* virtual:
* <ul>
* <li> Hyponym, Instance </li>
* <li> Hypernym, Instance </li>
* </ul>
* <br>
* pure-virtual:
* <ul>
* <li> Holonym:: Part, Member, Substance </li>
* <li> Meronym:: Part, Member, Substance </li>
*
* <li> Domain:: {Member, Domain} X {Topic, Region, Usage} </li>
* </ul>
*
* Adjective - not sure how this fits in
* Similar To
*
* Also see -- verb only ?
*/
// e.g. "Bill Clinton" has instance hypernym "president"
// which in turn has normal hypernyms
HYPERNYM.superTypes = Arrays.asList(INSTANCE_HYPERNYM);
// e.g. "president"#2 (* the Synset) has instance hyponyms ("George Washington", ...) AND
// normal hyponyms ("chief of state", ...). Note that while "president"#2 also
// has normal hyponyms, "President of the United States" does NOT since
// it is more lexically specified.
// FIXME this example seems to show a bad, unneeded asymmetry
HYPONYM.subTypes = Arrays.asList(INSTANCE_HYPONYM);
MERONYM.subTypes = Arrays.asList(MEMBER_MERONYM, PART_MERONYM, SUBSTANCE_MERONYM);
// don't assign superTypes since MERONYM is pure-virtual
HOLONYM.subTypes = Arrays.asList(MEMBER_HOLONYM, PART_HOLONYM, SUBSTANCE_HOLONYM);
// don't assign superTypes since HOLONYM is pure-virtual
DOMAIN.subTypes = Arrays.asList(DOMAIN_OF_TOPIC, DOMAIN_OF_REGION, DOMAIN_OF_USAGE);
// don't assign superTypes since DOMAIN is pure-virtual
}
private static final PointerType[] VALUES = values();
static PointerType fromOrdinal(final byte ordinal) {
return VALUES[ordinal];
}
/**
* @return the <code>PointerType</code> whose key matches <var>key</var>.
* @exception NoSuchElementException If <var>key</var> doesn't name any <code>PointerType</code>.
*/
public static PointerType parseKey(final CharSequence key) {
for (final PointerType pType : VALUES) {
if (pType.key.contentEquals(key)) {
return pType;
}
}
throw new NoSuchElementException("unknown link type " + key);
}
/*
* Instance Interface
*/
private final String label;
private final String longNounLabel;
private final String longVerbLabel;
private final String key;
private final int value;
private final int flags;
private final String toString;
private PointerType symmetricType;
private List<PointerType> subTypes;
private List<PointerType> superTypes;
PointerType(final String label, final String key, final int value, final int flags) {
this(label, key, value, flags, null, null);
}
PointerType(final String label, final String key, final int value, final int flags, final String longNounLabel) {
this(label, key, value, flags, longNounLabel, null);
}
PointerType(final String label, final String key, final int value, final int flags, final String longNounLabel, final String longVerbLabel) {
this.label = label;
this.key = key;
this.value = value;
this.flags = flags;
this.toString = getLabel()+" "+getKey();
if (longNounLabel != null) {
this.longNounLabel = longNounLabel;
} else {
this.longNounLabel = label;
}
if (longVerbLabel != null) {
this.longVerbLabel = longVerbLabel;
} else {
if (longNounLabel != null) {
this.longVerbLabel = longNounLabel;
} else {
this.longVerbLabel = label;
}
}
this.superTypes = Collections.emptyList();
this.subTypes = Collections.emptyList();
//XXX System.err.println(this+" longNounLabel: "+this.longNounLabel+" longVerbLabel: "+this.longVerbLabel+" label: "+this.label);
}
@Override public String toString() {
return toString;
}
/**
* @return human-readable label.
*/
public String getLabel() {
return label;
}
/**
* @return labels with <code>"%s"</code> variables which can be substituted
* for to create textual content of WordNet interfaces.
*/
public String getFormatLabel(final POS pos) {
switch(pos) {
case NOUN: return longNounLabel;
case VERB: return longVerbLabel;
default: return longNounLabel;
}
}
public String getKey() {
return this.key;
}
/**
* Some <code>PointerType</code>s only apply to certain {@link POS}.
*/
public boolean appliesTo(final POS pos) {
return (flags & POS_MASK[pos.ordinal()]) != 0;
}
/**
* <code>type</code> is the opposite concept of <code>this</code>.
* For example <code>{@link PointerType#HYPERNYM}.symmetricTo({@link PointerType#HYPONYM}<code>).
*/
public boolean symmetricTo(final PointerType type) {
return symmetricType != null && symmetricType.equals(type);
}
public List<PointerType> getSuperTypes() {
return this.superTypes;
}
public List<PointerType> getSubTypes() {
return this.subTypes;
}
}
/**
* Flags for tagging a pointer type with the POS types it apples to.
* Separate class to allow PointerType enum constructor to reference it.
*/
class PointerTypeFlag {
static final int N = 1;
static final int V = 2;
static final int ADJ = 4;
static final int ADV = 8;
static final int SAT_ADJ = 16;
// special case indicator for lexical relations (those connecting specific WordSenses)
// rather than common case semantic relations which connect Synsets.
static final int LEXICAL = 32;
}
|
package hudson.model;
import hudson.search.Search;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Flavor;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.CheckForNull;
/**
* Data representation of the auto-completion candidates.
* <p>
* This object should be returned from your doAutoCompleteXYZ methods.
*
* @author Kohsuke Kawaguchi
*/
public class AutoCompletionCandidates implements HttpResponse {
private final List<String> values = new ArrayList<String>();
public AutoCompletionCandidates add(String v) {
values.add(v);
return this;
}
public AutoCompletionCandidates add(String... v) {
values.addAll(Arrays.asList(v));
return this;
}
/**
* Exposes the raw value, in case you want to modify {@link List} directly.
* @since 1.402
*/
public List<String> getValues() {
return values;
}
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object o) throws IOException, ServletException {
Search.Result r = new Search.Result();
for (String value : values) {
r.suggestions.add(new hudson.search.Search.Item(value));
}
rsp.serveExposedBean(req,r, Flavor.JSON);
}
/**
* Auto-completes possible job names.
*
* @param type
* Limit the auto-completion to the subtype of this type.
* @param value
* The value the user has typed in. Matched as a prefix.
* @param self
* The contextual item for which the auto-completion is provided to.
* For example, if you are configuring a job, this is the job being configured.
* @param container
* The nearby contextual {@link ItemGroup} to resolve relative job names from.
* @since 1.489
*/
public static <T extends Item> AutoCompletionCandidates ofJobNames(final Class<T> type, final String value, @CheckForNull Item self, ItemGroup container) {
if (self==container)
container = self.getParent();
return ofJobNames(type, value, container);
}
/**
* Auto-completes possible job names.
*
* @param type
* Limit the auto-completion to the subtype of this type.
* @param value
* The value the user has typed in. Matched as a prefix.
* @param container
* The nearby contextual {@link ItemGroup} to resolve relative job names from.
* @since 1.553
*/
public static <T extends Item> AutoCompletionCandidates ofJobNames(final Class<T> type, final String value, ItemGroup container) {
final AutoCompletionCandidates candidates = new AutoCompletionCandidates();
class Visitor extends ItemVisitor {
String prefix;
Visitor(String prefix) {
this.prefix = prefix;
}
@Override
public void onItem(Item i) {
String n = contextualNameOf(i);
if ((n.startsWith(value) || value.startsWith(n))
// 'foobar' is a valid candidate if the current value is 'foo'.
// Also, we need to visit 'foo' if the current value is 'foo/bar'
&& (value.length()>n.length() || !n.substring(value.length()).contains("/"))
// but 'foobar/zot' isn't if the current value is 'foo'
// we'll first show 'foobar' and then wait for the user to type '/' to show the rest
&& i.hasPermission(Item.READ)
) {
if (type.isInstance(i) && n.startsWith(value))
candidates.add(n);
// recurse
String oldPrefix = prefix;
prefix = n;
super.onItem(i);
prefix = oldPrefix;
}
}
private String contextualNameOf(Item i) {
if (prefix.endsWith("/") || prefix.length()==0)
return prefix+i.getName();
else
return prefix+'/'+i.getName();
}
}
if (container==null || container==Jenkins.getInstance()) {
new Visitor("").onItemGroup(Jenkins.getInstance());
} else {
new Visitor("").onItemGroup(container);
if (value.startsWith("/"))
new Visitor("/").onItemGroup(Jenkins.getInstance());
for ( String p="../"; value.startsWith(p); p+="../") {
container = ((Item)container).getParent();
new Visitor(p).onItemGroup(container);
}
}
return candidates;
}
}
|
package org.mskcc.cbio.portal.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringUtil
{
private static final Log log = LogFactory.getLog(SpringUtil.class);
private static AccessControl accessControl;
private static ApplicationContext context;
public static void setAccessControl(AccessControl accessControl) {
log.debug("Setting access control");
SpringUtil.accessControl = accessControl;
}
public static AccessControl getAccessControl()
{
return accessControl;
}
public static synchronized void initDataSource()
{
if (SpringUtil.context == null) {
context = new ClassPathXmlApplicationContext("classpath:applicationContext-business.xml");
}
}
/**
* setter to allow override by unit test classes (which run in different context, connecting
* to test DB).
*
* @param context
*/
public static void setApplicationContext(ApplicationContext context) {
SpringUtil.context = context;
}
}
|
package org.usergrid.tools;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.impl.DefaultPrettyPrinter;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author zznate
*/
public abstract class ExportingToolBase extends ToolBase {
protected Logger logger = LoggerFactory.getLogger(ExportingToolBase.class);
protected static File outputDir;
/** Output dir option: -outputDir */
protected static final String OUTPUT_DIR = "outputDir";
protected String baseOutputDirName = "export";
JsonFactory jsonFactory = new JsonFactory();
protected long startTime = System.currentTimeMillis();
@Override
@SuppressWarnings("static-access")
public Options createOptions() {
Options options = super.createOptions();
Option outputDir = OptionBuilder.hasArg()
.withDescription("output file name -outputDir")
.create(OUTPUT_DIR);
options.addOption(outputDir);
return options;
}
protected void prepareBaseOutputFileName(CommandLine line) {
boolean hasOutputDir = line.hasOption(OUTPUT_DIR);
if (hasOutputDir) {
baseOutputDirName = line.getOptionValue(OUTPUT_DIR);
}
}
/**
* Write the string onto the writer and check if verbose is enabled to log
* also an echo of what is being written to the writer.
*
* @param out
* PrintWriter
* @param content
* string to be written
*/
@SuppressWarnings("unused")
protected void writeOutput(PrintWriter out, String content) {
echo(content);
out.print(content);
}
protected File createOutputParentDir() {
return createDir(baseOutputDirName);
}
protected File createOutputFile(String type, String name) {
return new File(outputDir, prepareOutputFileName(type, name));
}
@SuppressWarnings("unused")
protected File createOutputFile(File parent, String type, String name) {
return new File(parent, prepareOutputFileName(type, name));
}
@SuppressWarnings("unused")
protected File createCollectionsDir(String applicationName) {
return createDir(outputDir, "application." + applicationName
+ ".collections");
}
protected File createDir(String dirName) {
return createDir(null, dirName);
}
protected File createDir(File parent, String dirName) {
File file = null;
if (parent == null) {
file = new File(dirName);
} else {
file = new File(parent, dirName);
}
boolean wasCreated = false;
if (file.exists() && file.isDirectory()) {
wasCreated = true;
} else {
wasCreated = file.mkdir();
}
if (!wasCreated) {
throw new RuntimeException("Unable to create directory:" + dirName);
}
return file;
}
/**
*
* @param type
* just a label such us: organization, application.
* @param name
* @return the file name concatenated with the type and the name of the
* collection
*/
protected String prepareOutputFileName(String type, String name) {
name = name.replace("/", PATH_REPLACEMENT);
// Add application and timestamp
StringBuilder str = new StringBuilder();
// str.append(baseOutputFileName);
// str.append(".");
str.append(type);
str.append(".");
str.append(name);
str.append(".");
str.append(startTime);
str.append(".json");
String outputFileName = str.toString();
logger.info("Creating output filename:" + outputFileName);
return outputFileName;
}
protected JsonGenerator getJsonGenerator(String outFile) throws IOException {
return getJsonGenerator(new File(outputDir,outFile));
}
protected JsonGenerator getJsonGenerator(File outFile) throws IOException {
PrintWriter out = new PrintWriter(outFile, "UTF-8");
JsonGenerator jg = jsonFactory.createJsonGenerator(out);
jg.setPrettyPrinter(new DefaultPrettyPrinter());
jg.setCodec(new ObjectMapper());
return jg;
}
}
|
package org.dozer.factory;
import org.dozer.AbstractDozerTest;
import org.dozer.MappingException;
import org.junit.Before;
import org.junit.Test;
/**
* @author Vincent Jassogne
*/
public class JAXBBeanFactoryTest extends AbstractDozerTest {
private JAXBBeanFactory factory;
@Before
public void setUp() throws Exception {
factory = new JAXBBeanFactory();
}
@Test
public void testCreateBeanForSimpleJaxbClass() {
Object obj = factory.createBean(null, null, "org.dozer.vo.jaxb.employee.EmployeeType");
assertNotNull("Object can not be null", obj);
assertEquals("org.dozer.vo.jaxb.employee.EmployeeType", obj.getClass().getName());
}
@Test(expected = MappingException.class)
public void testCreateBeanClassNotFoundException() {
factory.createBean(null, null, "ve.ve.DE");
}
@Test
public void testCreateBeanForInnerJaxbClass() {
Object obj = factory.createBean(null, null, "org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address");
assertNotNull(obj);
assertEquals("org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address", obj.getClass().getName());
}
@Test
public void testCreateBeanForNestedInnerJaxbClass() {
Object obj = factory.createBean(null, null, "org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address$State");
assertNotNull(obj);
assertEquals("org.dozer.vo.jaxb.employee.EmployeeWithInnerClass$Address$State", obj.getClass().getName());
}
}
|
// TODO: when no rewind - stop thread
package kg.apc.jmeter.modifiers;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import kg.apc.jmeter.EndOfFileException;
import kg.apc.jmeter.RuntimeEOFException;
import org.apache.commons.io.IOExceptionWithCause;
import org.apache.jmeter.engine.util.NoThreadClone;
import org.apache.jmeter.processor.PreProcessor;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.testelement.property.BooleanProperty;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
*
* @author undera
*/
public class RawRequestSourcePreProcessor
extends AbstractTestElement
implements PreProcessor, NoThreadClone {
public static final String regexp = "\\s";
private static final Logger log = LoggingManager.getLoggerForClass();
public static final String VARIABLE_NAME = "variable_name";
public static final String FILENAME = "filename";
public static final String REWIND = "rewind";
private FileChannel file;
private final ByteBuffer metaBuf = ByteBuffer.allocateDirect(1024);
private final ByteBuffer oneByte = ByteBuffer.allocateDirect(1);
public RawRequestSourcePreProcessor() {
super();
}
@Override
public synchronized void process() {
if (file == null) {
log.info("Creating file object: " + getFileName());
try {
file = new FileInputStream(getFileName()).getChannel();
} catch (FileNotFoundException ex) {
log.error(getFileName(), ex);
return;
}
}
String rawData;
try {
rawData = readNextChunk(getNextChunkSize());
} catch (EndOfFileException ex) {
if (getRewindOnEOF()) {
if (log.isDebugEnabled()) {
log.debug("Rewind file");
}
try {
file.position(0);
} catch (IOException ex1) {
log.error("Cannot rewind", ex1);
}
process();
return;
} else {
log.info("End of file reached: " + getFileName());
if (JMeterContextService.getContext().getThread() != null) {
JMeterContextService.getContext().getThread().stop();
}
throw new RuntimeEOFException("End of file reached", ex);
}
} catch (IOException ex) {
log.error("Error reading next chunk", ex);
throw new RuntimeException("Error reading next chunk", ex);
}
final JMeterVariables vars = JMeterContextService.getContext().getVariables();
if (vars != null) {
vars.put(getVarName(), rawData);
}
}
private synchronized String readNextChunk(int capacity)
throws IOException {
if (capacity == 0) {
throw new EndOfFileException("Zero chunk size, possibly end of file reached.");
}
ByteBuffer buf = ByteBuffer.allocateDirect(capacity);
byte[] dst = new byte[capacity];
int cnt = file.read(buf);
//log.debug("Read " + cnt);
if (cnt != capacity) {
throw new IOException("Expected chunk size (" + capacity + ") differs from read bytes count (" + cnt + ")");
}
buf.flip();
buf.get(dst);
if (log.isDebugEnabled()) {
log.debug("Chunk : " + new String(dst));
}
return new String(dst);
}
private int getNextChunkSize() throws IOException {
metaBuf.clear();
while (true) {
byte b = getOneByte();
if (b == 10 || b == 13) {
// if we have \r\n then skip \n
byte b2 = getOneByte();
if (b2 != 10) {
file.position(file.position() - 1);
}
// ignore newlines before length marker
if (metaBuf.position() > 0) {
break;
}
} else {
//if (log.isDebugEnabled()) log.debug("Read byte: "+b);
metaBuf.put(b);
}
}
//if (log.isDebugEnabled()) log.debug("Meta line: "+JMeterPluginsUtils.byteBufferToString(metaBuf));
byte[] bLine = new byte[metaBuf.position()];
metaBuf.rewind();
metaBuf.get(bLine);
String sLine = new String(bLine).trim();
String[] ar = sLine.split(regexp);
if (log.isDebugEnabled()) {
log.debug("Chunk size: " + ar[0]);
}
int res = 0;
try {
res = Integer.parseInt(ar[0]);
} catch (NumberFormatException ex) {
log.error("Error reading chunk size near: " + sLine, ex);
throw new IOExceptionWithCause(ex);
}
return res;
}
private byte getOneByte() throws IOException {
oneByte.rewind();
if (file.read(oneByte) < 1) {
throw new EndOfFileException(getFileName());
}
return oneByte.get(0);
}
public String getVarName() {
return getPropertyAsString(VARIABLE_NAME);
}
public void setVarName(String name) {
setProperty(VARIABLE_NAME, name);
}
public String getFileName() {
return getPropertyAsString(FILENAME);
}
public void setFileName(String filename) {
setProperty(FILENAME, filename);
file = null;
}
public void setRewindOnEOF(boolean isRew) {
setProperty(new BooleanProperty(REWIND, isRew));
}
public boolean getRewindOnEOF() {
return getPropertyAsBoolean(REWIND);
}
}
|
package br.com.Modelo;
public class AdicionarTipoDespesa {
private String nome;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
//aterardo.
|
package com.unidev.polycms.web;
import com.unidev.platform.j2ee.common.WebUtils;
import com.unidev.polydata.SQLiteStorage;
import com.unidev.polydata.domain.BasicPoly;
import com.unidev.polydata.domain.Poly;
import com.unidev.polyembeddedcms.PolyConstants;
import com.unidev.polyembeddedcms.PolyCore;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
/**
* Core service for web app
*/
@Service
public class WebPolyCore {
private static Logger LOG = LoggerFactory.getLogger(WebPolyCore.class);
@Autowired
private PolyCore polyCore;
@Autowired
private WebUtils webUtils;
public List<BasicPoly> fetchTags(HttpServletRequest httpServletRequest) {
SQLiteStorage sqLiteStorage = fetchSqliteDB(httpServletRequest);
PreparedStatement preparedStatement;
try(Connection connection = sqLiteStorage.openDb()) {
preparedStatement = connection.prepareStatement("SELECT * FROM " + PolyConstants.TAGS_POLY);
List<BasicPoly> polyList = sqLiteStorage.evaluateStatement(preparedStatement);
return polyList;
} catch (Exception e) {
e.printStackTrace();
LOG.warn("Failed to fetch tags for request {}", httpServletRequest);
return null;
}
}
/**
* Fetch poly by ID
* @param id
* @param httpServletRequest
* @return poly instance or null if poly is not available
*/
public Poly fetchPoly(String id, HttpServletRequest httpServletRequest) {
SQLiteStorage sqLiteStorage = fetchSqliteDB(httpServletRequest);
PreparedStatement preparedStatement;
try(Connection connection = sqLiteStorage.openDb()) {
preparedStatement = connection.prepareStatement("SELECT * FROM " + PolyConstants.DATA_POLY + " WHERE _id = ?");
preparedStatement.setObject(1, id);
List<BasicPoly> polyList = sqLiteStorage.evaluateStatement(preparedStatement);
if (polyList.size() != 1) {
return null;
}
return polyList.get(0);
} catch (Exception e) {
e.printStackTrace();
LOG.warn("Failed to fetch poly {} for request {}", id, httpServletRequest);
return null;
}
}
/**
* Fetch tenant root file
* @param httpServletRequest
* @return
*/
public File fetchTenantRoot(HttpServletRequest httpServletRequest) {
String domain = webUtils.getDomain(httpServletRequest);
return polyCore.fetchStorageRoot(domain);
}
public boolean existsTenant(HttpServletRequest httpServletRequest) {
return fetchTenantRoot(httpServletRequest).exists();
}
private SQLiteStorage fetchSqliteDB(HttpServletRequest httpServletRequest) {
File tenantRoot = fetchTenantRoot(httpServletRequest);
File dbFile = new File(tenantRoot, PolyConstants.DB_FILE);
return new SQLiteStorage(dbFile.getAbsolutePath());
}
}
|
package org.nick.wwwjdic.widgets;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.nick.wwwjdic.Constants;
import org.nick.wwwjdic.GzipStringResponseHandler;
import org.nick.wwwjdic.KanjiEntry;
import org.nick.wwwjdic.KanjiEntryDetail;
import org.nick.wwwjdic.R;
import org.nick.wwwjdic.WwwjdicApplication;
import org.nick.wwwjdic.WwwjdicPreferences;
import org.nick.wwwjdic.utils.StringUtils;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
public class GetKanjiService extends Service {
private static final String TAG = GetKanjiService.class.getSimpleName();
private static final Pattern PRE_START_PATTERN = Pattern
.compile("^<pre>.*$");
private static final Pattern PRE_END_PATTERN = Pattern
.compile("^</pre>.*$");
private static final String PRE_END_TAG = "</pre>";
private static final int NUM_RETRIES = 5;
private static final int RETRY_INTERVAL = 15 * 1000;
private final RandomJisGenerator jisGenerator = new RandomJisGenerator();
private final Executor executor = Executors.newSingleThreadExecutor();
@Override
public void onStart(Intent intent, int startId) {
executor.execute(new GetKanjiTask());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class GetKanjiTask implements Runnable {
public void run() {
try {
RemoteViews updateViews = buildUpdate(GetKanjiService.this);
ComponentName thisWidget = new ComponentName(
GetKanjiService.this, KodWidgetProvider.class);
AppWidgetManager manager = AppWidgetManager
.getInstance(GetKanjiService.this);
manager.updateAppWidget(thisWidget, updateViews);
} finally {
scheduleNextUpdate();
stopSelf();
}
}
}
private void scheduleNextUpdate() {
Time time = new Time();
long updateIntervalMillis = WwwjdicPreferences
.getKodUpdateInterval(this);
time.set(System.currentTimeMillis() + updateIntervalMillis);
long nextUpdate = time.toMillis(false);
long nowMillis = System.currentTimeMillis();
long deltaMinutes = (nextUpdate - nowMillis)
/ DateUtils.MINUTE_IN_MILLIS;
Log.d(TAG, "Requesting next update at " + time + ", in " + deltaMinutes
+ " min");
Intent updateIntent = new Intent(this, GetKanjiService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0,
updateIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, nextUpdate, pendingIntent);
}
private RemoteViews buildUpdate(Context context) {
RemoteViews views = null;
try {
boolean showReadingAndMeaning = WwwjdicPreferences
.isKodShowReading(this);
if (showReadingAndMeaning) {
views = new RemoteViews(context.getPackageName(),
R.layout.kod_widget_details);
} else {
views = new RemoteViews(context.getPackageName(),
R.layout.kod_widget);
}
showLoading(views);
HttpClient client = createHttpClient(WwwjdicPreferences
.getWwwjdicUrl(this), WwwjdicPreferences
.getWwwjdicTimeoutSeconds(this) * 1000);
String unicodeCp = jisGenerator
.generateAsUnicodeCp(WwwjdicPreferences
.isKodLevelOneOnly(context));
Log.d(TAG, "KOD Unicode CP: " + unicodeCp);
String backdoorCode = generateBackdoorCode(unicodeCp);
Log.d(TAG, "backdoor code: " + backdoorCode);
String wwwjdicResponse = null;
for (int i = 0; i < NUM_RETRIES; i++) {
try {
wwwjdicResponse = query(client, WwwjdicPreferences
.getWwwjdicUrl(this), backdoorCode);
if (wwwjdicResponse != null) {
break;
}
} catch (Exception e) {
if (i < NUM_RETRIES - 1) {
Log.w(TAG, String.format("Couldn't contact "
+ "WWWJDIC, will retry after %d ms.",
RETRY_INTERVAL), e);
Thread.sleep(RETRY_INTERVAL * (i + 1));
} else {
Log.e(TAG, "Couldn't contact WWWJDIC.", e);
}
}
}
if (wwwjdicResponse == null) {
Log.e(TAG, String.format("Failed to get WWWJDIC response "
+ "after %d tries, giving up.", NUM_RETRIES));
showError(views);
return views;
}
Log.d(TAG, "WWWJDIC response " + wwwjdicResponse);
List<KanjiEntry> entries = parseResult(wwwjdicResponse);
if (entries.isEmpty()) {
showError(views);
return views;
}
KanjiEntry entry = entries.get(0);
String kod = entry.getHeadword();
Log.d(TAG, "KOD: " + kod);
Intent intent = new Intent(context, KanjiEntryDetail.class);
intent.putExtra(Constants.KANJI_ENTRY_KEY, entries.get(0));
intent.putExtra(Constants.KOD_WIDGET_CLICK, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
String dateStr = DateFormat.getDateFormat(this).format(new Date());
views.setTextViewText(R.id.kod_date_text, dateStr);
views.setTextViewText(R.id.kod_text, kod);
if (showReadingAndMeaning) {
views.setTextViewText(R.id.kod_reading, entry.getReading());
views.setTextViewText(R.id.kod_meaning, entry
.getMeaningsAsString());
}
views.setOnClickPendingIntent(R.id.widget, pendingIntent);
clearLoading(views);
return views;
} catch (Exception e) {
Log.e(TAG, "Couldn't contact WWWJDIC", e);
views = new RemoteViews(context.getPackageName(),
R.layout.kod_widget);
showError(views);
return views;
}
}
private void showError(RemoteViews views) {
views.setViewVisibility(R.id.kod_message_text, View.VISIBLE);
views.setTextViewText(R.id.kod_message_text, getResources().getString(
R.string.error));
views.setViewVisibility(R.id.widget, View.GONE);
}
private void showLoading(RemoteViews views) {
views.setTextViewText(R.id.kod_message_text, getResources().getString(
R.string.widget_loading));
views.setViewVisibility(R.id.kod_message_text, View.VISIBLE);
views.setViewVisibility(R.id.widget, View.GONE);
}
private void clearLoading(RemoteViews views) {
views.setViewVisibility(R.id.kod_message_text, View.GONE);
views.setViewVisibility(R.id.widget, View.VISIBLE);
}
private HttpClient createHttpClient(String url, int timeoutMillis) {
Log.d(TAG, "WWWJDIC URL: " + url);
Log.d(TAG, "HTTP timeout: " + timeoutMillis);
HttpClient httpclient = new DefaultHttpClient();
HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, timeoutMillis);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMillis);
HttpProtocolParams.setUserAgent(httpParams, WwwjdicApplication
.getUserAgentString());
return httpclient;
}
private String query(HttpClient httpclient, String url, String backdoorCode) {
try {
String lookupUrl = String.format("%s?%s", url, backdoorCode);
HttpGet get = new HttpGet(lookupUrl);
GzipStringResponseHandler responseHandler = new GzipStringResponseHandler();
String responseStr = httpclient.execute(get, responseHandler);
// localContext);
return responseStr;
} catch (ClientProtocolException cpe) {
Log.e("WWWJDIC", "ClientProtocolException", cpe);
throw new RuntimeException(cpe);
} catch (IOException e) {
Log.e("WWWJDIC", "IOException", e);
throw new RuntimeException(e);
}
}
protected List<KanjiEntry> parseResult(String html) {
List<KanjiEntry> result = new ArrayList<KanjiEntry>();
boolean isInPre = false;
String[] lines = html.split("\n");
for (String line : lines) {
if (StringUtils.isEmpty(line)) {
continue;
}
Matcher m = PRE_START_PATTERN.matcher(line);
if (m.matches()) {
isInPre = true;
continue;
}
m = PRE_END_PATTERN.matcher(line);
if (m.matches()) {
break;
}
if (isInPre) {
boolean hasEndPre = false;
// some entries have </pre> on the same line
if (line.contains(PRE_END_TAG)) {
hasEndPre = true;
line = line.replaceAll(PRE_END_TAG, "");
}
Log.d(TAG, "dic entry line: " + line);
KanjiEntry entry = KanjiEntry.parseKanjidic(line);
result.add(entry);
if (hasEndPre) {
break;
}
}
}
return result;
}
private String generateBackdoorCode(String jisCode) {
StringBuffer buff = new StringBuffer();
// always "1" for kanji?
buff.append("1");
// raw
buff.append("Z");
// code
buff.append("K");
// Unicode
buff.append("U");
try {
buff.append(URLEncoder.encode(jisCode, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return buff.toString();
}
}
|
/* Generated By:JJTree: Do not edit this line. ASTMethod.java */
/**
* ASTMethod.java
*
* Method support for references : $foo.method()
*
* NOTE :
*
* introspection is now done at render time.
*
* Please look at the Parser.jjt file which is
* what controls the generation of this class.
*
* @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: ASTMethod.java,v 1.12 2001/03/19 18:13:43 jon Exp $
*/
package org.apache.velocity.runtime.parser.node;
import java.lang.reflect.Method;
import java.io.*;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.runtime.parser.*;
import org.apache.velocity.util.introspection.Introspector;
import org.apache.velocity.util.introspection.IntrospectionCacheData;
import org.apache.velocity.exception.MethodInvocationException;
import java.lang.reflect.InvocationTargetException;
public class ASTMethod extends SimpleNode
{
private String methodName = "";
private int paramCount = 0;
private Object [] params;
public ASTMethod(int id)
{
super(id);
}
public ASTMethod(Parser p, int id)
{
super(p, id);
}
/** Accept the visitor. **/
public Object jjtAccept(ParserVisitor visitor, Object data)
{
return visitor.visit(this, data);
}
/**
* simple init - init our subtree and get what we can from
* the AST
*/
public Object init( InternalContextAdapter context, Object data)
throws Exception
{
super.init( context, data );
/*
* this is about all we can do
*/
methodName = getFirstToken().image;
paramCount = jjtGetNumChildren() - 1;
params = new Object[paramCount];
return data;
}
/**
* does the instrospection of the class for the method needed.
* Note, as this calls value() on the args if any, this must
* only be called at execute() / render() time
*/
private Method doIntrospection( InternalContextAdapter context, Class data)
throws Exception
{
/*
* Now the parameters have to be processed, there
* may be references contained within that need
* to be introspected.
*/
for (int j = 0; j < paramCount; j++)
params[j] = jjtGetChild(j + 1).value(context);
Method m = Introspector.getMethod( data, methodName, params);
return m;
}
/**
* invokes the method. Returns null if a problem, the
* actual return if the method returns something, or
* an empty string "" if the method returns void
*/
public Object execute(Object o, InternalContextAdapter context)
throws MethodInvocationException
{
/*
* new strategy (strategery!) for introspection. Since we want
* to be thread- as well as context-safe, we *must* do it now,
* at execution time. There can be no in-node caching,
* but if we are careful, we can do it in the context.
*/
Method method = null;
try
{
/*
* check the cache
*/
IntrospectionCacheData icd = context.icacheGet( this );
Class c = o.getClass();
/*
* like ASTIdentifier, if we have cache information, and the
* Class of Object o is the same as that in the cache, we are
* safe.
*/
if ( icd != null && icd.contextData == c )
{
/*
* sadly, we do need recalc the values of the args, as this can
* change from visit to visit
*/
for (int j = 0; j < paramCount; j++)
params[j] = jjtGetChild(j + 1).value(context);
/*
* and get the method from the cache
*/
method = (Method) icd.thingy;
}
else
{
/*
* otherwise, do the introspection, and then
* cache it
*/
method = doIntrospection( context, c );
if (method != null)
{
icd = new IntrospectionCacheData();
icd.contextData = c;
icd.thingy = method;
context.icachePut( this, icd );
}
}
/*
* if we still haven't gotten the method, either we are calling
* a method that doesn't exist (which is fine...) or I screwed
* it up.
*/
if (method == null)
return null;
}
catch( Exception e )
{
Runtime.error("ASTMethod.execute() : exception : " + e );
return null;
}
try
{
/*
* get the returned object. It may be null, and that is
* valid for something declared with a void return type.
* Since the caller is expecting something to be returned,
* as long as things are peachy, we can return an empty
* String so ASTReference() correctly figures out that
* all is well.
*/
Object obj = method.invoke(o, params);
if (obj == null)
{
if( method.getReturnType() == Void.TYPE)
return new String("");
}
return obj;
}
catch( InvocationTargetException ite )
{
/*
* In the even that the invocation of the method
* itself throws an exception, we want to catch that
* wrap it, and throw. We don't log here as we want to figure
* out which reference threw the exception, so do that
* above
*/
throw new MethodInvocationException(
"Invocation of method threw exception.",
ite.getTargetException(), methodName );
}
catch( Exception e )
{
return null;
}
}
}
|
package core;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.QuoteMode;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class Artifact_Manifest {
private static final CSVFormat MANIFEST_FORMAT = CSVFormat.newFormat('\t')
.withHeader("uuid", "name", "description")
.withQuote('"')
.withQuoteMode(QuoteMode.MINIMAL);
private static final Artifact_ID aidAmbiguous = new Artifact_ID(null, null, null);
// aid inversions
private final Map<String, Artifact_ID> mpname_artifactID;
private final Map<UUID, Artifact_ID> mpuuid_artifactID;
private Artifact_Manifest() {
this.mpname_artifactID = new HashMap<String, Artifact_ID>();
this.mpuuid_artifactID = new HashMap<UUID, Artifact_ID>();
}
private Artifact_Manifest(Iterable<Artifact_ID> ids) {
this();
for (Artifact_ID aid : ids) {
AddArtifactID(aid);
}
}
public void AddArtifactID(Artifact_ID aid) {
if (mpname_artifactID.containsKey(aid.name)) {
mpname_artifactID.put(aid.name, aidAmbiguous);
}
else {
mpname_artifactID.put(aid.name, aid);
}
// TODO check for duplicates and throw if there are any
mpuuid_artifactID.put(aid.uuid, aid);
}
public Artifact_ID ArtifactIDFromName(String name) {
Artifact_ID aid = mpname_artifactID.get(name);
if (aid == aidAmbiguous) {
System.err.println("Artifact name " + name + " is ambiguous. Please refer to artifact by UUID instead");
return null;
}
return aid;
}
public static Artifact_Manifest FromFile(File file) {
try (CSVParser in = new CSVParser(new FileReader(file), MANIFEST_FORMAT)) {
Artifact_Manifest manifest = new Artifact_Manifest();
for (CSVRecord record : in) {
String name = record.get("name");
UUID uuid = UUID.fromString(record.get("uuid"));
String description = record.get("description");
manifest.AddArtifactID(new Artifact_ID(uuid, name, description));
}
return manifest;
} catch (IOException ex) {
System.err.println("Could not read file " + file.getAbsolutePath());
return null;
}
}
public void WriteToFile(File file) {
try (CSVPrinter out = new CSVPrinter(new FileWriter(file), MANIFEST_FORMAT)) {
for (Artifact_ID aid : mpuuid_artifactID.values()) {
out.printRecord(aid.uuid, aid.name, aid.description);
}
} catch (IOException ex) {
System.err.println("Could not write to file " + file.getAbsolutePath());
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Artifact_ID aid : mpuuid_artifactID.values()) {
sb.append(aid.toString());
sb.append('\n');
}
return sb.toString();
}
public Artifact_ID ArtifactIDFromUUID(UUID uuid) {
return mpuuid_artifactID.get(uuid);
}
}
|
package arez.processor;
import com.google.common.collect.ImmutableList;
import com.google.testing.compile.Compilation;
import com.google.testing.compile.Compiler;
import com.google.testing.compile.JavaFileObjects;
import com.google.testing.compile.JavaSourcesSubjectFactory;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import javax.tools.JavaFileObject;
import static com.google.common.truth.Truth.*;
import static org.testng.Assert.*;
abstract class AbstractArezProcessorTest
{
void assertSuccessfulCompile( @Nonnull final String classname,
final boolean daggerModuleExpected,
final boolean daggerComponentExtensionExpected,
final boolean repositoryEnabled,
final boolean repositoryDaggerEnabled )
throws Exception
{
final String[] elements = classname.contains( "." ) ? classname.split( "\\." ) : new String[]{ classname };
final StringBuilder input = new StringBuilder();
final StringBuilder arezComponent = new StringBuilder();
final StringBuilder repository = repositoryEnabled ? new StringBuilder() : null;
final StringBuilder arezRepository = repositoryEnabled ? new StringBuilder() : null;
final StringBuilder componentDaggerModule = daggerModuleExpected ? new StringBuilder() : null;
final StringBuilder componentExtension = daggerComponentExtensionExpected ? new StringBuilder() : null;
final StringBuilder repositoryExtension = repositoryEnabled ? new StringBuilder() : null;
final StringBuilder repositoryDaggerModule = repositoryDaggerEnabled ? new StringBuilder() : null;
input.append( "input" );
arezComponent.append( "expected" );
if ( daggerModuleExpected )
{
componentDaggerModule.append( "expected" );
}
if ( daggerComponentExtensionExpected )
{
componentExtension.append( "expected" );
}
if ( repositoryEnabled )
{
repository.append( "expected" );
arezRepository.append( "expected" );
repositoryExtension.append( "expected" );
}
if ( repositoryDaggerEnabled )
{
repositoryDaggerModule.append( "expected" );
}
for ( int i = 0; i < elements.length; i++ )
{
input.append( '/' );
input.append( elements[ i ] );
arezComponent.append( '/' );
if ( daggerModuleExpected )
{
componentDaggerModule.append( '/' );
}
if ( daggerComponentExtensionExpected )
{
componentExtension.append( '/' );
}
if ( repositoryEnabled )
{
repository.append( '/' );
arezRepository.append( '/' );
repositoryExtension.append( '/' );
}
if ( repositoryDaggerEnabled )
{
repositoryDaggerModule.append( '/' );
}
final boolean isLastElement = i == elements.length - 1;
if ( isLastElement )
{
arezComponent.append( "Arez_" );
if ( repositoryEnabled )
{
arezRepository.append( "Arez_" );
}
}
arezComponent.append( elements[ i ] );
if ( daggerModuleExpected )
{
componentDaggerModule.append( elements[ i ] );
if ( isLastElement )
{
componentDaggerModule.append( "DaggerModule" );
}
}
if ( daggerComponentExtensionExpected )
{
componentExtension.append( elements[ i ] );
if ( isLastElement )
{
componentExtension.append( "DaggerComponentExtension" );
}
}
if ( repositoryEnabled )
{
repository.append( elements[ i ] );
arezRepository.append( elements[ i ] );
repositoryExtension.append( elements[ i ] );
if ( isLastElement )
{
repository.append( "Repository" );
arezRepository.append( "Repository" );
repositoryExtension.append( "Repository" );
}
}
if ( repositoryDaggerEnabled )
{
repositoryDaggerModule.append( elements[ i ] );
if ( isLastElement )
{
repositoryDaggerModule.append( "RepositoryDaggerModule" );
}
}
}
input.append( ".java" );
arezComponent.append( ".java" );
final ArrayList<String> expectedOutputs = new ArrayList<>();
expectedOutputs.add( arezComponent.toString() );
if ( daggerModuleExpected )
{
componentDaggerModule.append( ".java" );
expectedOutputs.add( componentDaggerModule.toString() );
}
if ( daggerComponentExtensionExpected )
{
componentExtension.append( ".java" );
expectedOutputs.add( componentExtension.toString() );
}
if ( repositoryEnabled )
{
repository.append( ".java" );
arezRepository.append( ".java" );
repositoryExtension.append( ".java" );
expectedOutputs.add( repository.toString() );
expectedOutputs.add( arezRepository.toString() );
expectedOutputs.add( repositoryExtension.toString() );
}
if ( repositoryDaggerEnabled )
{
repositoryDaggerModule.append( ".java" );
expectedOutputs.add( repositoryDaggerModule.toString() );
}
assertSuccessfulCompile( input.toString(), expectedOutputs.toArray( new String[ 0 ] ) );
}
void assertSuccessfulCompile( @Nonnull final String inputResource, @Nonnull final String... expectedOutputResources )
throws Exception
{
final JavaFileObject source = fixture( inputResource );
assertSuccessfulCompile( Collections.singletonList( source ), Arrays.asList( expectedOutputResources ) );
}
void assertSuccessfulCompile( @Nonnull final List<JavaFileObject> inputs, @Nonnull final List<String> outputs )
throws Exception
{
if ( outputFiles() )
{
final Compilation compilation =
Compiler.javac()
.withProcessors( new ArezProcessor() )
.withOptions( "-Xlint:all,-processing", "-implicit:none", "-Aarez.defer.errors=false" )
.compile( inputs );
final Compilation.Status status = compilation.status();
if ( Compilation.Status.SUCCESS != status )
{
/*
* Ugly hackery that marks the compile as successful so we can emit output onto filesystem. This could
* result in java code that is not compilable emitted to filesystem. This re-running determining problems
* a little easier even if it does make re-running tests from IDE a little harder
*/
final Field field = compilation.getClass().getDeclaredField( "status" );
field.setAccessible( true );
field.set( compilation, Compilation.Status.SUCCESS );
}
final ImmutableList<JavaFileObject> fileObjects = compilation.generatedSourceFiles();
for ( final JavaFileObject fileObject : fileObjects )
{
final Path target = fixtureDir().resolve( "expected/" + fileObject.getName().replace( "/SOURCE_OUTPUT/", "" ) );
final File dir = target.getParent().toFile();
if ( !dir.exists() )
{
assertTrue( dir.mkdirs() );
}
if ( Files.exists( target ) )
{
final byte[] existing = Files.readAllBytes( target );
final InputStream generated = fileObject.openInputStream();
final byte[] data = new byte[ generated.available() ];
assertEquals( generated.read( data ), data.length );
if ( Arrays.equals( existing, data ) )
{
/*
* If the data on the filesystem is identical to data generated then do not write
* to filesystem. The writing can be slow and it can also trigger the IDE or other
* tools to recompile code which is problematic.
*/
continue;
}
Files.delete( target );
}
Files.copy( fileObject.openInputStream(), target );
}
if ( Compilation.Status.SUCCESS != status )
{
// Restore old status
final Field field = compilation.getClass().getDeclaredField( "status" );
field.setAccessible( true );
field.set( compilation, status );
// This next line will generate an error and fail the test
//noinspection ResultOfMethodCallIgnored
compilation.generatedSourceFiles();
}
}
final JavaFileObject firstExpected = fixture( outputs.get( 0 ) );
final JavaFileObject[] restExpected =
outputs.stream().skip( 1 ).map( this::fixture ).toArray( JavaFileObject[]::new );
assert_().about( JavaSourcesSubjectFactory.javaSources() ).
that( inputs ).
withCompilerOptions( "-Xlint:all,-processing", "-implicit:none", "-Aarez.defer.errors=false" ).
processedWith( new ArezProcessor() ).
compilesWithoutWarnings().
and().
generatesSources( firstExpected, restExpected );
}
void assertFailedCompile( @Nonnull final String classname, @Nonnull final String errorMessageFragment )
{
assertFailedCompileResource( toFilename( "bad_input", classname ), errorMessageFragment );
}
@Nonnull
final String toFilename( @Nonnull final String dir, @Nonnull final String classname )
{
final String[] elements = classname.contains( "." ) ? classname.split( "\\." ) : new String[]{ classname };
final StringBuilder input = new StringBuilder();
input.append( dir );
for ( final String element : elements )
{
input.append( '/' );
input.append( element );
}
input.append( ".java" );
return input.toString();
}
private void assertFailedCompileResource( @Nonnull final String inputResource,
@Nonnull final String errorMessageFragment )
{
assertFailedCompileResource( Collections.singletonList( fixture( inputResource ) ), errorMessageFragment );
}
void assertFailedCompileResource( @Nonnull final List<JavaFileObject> inputs,
@Nonnull final String errorMessageFragment )
{
assert_().about( JavaSourcesSubjectFactory.javaSources() ).
that( inputs ).
processedWith( new ArezProcessor() ).
failsToCompile().
withWarningContaining( errorMessageFragment );
}
@Nonnull
final JavaFileObject fixture( @Nonnull final String path )
{
final Path outputFile = fixtureDir().resolve( path );
if ( !Files.exists( outputFile ) )
{
fail( "Output file fixture " + outputFile + " does not exist. Thus can not compare against it." );
}
try
{
return JavaFileObjects.forResource( outputFile.toUri().toURL() );
}
catch ( final MalformedURLException e )
{
throw new IllegalStateException( e );
}
}
@Nonnull
private Path fixtureDir()
{
final String fixtureDir = System.getProperty( "arez.fixture_dir" );
assertNotNull( fixtureDir, "Expected System.getProperty( \"arez.fixture_dir\" ) to return fixture directory" );
return new File( fixtureDir ).toPath();
}
private boolean outputFiles()
{
return System.getProperty( "arez.output_fixture_data", "false" ).equals( "true" );
}
}
|
package com.xpn.xwiki.web;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
/**
* Action used to get a resource that is a part of a page loaded asynchronously generally for performance reasons. Like
* <code>download</code> or <code>skin</code> but for wiki content.
* <p>
* This means that by default there is not UI and it's not registered in the statistics since the main page is already
* logged.
*
* @version $Id$
*/
public class GetAction extends XWikiAction
{
/**
* The identifier of the view action.
*
* @todo need an enumerated class for actions.
*/
public static final String GET_ACTION = "get";
/**
* {@inheritDoc}
*
* @see XWikiAction#action(com.xpn.xwiki.XWikiContext)
*/
public boolean action(XWikiContext context) throws XWikiException
{
boolean shouldRender = true;
context.put("action", GET_ACTION);
return shouldRender;
}
/**
* {@inheritDoc}
*
* @see XWikiAction#render(com.xpn.xwiki.XWikiContext)
*/
public String render(XWikiContext context) throws XWikiException
{
handleRevision(context);
// In case a search engine spider should end up calling the /get/ action, point them to the view action with
// a Content-Location header. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.14
context.getResponse().setHeader("Content-Location", context.getDoc().getURL("view", context));
return GET_ACTION;
}
}
|
package org.jdesktop.swingx.painter;
import java.awt.Insets;
import java.awt.Rectangle;
/**
* An abstract base class for any painter which can be positioned. This means
* the painter has some intrinsic size to what it is drawing and
* can be stretched or aligned both horizontally and vertically.
*
*
* The AbstractLayoutPainter class provides the following configuraable properties:
*
* <ul>
* <li>horizonalAlignment - the horizonal alignment (left, center, and right)</li>
* <li>verticalAlignment - the verticalAlignment alignment (top, center, and bottom)</li>
* <li>fillHorizontal - indicates if the painter should stretch to fill the available space horizontally</li>
* <li>fillVertical - indicates if the painter should stretch to fill the available space vertically</li>
* <li>insets - whitespace on the top, bottom, left, and right.
* </ul>
* @author joshy
*/
public abstract class AbstractLayoutPainter<T> extends AbstractPainter<T> {
/**
* Specifies how to draw the image, i.e. what kind of Style to use
* when drawing
*/
private VerticalAlignment verticalAlignment = VerticalAlignment.CENTER;
private HorizontalAlignment horizontalAlignment = HorizontalAlignment.CENTER;
private Insets insets = new Insets(0,0,0,0);
private boolean fillVertical = false;
private boolean fillHorizontal = false;
/**
* Creates a new instance of AbstractLayoutPainter
*/
public AbstractLayoutPainter() {
}
/**
* An enum which controls horizontalAlignment alignment
*/
public static enum HorizontalAlignment { LEFT, CENTER, RIGHT }
/**
* An enum which controls verticalAlignment alignment
*/
public static enum VerticalAlignment { TOP, CENTER, BOTTOM }
/**
* Gets the current horizontalAlignment alignment.
*
* @return the current horizontalAlignment alignment
*/
public HorizontalAlignment getHorizontalAlignment() {
return horizontalAlignment;
}
/**
* Gets the current whitespace insets.
* @return the current insets
*/
public Insets getInsets() {
return insets;
}
/**
* gets the current verticalAlignment alignment
*
* @return current verticalAlignment alignment
*/
public VerticalAlignment getVerticalAlignment() {
return verticalAlignment;
}
/**
* indicates if the painter content is stretched horizontally
*
* @return the current horizontalAlignment stretch value
*/
public boolean isFillHorizontal() {
return fillHorizontal;
}
/**
* indicates if the painter content is stretched vertically
*
* @return the current verticalAlignment stretch value
*/
public boolean isFillVertical() {
return fillVertical;
}
/**
* Sets a new horizontalAlignment alignment. Used to position the content at the left, right, or center.
*
* @param horizontal new horizontalAlignment alignment
*/
public void setHorizontalAlignment(HorizontalAlignment horizontal) {
HorizontalAlignment old = this.getHorizontalAlignment();
this.horizontalAlignment = horizontal;
firePropertyChange("horizontal",old,this.horizontalAlignment);
}
/**
* Sets if the content should be stretched horizontally to fill all available horizontalAlignment
* space (minus the left and right insets).
*
*
* @param fillHorizontal new horizonal stretch value
*/
public void setFillHorizontal(boolean fillHorizontal) {
boolean old = this.isFillHorizontal();
this.fillHorizontal = fillHorizontal;
firePropertyChange("horizontalStretch",old,this.fillHorizontal);
}
/**
* Sets the current whitespace insets.
* @param insets new insets
*/
public void setInsets(Insets insets) {
Insets old = this.getInsets();
this.insets = insets;
firePropertyChange("insets",old,this.insets);
}
/**
* Sets a new verticalAlignment alignment. Used to position the content at the top, bottom, or center.
*
* @param vertical new verticalAlignment alignment
*/
public void setVerticalAlignment(VerticalAlignment vertical) {
VerticalAlignment old = this.getVerticalAlignment();
this.verticalAlignment = vertical;
firePropertyChange("vertical",old,this.verticalAlignment);
}
/**
* Sets if the content should be stretched vertically to fill all available verticalAlignment
* space (minus the top and bottom insets).
*
*
* @param verticalStretch new verticalAlignment stretch value
*/
public void setFillVertical(boolean verticalStretch) {
boolean old = this.isFillVertical();
this.fillVertical = verticalStretch;
firePropertyChange("verticalStretch",old,this.fillVertical);
}
/**
* a protected method used by subclasses to calculate the final position of the
* content. Subclasses usually don't need to override this.
* @param contentWidth The width of the content to be painted
* @param contentHeight The height of the content to be painted
* @param width the width of the area that the content will be positioned in
* @param height the height of the area that the content will be positioned in
* @return the rectangle for the content to be painted in
*/
protected final Rectangle calculateLayout(final int contentWidth, final int contentHeight,
final int width, final int height) {
Rectangle rect = new Rectangle();
rect.width = contentWidth;
rect.height = contentHeight;
if(isFillHorizontal()) {
rect.width = width - insets.left - insets.right;
}
if(isFillVertical()) {
rect.height = height - insets.top - insets.bottom;
}
rect.x = calculateX(rect.width, width);
rect.y = calculateY(rect.height, height);
return rect;
}
private int calculateY(final int imgHeight, final int height) {
int y = 0;
if(getVerticalAlignment() == VerticalAlignment.TOP) {
y = 0;
y+= insets.top;
}
if(getVerticalAlignment() == VerticalAlignment.CENTER) {
y = (height-imgHeight)/2;
y += insets.top;
}
if(getVerticalAlignment() == VerticalAlignment.BOTTOM) {
y = height-imgHeight;
y-= insets.bottom;
}
return y;
}
private int calculateX(final int imgWidth, final int width) {
int x = 0;
if(getHorizontalAlignment() == HorizontalAlignment.LEFT) {
x = 0;
x+= insets.left;
}
if(getHorizontalAlignment() == HorizontalAlignment.CENTER) {
x = (width-imgWidth)/2;
x += insets.left;
}
if(getHorizontalAlignment() == HorizontalAlignment.RIGHT) {
x = width-imgWidth;
x-= insets.right;
}
return x;
}
}
|
package org.yamcs.cfdp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.yamcs.cfdp.pdu.ActionCode;
import org.yamcs.cfdp.pdu.CfdpHeader;
import org.yamcs.cfdp.pdu.CfdpPacket;
import org.yamcs.cfdp.pdu.ConditionCode;
import org.yamcs.cfdp.pdu.EofPacket;
import org.yamcs.cfdp.pdu.FaultHandlerOverride;
import org.yamcs.cfdp.pdu.FileDataPacket;
import org.yamcs.cfdp.pdu.FileStoreRequest;
import org.yamcs.cfdp.pdu.LV;
import org.yamcs.cfdp.pdu.MessageToUser;
import org.yamcs.cfdp.pdu.MetadataPacket;
import org.yamcs.cfdp.pdu.TLV;
import org.yamcs.protobuf.Cfdp;
import org.yamcs.protobuf.Cfdp.TransferDirection;
import org.yamcs.protobuf.Cfdp.TransferState;
import org.yamcs.yarch.Stream;
public class CfdpTransfer extends CfdpTransaction {
private enum CfdpTransferState {
START,
METADATA_SENT,
SENDING_DATA,
SENDING_FINISHED,
EOF_SENT,
FINISHED_RECEIVED,
FINISHED_ACK_SENT,
CANCELING,
CANCELED
}
private final boolean withCrc = false;
private final boolean acknowledged = false;
private final boolean withSegmentation = false;
private final int entitySize = 4;
private final int seqNrSize = 4;
private final int maxDataSize = 7;
private long startTime;
private CfdpTransferState currentState;
private TransferState state;
private long transferred;
private int offset = 0;
private int end = 0;
private final int pauseBetweenFileDataPackets = 2000;
private TransferDirection transferDirection;
private boolean sleeping = false;
private PutRequest request;
public CfdpTransfer(PutRequest request, Stream cfdpOut) {
super(request.getSourceId(), cfdpOut);
this.request = request;
this.currentState = CfdpTransferState.START;
this.state = Cfdp.TransferState.RUNNING;
this.transferDirection = TransferDirection.UPLOAD;
}
public TransferState getTransferState() {
return this.state;
}
public PutRequest getRequest() {
return request;
}
public long getTransferredSize() {
return this.transferred;
}
public boolean isOngoing() {
return state == TransferState.RUNNING || state == TransferState.PAUSED;
}
@Override
public void run() {
while (isOngoing()) {
step();
}
}
@Override
public void step() {
switch (currentState) {
case START:
this.startTime = System.currentTimeMillis();
sendPacket(getMetadataPacket());
this.currentState = CfdpTransferState.METADATA_SENT;
break;
case METADATA_SENT:
offset = 0; // first file data packet starts at the start of the data
end = Math.min(maxDataSize, request.getPacketLength());
sendPacket(getNextFileDataPacket());
transferred = end;
offset = end;
this.currentState = CfdpTransferState.SENDING_DATA;
break;
case SENDING_DATA:
if (offset == request.getPacketLength()) {
this.currentState = CfdpTransferState.SENDING_FINISHED;
} else {
try {
while (sleeping) {
Thread.sleep(100);
}
Thread.sleep(pauseBetweenFileDataPackets);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
end = Math.min(offset + maxDataSize, request.getPacketLength());
sendPacket(getNextFileDataPacket());
transferred += (end - offset);
offset = end;
}
break;
case SENDING_FINISHED:
sendPacket(getEofPacket(ConditionCode.NoError));
this.currentState = CfdpTransferState.EOF_SENT;
break;
case EOF_SENT:
// Do nothing, we're waiting for a FINISHED_RECEIVED packet
break;
case FINISHED_RECEIVED:
// TODO Send FINISHED_Ack_packet and go to FINISHED_ACK_SENT
// TODO, for now we don't send acknowledgements, so just move on
this.currentState = CfdpTransferState.FINISHED_ACK_SENT;
break;
case FINISHED_ACK_SENT:
// we're done;
state = TransferState.COMPLETED;
break;
case CANCELING:
sendPacket(getEofPacket(ConditionCode.CancelRequestReceived));
this.currentState = CfdpTransferState.CANCELED;
break;
case CANCELED:
this.state = Cfdp.TransferState.FAILED;
break;
default:
throw new IllegalStateException("packet in unknown/illegal state");
}
}
private MetadataPacket getMetadataPacket() {
// create packet header
CfdpHeader header = new CfdpHeader(
true, // it's a file directive
false, // it's sent towards the receiver
acknowledged, // not acknowledged // TODO, is this okay?
withCrc, // no CRC
entitySize, // TODO, hardcoded entity length
seqNrSize, // TODO, hardcoded sequence number length
getTransactionId().getInitiatorEntity(), // my Entity Id
request.getDestinationId(), // the id of the target
this.myId.getSequenceNumber());
// TODO, only supports the creation of new files at the moment
List<FileStoreRequest> fsrs = new ArrayList<FileStoreRequest>();
fsrs.add(new FileStoreRequest(ActionCode.CreateFile, new LV(request.getTargetPath())));
return new MetadataPacket(
withSegmentation, // TODO no segmentation
request.getPacketLength(),
"", // no source file name, the data will come from a bucket
request.getTargetPath(),
fsrs,
new ArrayList<MessageToUser>(), // no user messages
new ArrayList<FaultHandlerOverride>(), // no fault handler overides
new TLV((byte) 0x05, new byte[0]), // empty flow label
header);
}
private FileDataPacket getNextFileDataPacket() {
CfdpHeader header = new CfdpHeader(
false, // it's file data
false, // it's sent towards the receiver
acknowledged, // not acknowledged // TODO, is this okay?
withCrc, // no CRC
entitySize, // TODO, hardcoded entity length
seqNrSize, // TODO, hardcoded sequence number length
getTransactionId().getInitiatorEntity(), // my Entity Id
request.getDestinationId(), // the id of the target
this.myId.getSequenceNumber());
FileDataPacket filedata = new FileDataPacket(
Arrays.copyOfRange(request.getPacketData(), offset, end),
offset,
header);
return filedata;
}
private EofPacket getEofPacket(ConditionCode code) {
CfdpHeader header = new CfdpHeader(
true, // file directive
false, // towards receiver
acknowledged,
withCrc,
entitySize,
seqNrSize,
getTransactionId().getInitiatorEntity(),
request.getDestinationId(),
this.myId.getSequenceNumber());
return new EofPacket(
code, // TODO, we assume no errors
0, // TODO checksum
request.getPacketLength(), // TODO, currently assumes that all data is sent exactly once
null, // TODO, only if ConditionCode.NoError is sent
header);
}
public CfdpTransferState getCfdpState() {
return this.currentState;
}
public TransferDirection getDirection() {
return this.transferDirection;
}
public long getTotalSize() {
return this.request.getPacketLength();
}
public CfdpTransfer cancel() {
// IF cancelled, return myself, otherwise return null id, otherwise return null
return this;
}
public CfdpTransfer pause() {
sleeping = true;
return this;
}
public CfdpTransfer resumeTransfer() {
sleeping = false;
return this;
}
public CfdpTransfer cancelTransfer() {
sleeping = false; // wake up if sleeping
currentState = CfdpTransferState.CANCELING;
return this;
}
public long getTransferredBytes() {
return transferred;
}
@Override
public void processPacket(CfdpPacket packet) {
if (packet.getHeader().isFileDirective()) {
switch (((FileDirective) packet).getFileDirectiveCode()) {
case Finished:
if (currentState == CfdpTransferState.EOF_SENT) {
currentState = CfdpTransferState.FINISHED_RECEIVED;
}
break;
default:
break;
}
} else {
// TODO incoming data
}
}
}
|
package lv.ctco.cukesrest.api;
import com.google.inject.*;
import cucumber.api.java.en.*;
import lv.ctco.cukesrest.internal.*;
import lv.ctco.cukesrest.internal.resources.*;
@Singleton
public class ThenSteps {
@Inject
private AssertionFacade assertionFacade;
@Inject
private ResourceFileReader fileReader;
@Then("^let variable \"([^\"]+)\" equal to header \"([^\"]+)\" value$")
public void var_assigned_from_header(String varName, String headerName) {
assertionFacade.varAssignedFromHeader(varName, headerName);
}
@Then("^let variable \"([^\"]+)\" equal to property \"([^\"]+)\" value$")
public void var_assigned_fromProperty(String varName, String property) {
assertionFacade.varAssignedFromProperty(varName, property);
}
@Then("^response is empty$")
public void response_Body_Is_Empty() {
assertionFacade.bodyEqualTo("");
}
@Then("^response is not empty$")
public void response_Body_Is_Not_Empty() {
assertionFacade.bodyNotEmpty();
}
@Then("^response equals to \"(.*)\"$")
public void response_Body_Equal_To(String body) {
assertionFacade.bodyEqualTo(body);
}
@Then("^response body not equal to \"(.*)\"$")
public void response_Body_Not_Equal_To(String body) {
assertionFacade.bodyNotEqualTo(body);
}
@Then("^response contains \"(.+)\"$")
public void response_Body_Contains(String body) {
assertionFacade.bodyContains(body);
}
@Then("^response body does not contain \"(.+)\"$")
public void response_Body_Does_Not_Contain(String body) {
assertionFacade.bodyDoesNotContain(body);
}
@Then("^response contains property \"(.+)\" containing phrase \"(.*)\"$")
public void response_Body_Contains_Property_With_Phrase(String jsonPath, String phrase) {
assertionFacade.bodyContainsJsonPathValueContainingPhrase(jsonPath, phrase);
}
@Then("^response contains property \"(.+)\" with value \"(.*)\"$")
public void response_Body_Contains_Property(String path, String value) {
assertionFacade.bodyContainsPathWithValue(path, value);
}
@Then("^response contains property \"(.+)\" with value$")
public void response_Body_Contains_Property_Multiline(String path, String value) {
assertionFacade.bodyContainsPathWithValue(path, value);
}
@Then("^response contains property \"(.+)\" with value other than \"(.*)\"$")
public void response_Body_Contains_Property_Other_Value(String path, String value) {
assertionFacade.bodyContainsPathWithOtherValue(path, value);
}
@Then("^response contains property \"(.+)\" of type \"(.+)\"$")
public void response_Body_Contains_Property_Of_Type(String path, String type) {
assertionFacade.bodyContainsPathOfType(path, type);
}
@Then("^response contains an array \"(.+)\" of size \"(.+)\"$")
public void response_Body_Contains_Array_With_Size(String path, String size) {
assertionFacade.bodyContainsArrayWithSize(path, size);
}
@Then("^response does not contain property \"(.+)\"")
public void response_Body_Does_Not_Contain_Property(String path) {
assertionFacade.bodyDoesNotContainPath(path);
}
@Then("^response contains property \"(.+)\" matching pattern \"(.+)\"$")
public void response_Body_Contains_Property_Matching_Pattern(String path, String pattern) {
assertionFacade.bodyContainsPathMatchingPattern(path, pattern);
}
@Then("^response contains property \"(.+)\" not matching pattern \"(.+)\"$")
public void response_Body_Contains_Property_Not_Matching_Pattern(String path, String pattern) {
assertionFacade.bodyContainsPathNotMatchingPattern(path, pattern);
}
@Then("^response contains properties from file (.+)$")
public void response_Body_Contains_Properties_From_File(String path) {
assertionFacade.bodyContainsPropertiesFromJson(fileReader.read(path));
}
@Then("^response contains properties from json")
public void response_Body_Contains_Properties_From(String str) {
assertionFacade.bodyContainsPropertiesFromJson(str);
}
@Then("^status code is (\\d+)$")
public void response_Status_Code_Is(int statusCode) {
assertionFacade.statusCodeIs(statusCode);
}
@Then("^status code is not (\\d+)$")
public void response_Status_Code_Is_Not(int statusCode) {
assertionFacade.statusCodeIsNot(statusCode);
}
@Then("^header (.+) is empty$")
public void header_Is_Empty(String headerName) {
assertionFacade.headerIsEmpty(headerName);
}
@Then("^header (.+) is not empty$")
public void header_Is_Not_Empty(String headerName) {
assertionFacade.headerIsNotEmpty(headerName);
}
@Then("^header (.+) equal to \"(.+)\"$")
public void header_Equal_To(String headerName, String value) {
assertionFacade.headerEqualTo(headerName, value);
}
@Then("^header (.+) not equal to \"(.+)\"$")
public void header_Not_Equal_To(String headerName, String value) {
assertionFacade.headerNotEqualTo(headerName, value);
}
@Then("^header (.+) contains \"(.+)\"$")
public void header_Contains(String headerName, String text) {
assertionFacade.headerContains(headerName, text);
}
@Then("^header (.+) does not contain \"(.+)\"$")
public void header_Does_Not_Contain(String headerName, String text) {
assertionFacade.headerDoesNotContain(headerName, text);
}
@Then("^header (.+) ends with pattern \"(.+)\"$")
public void header_Ends_With(String headerName, String suffix) {
assertionFacade.headerEndsWith(headerName, suffix);
}
@Then("a failure is expected")
public void a_failure_is_expected() {
assertionFacade.failureIsExpected();
}
@Then("^it fails with ([^\"]+)$")
public void it_fails(String exceptionClass) {
assertionFacade.failureOccurs(exceptionClass);
}
}
|
import java.io.FileWriter;
import java.util.zip.Inflater;
import java.util.zip.Deflater;
//StarOffice Interfaces and UNO
import com.sun.star.bridge.XBridgeFactory;
import com.sun.star.bridge.XBridge;
import com.sun.star.connection.XConnector;
import com.sun.star.connection.XConnection;
import com.sun.star.container.XNameContainer;
import com.sun.star.embed.XTransactedObject;
import com.sun.star.io.XStream;
import com.sun.star.io.XSeekable;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XComponent;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.UnoRuntime;
/** This class is an xalan extension class. It provider 2 elements
* and 2 functions to used in xslt script. With this elements and functions
* we can convert between oledata between Wordml and OOo flat.
* To use it, we need a running OOo. There are two ways to get the XMultiServiceFactory.
* When called by OOo xslt filter, an XMultiServiceFactory will be add to the transformer
* by setParameter(), then we can get it using getParameter(). Another way is using an
* XConnection to connect to a running OOo. We connect to a running OOo, we need know the
* uno url. It can be set in the xslt script. The default uno url is:
* "uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager"
* see XSLTXalanOLEExtracter.java
*/
public class XSLTFilterOLEExtracter {
protected XMultiServiceFactory m_xMSF;
protected XNameContainer m_Storage;
protected XStream m_RootStream;
protected XConnection m_Connection;
protected String sConnectionString;
private static final String UNO_URL = "uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager";
public XSLTFilterOLEExtracter() {
}
public void init(String unoUrl) {
if (unoUrl == null || unoUrl.equals("")) {
unoUrl = UNO_URL;
}
debugln("Init with uno url=" + unoUrl);
if (null == m_xMSF) {
try {
m_xMSF = connectAwareGetServiceFactory();
} catch (Exception ex) {
System.err.println("Could not connect to the office '" + unoUrl + "'\n" + ex.getMessage());
}
}
}
public void exit() {
m_Storage = null;
m_xMSF = null;
if (null != m_Connection) {
try {
m_Connection.close();
} catch (Exception ex) {
System.err.println("Could not close connection to the office.\n" + ex.getMessage());
}
}
}
//If aName = "oledata.mso" then we load the root storage from the given base64 string
//Otherwise we compress the stream and add it to the root storage under the name of aName
public void insertByName(String aName, String aBase64) {
debugln("insertByName(" + aName + " : " + aBase64 + ")");
if (aName.equals("oledata.mso")) {
loadRootStorageFromBase64(aBase64);
} else {
ensureCreateRootStorage();
insertSubStorage(aName, aBase64);
}
}
//If aName = "oledata.mso" then we return the base64 encoded string of the root storage
//Otherwise we return the base64 encoded string of the sub stream under the name of aName
public String getByName(String aName) {
if (aName.equals("oledata.mso")) {
try {
//get the length and seek to 0
XSeekable xSeek = (XSeekable) UnoRuntime.queryInterface(XSeekable.class, m_RootStream);
int oleLength = (int) xSeek.getLength();
xSeek.seek(0);
xSeek = null;
//read all bytes
XInputStream xInput = m_RootStream.getInputStream();
byte oledata[][] = new byte[1][oleLength];
xInput.readBytes(oledata, oleLength);
//return the base64 encoded string
return Base64.encodeBytes(oledata[0]);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
return getEncodedSubStorage(aName);
}
return "";
}
//get the sub stream which name = aName, decompress it and return the base64 encoded string
public String getEncodedSubStorage(String aName) {
debugln("getByName(" + aName + ")");
try {
if (!m_Storage.hasByName(aName)) {
return "Not Found:" + aName;
}
Object oSubStream = m_Storage.getByName(aName);
if (oSubStream == null) {
return "Not Found:" + aName;
}
XInputStream xSubStream = (XInputStream) UnoRuntime.queryInterface(XInputStream.class,
oSubStream);
if (xSubStream == null) {
return "Not Found:" + aName;
}
//The first four byte are the length of the uncompressed data
byte pLength[][] = new byte[1][4];
XSeekable xSeek = (XSeekable) UnoRuntime.queryInterface(XSeekable.class, xSubStream);
xSeek.seek(0);
xSeek = null;
//Get the uncompressed length
int readbytes = xSubStream.readBytes(pLength, 4);
if (4 != readbytes) {
System.out.println("readbytes:" + readbytes);
return "Can not read the length.";
}
int oleLength = (pLength[0][0] << 0) + (pLength[0][1] << 8) + (pLength[0][2] << 16) + (pLength[0][3] << 24);
byte pContents[][] = new byte[1][oleLength];
//Read all bytes. The compressed length should less then the uncompressed length
readbytes = xSubStream.readBytes(pContents, oleLength);
if (oleLength < readbytes) {
return "oleLength :" + oleLength + " readbytes: " + readbytes;
}
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(pContents[0], 0, readbytes);
byte[] result = new byte[oleLength];
int resultLength = decompresser.inflate(result);
decompresser.end();
//return the base64 string of the uncompressed data
return Base64.encodeBytes(result);
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
public XStream CreateTempFileStream(XMultiServiceFactory xMSF) {
// try to get temporary file representation
XStream xTempFileStream = null;
try {
Object oTempFile = xMSF.createInstance("com.sun.star.io.TempFile");
xTempFileStream = (XStream) UnoRuntime.queryInterface(XStream.class, oTempFile);
} catch (Exception e) {
}
if (xTempFileStream == null) {
System.out.println("Can't create temporary file!");
}
return xTempFileStream;
}
//decode the base64 string and create an com.sun.star.embed.OLESimpleStorage from it
public void loadRootStorageFromBase64(String aBase64) {
try {
//Decode and write the data to an temp stream
byte[] oledata = Base64.decode(aBase64);
m_RootStream = CreateTempFileStream(m_xMSF);
XOutputStream xOutput = m_RootStream.getOutputStream();
xOutput.writeBytes(oledata);
xOutput.flush();
//Get the input stream and seek to begin
XInputStream xInput = m_RootStream.getInputStream();
XSeekable xSeek = (XSeekable) UnoRuntime.queryInterface(XSeekable.class, xInput);
xSeek.seek(0);
oledata = null;
xSeek = null;
//create an com.sun.star.embed.OLESimpleStorage from the temp stream
Object pArgs[] = new Object[1];
pArgs[0] = (Object) xInput;
Object oTempStorage = m_xMSF.createInstanceWithArguments("com.sun.star.embed.OLESimpleStorage", pArgs);
pArgs = null;
m_Storage = (XNameContainer) UnoRuntime.queryInterface(XNameContainer.class, oTempStorage);
} catch (Exception e) {
e.printStackTrace();
}
}
//Create a empty OLESimpleStorage if there is not one
public void ensureCreateRootStorage() {
if (null == m_RootStream || null == m_Storage) {
try {
m_RootStream = CreateTempFileStream(m_xMSF);
Object pArgs[] = new Object[1];
pArgs[0] = (Object) m_RootStream;
Object oTempStorage = m_xMSF.createInstanceWithArguments("com.sun.star.embed.OLESimpleStorage", pArgs);
pArgs = null;
m_Storage = (XNameContainer) UnoRuntime.queryInterface(XNameContainer.class, oTempStorage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//decode the base64 string and insert the length and the compressed data of it to
//the root storage as a sub stream under aName
public void insertSubStorage(String aName, String aBase64) {
try {
//decode the base64 string
byte[] oledata = Base64.decode(aBase64);
//create a temp stream to write data to
XStream subStream = CreateTempFileStream(m_xMSF);
XInputStream xInput = subStream.getInputStream();
XOutputStream xOutput = subStream.getOutputStream();
//write the length to the temp stream
byte oleHead[] = new byte[4];
oleHead[0] = (byte) ((oledata.length >>> 0) & 0xFF);
oleHead[1] = (byte) ((oledata.length >>> 8) & 0xFF);
oleHead[2] = (byte) ((oledata.length >>> 16) & 0xFF);
oleHead[3] = (byte) ((oledata.length >>> 24) & 0xFF);
xOutput.writeBytes(oleHead);
// Compress the bytes
byte[] output = new byte[oledata.length];
Deflater compresser = new Deflater();
compresser.setInput(oledata);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
//realloc the data length
byte[] compressedBytes = new byte[compressedDataLength];
for (int i = 0; i < compressedDataLength; i++) {
compressedBytes[i] = output[i];
}
//write the compressed data to the temp stream
xOutput.writeBytes(compressedBytes);
//seek to 0
XSeekable xSeek = (XSeekable) UnoRuntime.queryInterface(XSeekable.class, xInput);
xSeek.seek(0);
xSeek = null;
oledata = null;
//insert the temp stream as a sub stream and use an XTransactedObject to commit it immediately
XTransactedObject xTransact = (XTransactedObject) UnoRuntime.queryInterface(XTransactedObject.class, m_Storage);
m_Storage.insertByName(aName, xInput);
xTransact.commit();
xTransact = null;
} catch (Exception e) {
e.printStackTrace();
}
}
/** separtates the uno-url into 3 different parts.
*/
protected static String[] parseUnoUrl(String url) {
String[] aRet = new String[3];
if (!url.startsWith("uno:")) {
return null;
}
int semicolon = url.indexOf(';');
if (semicolon == -1) {
return null;
}
aRet[0] = url.substring(4, semicolon);
int nextSemicolon = url.indexOf(';', semicolon + 1);
if (semicolon == -1) {
return null;
}
aRet[1] = url.substring(semicolon + 1, nextSemicolon);
aRet[2] = url.substring(nextSemicolon + 1);
return aRet;
}
//connect to running OOo and keep an XConnection object so that we can disconnect from OOo as we wish
protected XMultiServiceFactory connectAwareGetServiceFactory() throws com.sun.star.uno.Exception,
com.sun.star.uno.RuntimeException,
Exception {
// Get component context
XComponentContext xComponentContext =
com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);
// instantiate connector service
Object x = xComponentContext.getServiceManager().createInstanceWithContext(
"com.sun.star.connection.Connector", xComponentContext);
XConnector xConnector = (XConnector) UnoRuntime.queryInterface(XConnector.class, x);
String a[] = parseUnoUrl(sConnectionString);
if (null == a) {
throw new com.sun.star.uno.Exception("Couldn't parse uno-url " + sConnectionString);
}
// connect using the connection string part of the uno-url only.
m_Connection = xConnector.connect(a[0]);
x = xComponentContext.getServiceManager().createInstanceWithContext(
"com.sun.star.bridge.BridgeFactory", xComponentContext);
XBridgeFactory xBridgeFactory = (XBridgeFactory) UnoRuntime.queryInterface(
XBridgeFactory.class, x);
// create a nameless bridge with no instance provider
// using the middle part of the uno-url
XBridge bridge = xBridgeFactory.createBridge("", a[1], m_Connection, null);
// query for the XComponent interface and add this as event listener
XComponent xComponent = (XComponent) UnoRuntime.queryInterface(
XComponent.class, bridge);
// get the remote instance
x = bridge.getInstance(a[2]);
// Did the remote server export this object ?
if (null == x) {
throw new com.sun.star.uno.Exception(
"Server didn't provide an instance for" + a[2], null);
}
XMultiServiceFactory xFac = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, x);
return xFac;
}
protected static boolean DEBUG = false;
protected static boolean DEBUGCHK = false;
protected static String debugfile;
protected static void debugln(String s) {
debug(s + "\n");
}
protected static void debug(String s) {
if (!DEBUGCHK) {
if (System.getProperty("xsltfilter.debug") == null) {
DEBUGCHK = true;
return;
} else {
debugfile = System.getProperty("xsltfilter.debug");
DEBUG = true;
}
}
if (!DEBUG) {
return;
}
try {
FileWriter dbgwriter = new FileWriter(debugfile, true);
dbgwriter.write(s);
dbgwriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.batfish.common;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(using = Warnings.Serializer.class)
@JsonDeserialize(using = Warnings.Deserializer.class)
public class Warnings implements Serializable {
public static class Deserializer extends JsonDeserializer<Warnings> {
@Override
public Warnings deserialize(JsonParser parser, DeserializationContext ctx)
throws IOException, JsonProcessingException {
JsonNode node = parser.getCodec().readTree(parser);
Warnings warnings = new Warnings();
if (node.has(PEDANTIC_VAR)) {
JsonNode warningsNode = node.get(PEDANTIC_VAR);
fillWarningList(warnings._pedanticWarnings, warningsNode);
}
if (node.has(RED_FLAGS_VAR)) {
JsonNode warningsNode = node.get(RED_FLAGS_VAR);
fillWarningList(warnings._redFlagWarnings, warningsNode);
}
if (node.has(UNIMPLEMENTED_VAR)) {
JsonNode warningsNode = node.get(UNIMPLEMENTED_VAR);
fillWarningList(warnings._unimplementedWarnings, warningsNode);
}
return warnings;
}
private void fillWarningList(List<Warning> warnings, JsonNode node) {
for (Iterator<Entry<String, JsonNode>> iter = node.fields(); iter
.hasNext();) {
Entry<String, JsonNode> e = iter.next();
String msg = e.getValue().asText();
int colonIndex = msg.indexOf(":");
String tag = msg.substring(0, colonIndex);
String text = msg.substring(colonIndex + 2, msg.length());
Warning warning = new Warning(text, tag);
warnings.add(warning);
}
}
}
public static class Serializer extends JsonSerializer<Warnings> {
@Override
public void serialize(Warnings value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
if (!value._pedanticWarnings.isEmpty()) {
jgen.writeFieldName(PEDANTIC_VAR);
jgen.writeStartObject();
for (int i = 0; i < value._pedanticWarnings.size(); i++) {
Warning taggedWarning = value._pedanticWarnings.get(i);
String text = taggedWarning.getFirst();
String tag = taggedWarning.getSecond();
String msg = tag + ": " + text;
jgen.writeFieldName(Integer.toString(i + 1));
jgen.writeString(msg);
}
jgen.writeEndObject();
}
if (!value._redFlagWarnings.isEmpty()) {
jgen.writeFieldName(RED_FLAGS_VAR);
jgen.writeStartObject();
for (int i = 0; i < value._redFlagWarnings.size(); i++) {
Warning taggedWarning = value._redFlagWarnings.get(i);
String text = taggedWarning.getFirst();
String tag = taggedWarning.getSecond();
String msg = tag + ": " + text;
jgen.writeFieldName(Integer.toString(i + 1));
jgen.writeString(msg);
}
jgen.writeEndObject();
}
if (!value._unimplementedWarnings.isEmpty()) {
jgen.writeFieldName(UNIMPLEMENTED_VAR);
jgen.writeStartObject();
for (int i = 0; i < value._unimplementedWarnings.size(); i++) {
Warning taggedWarning = value._unimplementedWarnings.get(i);
String text = taggedWarning.getFirst();
String tag = taggedWarning.getSecond();
String msg = tag + ": " + text;
jgen.writeFieldName(Integer.toString(i + 1));
jgen.writeString(msg);
}
jgen.writeEndObject();
}
jgen.writeEndObject();
}
}
private static final String PEDANTIC_VAR = "Pedantic complaints";
private static final String RED_FLAGS_VAR = "Red flags";
private static final long serialVersionUID = 1L;
private static final String UNIMPLEMENTED_VAR = "Unimplemented features";
protected final List<Warning> _pedanticWarnings;
protected final List<Warning> _redFlagWarnings;
protected final List<Warning> _unimplementedWarnings;
public Warnings() {
_pedanticWarnings = new ArrayList<Warning>();
_redFlagWarnings = new ArrayList<Warning>();
_unimplementedWarnings = new ArrayList<Warning>();
}
public List<Warning> getPedanticWarnings() {
return _pedanticWarnings;
}
public List<Warning> getRedFlagWarnings() {
return _redFlagWarnings;
}
public List<Warning> getUnimplementedWarnings() {
return _unimplementedWarnings;
}
@JsonIgnore
public boolean isEmpty() {
return _pedanticWarnings.isEmpty() && _redFlagWarnings.isEmpty()
&& _unimplementedWarnings.isEmpty();
}
}
|
package com.yahoo.vespa.flags;
import com.yahoo.component.Vtag;
import com.yahoo.vespa.defaults.Defaults;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
/**
* Definitions of feature flags.
*
* <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag}
* or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p>
*
* <ol>
* <li>The unbound flag</li>
* <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding
* an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li>
* <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should
* declare this in the unbound flag definition in this file (referring to
* {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g.
* {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li>
* </ol>
*
* <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically
* there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p>
*
* @author hakonhall
*/
public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Default limit for when to apply termwise query evaluation",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag(
"feed-sequencer-type", "LATENCY",
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment (requires restart)",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag FEED_TASK_LIMIT = defineIntFlag(
"feed-task-limit", 1000,
List.of("geirst, baldersheim"), "2021-10-14", "2022-01-01",
"The task limit used by the executors handling feed in proton",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag FEED_MASTER_TASK_LIMIT = defineIntFlag(
"feed-master-task-limit", 0,
List.of("geirst, baldersheim"), "2021-11-18", "2022-02-01",
"The task limit used by the master thread in each document db in proton. Ignored when set to 0.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag SHARED_FIELD_WRITER_EXECUTOR = defineStringFlag(
"shared-field-writer-executor", "NONE",
List.of("geirst, baldersheim"), "2021-11-05", "2022-02-01",
"Whether to use a shared field writer executor for the document database(s) in proton. " +
"Valid values: NONE, INDEX, INDEX_AND_ATTRIBUTE, DOCUMENT_DB",
"Takes effect at redeployment (requires restart)",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag(
"max-uncommitted-memory", 130000,
List.of("geirst, baldersheim"), "2021-10-21", "2022-01-01",
"Max amount of memory holding updates to an attribute before we do a commit.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag(
"response-sequencer-type", "ADAPTIVE",
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag(
"response-num-threads", 2,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Number of threads used for mbus responses, default is 2, negative number = numcores/4",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag(
"skip-communicationmanager-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the communicationmanager thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag(
"skip-mbus-request-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus request thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag(
"skip-mbus-reply-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus reply thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag(
"use-three-phase-updates", false,
List.of("vekterli"), "2020-12-02", "2022-01-01",
"Whether to enable the use of three-phase updates when bucket replicas are out of sync.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag(
"hide-shared-routing-endpoint", false,
List.of("tokle", "bjormel"), "2020-12-02", "2022-01-01",
"Whether the controller should hide shared routing layer endpoint",
"Takes effect immediately",
APPLICATION_ID
);
public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag(
"async-message-handling-on-schedule", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Optionally deliver async messages in own thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag(
"feed-concurrency", 0.5,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"How much concurrency should be allowed for feed",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag DISK_BLOAT_FACTOR = defineDoubleFlag(
"disk-bloat-factor", 0.2,
List.of("baldersheim"), "2021-10-08", "2022-01-01",
"Amount of bloat allowed before compacting file",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag DOCSTORE_COMPRESSION_LEVEL = defineIntFlag(
"docstore-compression-level", 3,
List.of("baldersheim"), "2021-10-08", "2022-01-01",
"Default compression level used for document store",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag NUM_DEPLOY_HELPER_THREADS = defineIntFlag(
"num-model-builder-threads", -1,
List.of("balder"), "2021-09-09", "2022-01-01",
"Number of threads used for speeding up building of models.",
"Takes effect on first (re)start of config server");
public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag(
"enable-feed-block-in-distributor", true,
List.of("geirst"), "2021-01-27", "2022-01-31",
"Enables blocking of feed in the distributor if resource usage is above limit on at least one content node",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag(
"container-dump-heap-on-shutdown-timeout", false,
List.of("baldersheim"), "2021-09-25", "2022-01-01",
"Will trigger a heap dump during if container shutdown times out",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag(
"container-shutdown-timeout", 50.0,
List.of("baldersheim"), "2021-09-25", "2022-01-01",
"Timeout for shutdown of a jdisc container",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag(
"allowed-athenz-proxy-identities", List.of(), String.class,
List.of("bjorncs", "tokle"), "2021-02-10", "2022-02-01",
"Allowed Athenz proxy identities",
"takes effect at redeployment");
public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag(
"generate-non-mtls-endpoint", true,
List.of("tokle"), "2021-02-18", "2022-02-01",
"Whether to generate the non-mtls endpoint",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag(
"max-activation-inhibited-out-of-sync-groups", 0,
List.of("vekterli"), "2021-02-19", "2022-02-01",
"Allows replicas in up to N content groups to not be activated " +
"for query visibility if they are out of sync with a majority of other replicas",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag(
"max-concurrent-merges-per-node", 128,
List.of("balder", "vekterli"), "2021-06-06", "2022-01-01",
"Specifies max concurrent merges per content node.",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag(
"max-merge-queue-size", 1024,
List.of("balder", "vekterli"), "2021-06-06", "2022-01-01",
"Specifies max size of merge queue.",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag IGNORE_MERGE_QUEUE_LIMIT = defineFeatureFlag(
"ignore-merge-queue-limit", false,
List.of("vekterli", "geirst"), "2021-10-06", "2022-03-01",
"Specifies if merges that are forwarded (chained) from another content node are always " +
"allowed to be enqueued even if the queue is otherwise full.",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag LARGE_RANK_EXPRESSION_LIMIT = defineIntFlag(
"large-rank-expression-limit", 8192,
List.of("baldersheim"), "2021-06-09", "2022-01-01",
"Limit for size of rank expressions distributed by filedistribution",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag(
"min-node-ratio-per-group", 0.0,
List.of("geirst", "vekterli"), "2021-07-16", "2022-03-01",
"Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SEPARATE_TENANT_IAM_ROLES = defineFeatureFlag(
"separate-tenant-iam-roles", false,
List.of("mortent"), "2021-08-12", "2022-01-01",
"Create separate iam roles for tenant",
"Takes effect on redeploy",
TENANT_ID);
public static final UnboundIntFlag METRICSPROXY_NUM_THREADS = defineIntFlag(
"metricsproxy-num-threads", 2,
List.of("balder"), "2021-09-01", "2022-01-01",
"Number of threads for metrics proxy",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag(
"enabled-horizon-dashboard", false,
List.of("olaa"), "2021-09-13", "2021-12-31",
"Enable Horizon dashboard",
"Takes effect immediately",
TENANT_ID, CONSOLE_USER_EMAIL
);
public static final UnboundBooleanFlag ENABLE_ONPREM_TENANT_S3_ARCHIVE = defineFeatureFlag(
"enable-onprem-tenant-s3-archive", false,
List.of("bjorncs"), "2021-09-14", "2021-12-31",
"Enable tenant S3 buckets in cd/main. Must be set on controller cluster only.",
"Takes effect immediately",
ZONE_ID, TENANT_ID
);
public static final UnboundBooleanFlag DELETE_UNMAINTAINED_CERTIFICATES = defineFeatureFlag(
"delete-unmaintained-certificates", false,
List.of("andreer"), "2021-09-23", "2021-12-11",
"Whether to delete certificates that are known by provider but not by controller",
"Takes effect on next run of EndpointCertificateMaintainer"
);
public static final UnboundBooleanFlag ENABLE_TENANT_DEVELOPER_ROLE = defineFeatureFlag(
"enable-tenant-developer-role", false,
List.of("bjorncs"), "2021-09-23", "2021-12-31",
"Enable tenant developer Athenz role in cd/main. Must be set on controller cluster only.",
"Takes effect immediately",
TENANT_ID
);
public static final UnboundBooleanFlag ENABLE_ROUTING_REUSE_PORT = defineFeatureFlag(
"enable-routing-reuse-port", false,
List.of("mortent"), "2021-09-29", "2021-12-31",
"Enable reuse port in routing configuration",
"Takes effect on container restart",
HOSTNAME
);
public static final UnboundBooleanFlag ENABLE_TENANT_OPERATOR_ROLE = defineFeatureFlag(
"enable-tenant-operator-role", false,
List.of("bjorncs"), "2021-09-29", "2021-12-31",
"Enable tenant specific operator roles in public systems. For controllers only.",
"Takes effect on subsequent maintainer invocation",
TENANT_ID
);
public static final UnboundIntFlag DISTRIBUTOR_MERGE_BUSY_WAIT = defineIntFlag(
"distributor-merge-busy-wait", 10,
List.of("geirst", "vekterli"), "2021-10-04", "2022-03-01",
"Number of seconds that scheduling of new merge operations in the distributor should be inhibited " +
"towards a content node that has indicated merge busy",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag DISTRIBUTOR_ENHANCED_MAINTENANCE_SCHEDULING = defineFeatureFlag(
"distributor-enhanced-maintenance-scheduling", false,
List.of("vekterli", "geirst"), "2021-10-14", "2022-01-31",
"Enable enhanced maintenance operation scheduling semantics on the distributor",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag ASYNC_APPLY_BUCKET_DIFF = defineFeatureFlag(
"async-apply-bucket-diff", false,
List.of("geirst", "vekterli"), "2021-10-22", "2022-01-31",
"Whether portions of apply bucket diff handling will be performed asynchronously",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag UNORDERED_MERGE_CHAINING = defineFeatureFlag(
"unordered-merge-chaining", false,
List.of("vekterli", "geirst"), "2021-11-15", "2022-03-01",
"Enables the use of unordered merge chains for data merge operations",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag JDK_VERSION = defineStringFlag(
"jdk-version", "11",
List.of("hmusum"), "2021-10-25", "2022-03-01",
"JDK version to use on host and inside containers. Note application-id dimension only applies for container, " +
"while hostname and node type applies for host.",
"Takes effect on restart for Docker container and on next host-admin tick for host",
APPLICATION_ID,
TENANT_ID,
HOSTNAME,
NODE_TYPE);
public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag(
"ignore-thread-stack-sizes", false,
List.of("arnej"), "2021-11-12", "2022-01-31",
"Whether C++ thread creation should ignore any requested stack size",
"Triggers restart, takes effect immediately",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_FILE_DISTRIBUTION_CONNECTION_POOL = defineFeatureFlag(
"use-file-distribution-connection-pool", true,
List.of("hmusum"), "2021-11-16", "2021-12-16",
"Whether to use FileDistributionConnectionPool instead of JRTConnectionPool for file downloads",
"Takes effect on config server restart",
ZONE_ID);
public static final UnboundBooleanFlag CONFIG_PROXY_USE_FILE_DISTRIBUTION_CONNECTION_POOL = defineFeatureFlag(
"config-proxy-use-file-distribution-connection-pool", false,
List.of("hmusum"), "2021-11-25", "2021-12-25",
"Whether to use FileDistributionConnectionPool instead of JRTConnectionPool for file downloads in config proxy",
"Takes effect on container reboot",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag(
"use-v8-geo-positions", false,
List.of("arnej"), "2021-11-15", "2022-12-31",
"Use Vespa 8 types and formats for geographical positions",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_LEGACY_LB_SERVICES = defineFeatureFlag(
"use-legacy-lb-services", true,
List.of("tokle"), "2021-11-22", "2021-12-31",
"Whether to generate routing table based on legacy lb-services config",
"Takes effect on container reboot",
ZONE_ID, HOSTNAME);
public static final UnboundBooleanFlag CHANGE_ROUTING_STATUS_OF_ALL_UPSTREAMS = defineFeatureFlag(
"change-routing-status-of-all-upstreams", false,
List.of("mpolden"), "2021-12-02", "2021-12-15",
"Whether the controller should send all known upstreams to configserver when changing routing status of a deployment",
"Takes effect on the next change in routing status");
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass,
List<String> owners, String createdAt, String expiresAt,
String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
@FunctionalInterface
private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> {
U create(FlagId id, T defaultVale, FetchVector defaultFetchVector);
}
/**
* Defines a Flag.
*
* @param factory Factory for creating unbound flag of type U
* @param flagId The globally unique FlagId.
* @param defaultValue The default value if none is present after resolution.
* @param description Description of how the flag is used.
* @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc.
* @param dimensions What dimensions will be set in the {@link FetchVector} when fetching
* the flag value in
* {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}.
* For instance, if APPLICATION is one of the dimensions here, you should make sure
* APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag
* from the FlagSource.
* @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features.
* @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag.
* @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and
* {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment
* is typically implicit.
*/
private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory,
String flagId,
T defaultValue,
List<String> owners,
String createdAt,
String expiresAt,
String description,
String modificationEffect,
FetchVector.Dimension[] dimensions) {
FlagId id = new FlagId(flagId);
FetchVector vector = new FetchVector()
.with(HOSTNAME, Defaults.getDefaults().vespaHostname())
// Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0
// (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0.
.with(VESPA_VERSION, Vtag.currentVersion.toFullString());
U unboundFlag = factory.create(id, defaultValue, vector);
FlagDefinition definition = new FlagDefinition(
unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions);
flags.put(id, definition);
return unboundFlag;
}
private static Instant parseDate(String rawDate) {
return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC);
}
public static List<FlagDefinition> getAllFlags() {
return List.copyOf(flags.values());
}
public static Optional<FlagDefinition> getFlag(FlagId flagId) {
return Optional.ofNullable(flags.get(flagId));
}
/**
* Allows the statically defined flags to be controlled in a test.
*
* <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block,
* the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from
* before the block is reinserted.
*
* <p>NOT thread-safe. Tests using this cannot run in parallel.
*/
public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) {
return new Replacer(flagsToKeep);
}
public static class Replacer implements AutoCloseable {
private static volatile boolean flagsCleared = false;
private final TreeMap<FlagId, FlagDefinition> savedFlags;
private Replacer(FlagId... flagsToKeep) {
verifyAndSetFlagsCleared(true);
this.savedFlags = Flags.flags;
Flags.flags = new TreeMap<>();
List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id)));
}
@Override
public void close() {
verifyAndSetFlagsCleared(false);
Flags.flags = savedFlags;
}
/**
* Used to implement a simple verification that Replacer is not used by multiple threads.
* For instance two different tests running in parallel cannot both use Replacer.
*/
private static void verifyAndSetFlagsCleared(boolean newValue) {
if (flagsCleared == newValue) {
throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?");
}
flagsCleared = newValue;
}
}
}
|
package org.batfish.datamodel;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonPropertyOrder({ Route.DIFF_SYMBOL_VAR })
@JsonInclude(Include.NON_NULL)
public class Route implements Comparable<Route>, Serializable {
private static final String ADMINISTRATIVE_COST_VAR = "administrativeCost";
public static final String AMBIGUOUS_NEXT_HOP = "(ambiguous)";
protected static final String DIFF_SYMBOL_VAR = "diffSymbol";
private static final String METRIC_VAR = "metric";
private static final String NETWORK_VAR = "network";
private static final String NEXT_HOP_INTERFACE_VAR = "nextHopInterface";
private static final String NEXT_HOP_IP_VAR = "nextHopIp";
private static final String NEXT_HOP_VAR = "nextHop";
private static final String NODE_VAR = "node";
private static final String PROTOCOL_VAR = "protocol";
private static final long serialVersionUID = 1L;
private static final String TAG_VAR = "tag";
public static final String UNSET_NEXT_HOP = "(unknown)";
public static final String UNSET_NEXT_HOP_INTERFACE = "dynamic";
public static final int UNSET_ROUTE_ADMIN = -1;
public static final int UNSET_ROUTE_COST = -1;
public static final Ip UNSET_ROUTE_NEXT_HOP_IP = new Ip(-1l);
public static final int UNSET_ROUTE_TAG = -1;
private final int _administrativeCost;
private transient String _diffSymbol;
private final int _metric;
private final Prefix _network;
private final transient String _nextHop;
private final String _nextHopInterface;
private final Ip _nextHopIp;
private final String _node;
private final RoutingProtocol _protocol;
private final int _tag;
@JsonCreator
public Route(@JsonProperty(NODE_VAR) String node,
@JsonProperty(NETWORK_VAR) Prefix network,
@JsonProperty(NEXT_HOP_IP_VAR) Ip nextHopIp,
@JsonProperty(NEXT_HOP_VAR) String nextHop,
@JsonProperty(NEXT_HOP_INTERFACE_VAR) String nextHopInterface,
@JsonProperty(ADMINISTRATIVE_COST_VAR) int administrativeCost,
@JsonProperty(METRIC_VAR) int metric,
@JsonProperty(PROTOCOL_VAR) RoutingProtocol protocol,
@JsonProperty(TAG_VAR) int tag) {
_network = network;
_nextHopIp = nextHopIp;
_node = node;
_nextHop = nextHop;
_nextHopInterface = nextHopInterface;
_administrativeCost = administrativeCost;
_metric = metric;
_protocol = protocol;
_tag = tag;
}
@Override
public int compareTo(Route rhs) {
int result = _node.compareTo(rhs._node);
if (result != 0) {
return result;
}
result = _network.compareTo(rhs._network);
if (result != 0) {
return result;
}
result = _nextHopIp.compareTo(rhs._nextHopIp);
if (result != 0) {
return result;
}
result = Integer.compare(_administrativeCost, rhs._administrativeCost);
if (result != 0) {
return result;
}
result = Integer.compare(_metric, rhs._metric);
if (result != 0) {
return result;
}
result = _protocol.compareTo(rhs._protocol);
if (result != 0) {
return result;
}
result = Integer.compare(_tag, rhs._tag);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
Route other = (Route) obj;
if (_administrativeCost != other._administrativeCost) {
return false;
}
if (_metric != other._metric) {
return false;
}
if (!_nextHopIp.equals(other._nextHopIp)) {
return false;
}
if (!_node.equals(other._node)) {
return false;
}
if (!_network.equals(other._network)) {
return false;
}
if (_protocol != other._protocol) {
return false;
}
if (_tag != other._tag) {
return false;
}
return true;
}
@JsonProperty(ADMINISTRATIVE_COST_VAR)
public int getAdministrativeCost() {
return _administrativeCost;
}
@JsonProperty(DIFF_SYMBOL_VAR)
public String getDiffSymbol() {
return _diffSymbol;
}
@JsonProperty(METRIC_VAR)
public int getMetric() {
return _metric;
}
@JsonProperty(NETWORK_VAR)
public Prefix getNetwork() {
return _network;
}
@JsonProperty(NEXT_HOP_VAR)
public String getNextHop() {
return _nextHop;
}
@JsonProperty(NEXT_HOP_INTERFACE_VAR)
public String getNextHopInterface() {
return _nextHopInterface;
}
@JsonProperty(NEXT_HOP_IP_VAR)
public Ip getNextHopIp() {
return _nextHopIp;
}
@JsonProperty(NODE_VAR)
public String getNode() {
return _node;
}
@JsonProperty(PROTOCOL_VAR)
public RoutingProtocol getProtocol() {
return _protocol;
}
@JsonProperty(TAG_VAR)
public int getTag() {
return _tag;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + _administrativeCost;
result = prime * result + _metric;
result = prime * result + _nextHopIp.hashCode();
result = prime * result + _node.hashCode();
result = prime * result + _network.hashCode();
result = prime * result + _protocol.hashCode();
result = prime * result + _tag;
return result;
}
@JsonProperty(DIFF_SYMBOL_VAR)
public void setDiffSymbol(String diffSymbol) {
_diffSymbol = diffSymbol;
}
@Override
public String toString() {
String nextHop = _nextHop;
String nextHopIp = _nextHopIp.toString();
String tag = Integer.toString(_tag);
// extra formatting
if (!_nextHopInterface.equals(UNSET_NEXT_HOP_INTERFACE)) {
// static interface
if (_nextHopIp.equals(UNSET_ROUTE_NEXT_HOP_IP)) {
nextHop = "N/A";
nextHopIp = "N/A";
}
}
if (_tag == UNSET_ROUTE_TAG) {
tag = "none";
}
return "Route<" + _node.toString() + ", " + _network.toString() + ", "
+ nextHopIp.toString() + ", " + nextHop.toString() + ", "
+ _nextHopInterface.toString() + ", " + _administrativeCost + ", "
+ _metric + ", " + tag + ", " + _protocol.toString() + ">";
}
}
|
package com.yahoo.vespa.flags;
import com.yahoo.component.Vtag;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.flags.custom.PreprovisionCapacity;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
/**
* Definitions of feature flags.
*
* <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag}
* or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p>
*
* <ol>
* <li>The unbound flag</li>
* <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding
* an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li>
* <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should
* declare this in the unbound flag definition in this file (referring to
* {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g.
* {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li>
* </ol>
*
* <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically
* there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p>
*
* @author hakonhall
*/
public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
public static final UnboundIntFlag DROP_CACHES = defineIntFlag("drop-caches", 3,
"The int value to write into /proc/sys/vm/drop_caches for each tick. " +
"1 is page cache, 2 is dentries inodes, 3 is both page cache and dentries inodes, etc.",
"Takes effect on next tick.",
HOSTNAME);
public static final UnboundBooleanFlag ENABLE_CROWDSTRIKE = defineFeatureFlag(
"enable-crowdstrike", true,
"Whether to enable CrowdStrike.", "Takes effect on next host admin tick",
HOSTNAME);
public static final UnboundBooleanFlag ENABLE_NESSUS = defineFeatureFlag(
"enable-nessus", true,
"Whether to enable Nessus.", "Takes effect on next host admin tick",
HOSTNAME);
public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag(
"disabled-host-admin-tasks", List.of(), String.class,
"List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask) that should be skipped",
"Takes effect on next host admin tick",
HOSTNAME, NODE_TYPE);
public static final UnboundStringFlag DOCKER_VERSION = defineStringFlag(
"docker-version", "1.13.1-91.git07f3374",
"The version of the docker to use of the format VERSION-REL: The YUM package to be installed will be " +
"2:docker-VERSION-REL.el7.centos.x86_64 in AWS (and without '.centos' otherwise). " +
"If docker-version is not of this format, it must be parseable by YumPackageName::fromString.",
"Takes effect on next tick.",
HOSTNAME);
public static final UnboundLongFlag THIN_POOL_GB = defineLongFlag(
"thin-pool-gb", -1,
"The size of the disk reserved for the thin pool with dynamic provisioning in AWS, in base-2 GB. " +
"If <0, the default is used (which may depend on the zone and node type).",
"Takes effect immediately (but used only during provisioning).",
NODE_TYPE);
public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag(
"container-cpu-cap", 0,
"Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " +
"to cap CPU at 200%, set this to 2, etc.",
"Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart",
HOSTNAME, APPLICATION_ID);
public static final UnboundBooleanFlag USE_BUCKET_SPACE_METRIC = defineFeatureFlag(
"use-bucket-space-metric", true,
"Whether to use vds.datastored.bucket_space.buckets_total (true) instead of " +
"vds.datastored.alldisks.buckets (false, legacy).",
"Takes effect on the next deployment of the application",
APPLICATION_ID);
public static final UnboundStringFlag TLS_INSECURE_MIXED_MODE = defineStringFlag(
"tls-insecure-mixed-mode", "tls_client_mixed_server",
"TLS insecure mixed mode. Allowed values: ['plaintext_client_mixed_server', 'tls_client_mixed_server', 'tls_client_tls_server']",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundStringFlag TLS_INSECURE_AUTHORIZATION_MODE = defineStringFlag(
"tls-insecure-authorization-mode", "log_only",
"TLS insecure authorization mode. Allowed values: ['disable', 'log_only', 'enforce']",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundBooleanFlag USE_ADAPTIVE_DISPATCH = defineFeatureFlag(
"use-adaptive-dispatch", false,
"Should adaptive dispatch be used over round robin",
"Takes effect at redeployment",
APPLICATION_ID);
public static final UnboundIntFlag REBOOT_INTERVAL_IN_DAYS = defineIntFlag(
"reboot-interval-in-days", 30,
"No reboots are scheduled 0x-1x reboot intervals after the previous reboot, while reboot is " +
"scheduled evenly distributed in the 1x-2x range (and naturally guaranteed at the 2x boundary).",
"Takes effect on next run of NodeRebooter");
public static final UnboundBooleanFlag ENABLE_LARGE_ORCHESTRATOR_LOCKS = defineFeatureFlag(
"enable-large-orchestrator-locks", true,
"If enabled, the orchestrator will accumulate application locks during probe in batch suspension, " +
"and release them in reverse order only after the non-probe is complete. Can be set depending on " +
"parent hostname.",
"Takes immediate effect for new batch suspensions.",
HOSTNAME);
public static final UnboundBooleanFlag ENABLE_DYNAMIC_PROVISIONING = defineFeatureFlag(
"enable-dynamic-provisioning", false,
"Provision a new docker host when we otherwise can't allocate a docker node",
"Takes effect on next deployment",
APPLICATION_ID);
public static final UnboundListFlag<PreprovisionCapacity> PREPROVISION_CAPACITY = defineListFlag(
"preprovision-capacity", List.of(), PreprovisionCapacity.class,
"List of node resources and their count that should be present in zone to receive new deployments. When a " +
"preprovisioned is taken, new will be provisioned within next iteration of maintainer.",
"Takes effect on next iteration of HostProvisionMaintainer.");
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
"Node resource memory in Gb for admin cluster nodes",
"Takes effect at redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag HOST_HARDENING = defineFeatureFlag(
"host-hardening", false,
"Whether to enable host hardening Linux baseline.",
"Takes effect on next tick or on host-admin restart (may vary where used).",
HOSTNAME);
public static final UnboundStringFlag ZOOKEEPER_SERVER_MAJOR_MINOR_VERSION = defineStringFlag(
"zookeeper-server-version", "3.5",
"The version of ZooKeeper server to use (major.minor, not full version)",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_QUORUM_COMMUNICATION = defineStringFlag(
"tls-for-zookeeper-quorum-communication", "OFF",
"How to setup TLS for ZooKeeper quorum communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY",
"Takes effect on restart of config server",
NODE_TYPE, HOSTNAME);
public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag(
"tls-for-zookeeper-client-server-communication", "OFF",
"How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY",
"Takes effect on restart of config server",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag(
"use-tls-for-zookeeper-client", false,
"Whether to use TLS for ZooKeeper clients",
"Takes effect on restart of process",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag ENABLE_DISK_WRITE_TEST = defineFeatureFlag(
"enable-disk-write-test", false,
"Regularly issue a small write to disk and fail the host if it is not successful",
"Takes effect on next node agent tick (but does not clear existing failure reports)",
HOSTNAME);
public static final UnboundBooleanFlag DISABLE_CM3 = defineFeatureFlag(
"disable-cm3", false,
"Whether to disable CM3.", "Takes effect on next host admin tick",
HOSTNAME);
public static final UnboundBooleanFlag USE_4443_UPSTREAM = defineFeatureFlag(
"use-4443-upstream", false,
"Use port 4443 for nginx upstream",
"Takes effect when routing container asks for new config",
APPLICATION_ID);
public static final UnboundBooleanFlag ENABLE_IN_PLACE_RESIZE = defineFeatureFlag(
"enable-in-place-resize", false,
"Whether nodes can be resized in-place when certain conditions are met",
"Takes effect on next deployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_CONFIG_SERVER_FOR_TESTER_API_CALLS = defineFeatureFlag(
"use-config-server-for-tester-api-calls", false,
"Whether controller should send requests to tester API through config server (if false) or tester endpoint (if true)",
"Takes effect immediately",
ZONE_ID);
public static final UnboundBooleanFlag GENERATE_L4_ROUTING_CONFIG = defineFeatureFlag(
"generate-l4-routing-config", false,
"Whether routing nodes should generate L4 routing config",
"Takes effect immediately",
ZONE_ID, HOSTNAME);
public static final UnboundBooleanFlag GENERATE_ROUTING_CONFIG_FOR_TESTER_APPLICATIONS = defineFeatureFlag(
"generate-routing-config-for-tester-applications", false,
"Whether config server should generate routing config (lb-services) for tester applications",
"Takes effect on the next deployment of the routing (zone) application",
ZONE_ID);
public static final UnboundBooleanFlag USE_REFRESHED_ENDPOINT_CERTIFICATE = defineFeatureFlag(
"use-refreshed-endpoint-certificate", false,
"Whether an application should start using a newer certificate/key pair if available",
"Takes effect on the next deployment of the application",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_NEW_ATHENZ_FILTER = defineFeatureFlag(
"use-new-athenz-filter", false,
"Use new Athenz filter that supports access-tokens",
"Takes effect at redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_RPM_PACKAGES_FOR_DATA_HIGHWAY = defineFeatureFlag(
"use-rpm-packages-for-data-highway", false,
"Whether RPM packages should be used for Data Highway",
"Takes effect on restart of Docker container",
ZONE_ID, APPLICATION_ID);
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundBooleanFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundStringFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundIntFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundLongFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundDoubleFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass),
flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass,
String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec),
flagId, defaultValue, description, modificationEffect, dimensions);
}
@FunctionalInterface
private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> {
U create(FlagId id, T defaultVale, FetchVector defaultFetchVector);
}
/**
* Defines a Flag.
*
* @param factory Factory for creating unbound flag of type U
* @param flagId The globally unique FlagId.
* @param defaultValue The default value if none is present after resolution.
* @param description Description of how the flag is used.
* @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc.
* @param dimensions What dimensions will be set in the {@link FetchVector} when fetching
* the flag value in
* {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}.
* For instance, if APPLICATION is one of the dimensions here, you should make sure
* APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag
* from the FlagSource.
* @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features.
* @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag.
* @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and
* {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment
* is typically implicit.
*/
private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory,
String flagId,
T defaultValue,
String description,
String modificationEffect,
FetchVector.Dimension[] dimensions) {
FlagId id = new FlagId(flagId);
FetchVector vector = new FetchVector()
.with(HOSTNAME, Defaults.getDefaults().vespaHostname())
// Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0
// (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0.
.with(VESPA_VERSION, Vtag.currentVersion.toFullString());
U unboundFlag = factory.create(id, defaultValue, vector);
FlagDefinition definition = new FlagDefinition(unboundFlag, description, modificationEffect, dimensions);
flags.put(id, definition);
return unboundFlag;
}
public static List<FlagDefinition> getAllFlags() {
return List.copyOf(flags.values());
}
public static Optional<FlagDefinition> getFlag(FlagId flagId) {
return Optional.ofNullable(flags.get(flagId));
}
/**
* Allows the statically defined flags to be controlled in a test.
*
* <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block,
* the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from
* before the block is reinserted.
*
* <p>NOT thread-safe. Tests using this cannot run in parallel.
*/
public static Replacer clearFlagsForTesting() {
return new Replacer();
}
public static class Replacer implements AutoCloseable {
private static volatile boolean flagsCleared = false;
private final TreeMap<FlagId, FlagDefinition> savedFlags;
private Replacer() {
verifyAndSetFlagsCleared(true);
this.savedFlags = Flags.flags;
Flags.flags = new TreeMap<>();
}
@Override
public void close() {
verifyAndSetFlagsCleared(false);
Flags.flags = savedFlags;
}
/**
* Used to implement a simple verification that Replacer is not used by multiple threads.
* For instance two different tests running in parallel cannot both use Replacer.
*/
private static void verifyAndSetFlagsCleared(boolean newValue) {
if (flagsCleared == newValue) {
throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?");
}
flagsCleared = newValue;
}
}
}
|
/**
*
* This is the view to place into a layout to implement ormma functionality.
* It can be used either via xml or programatically
*
* It is a subclass of the standard WebView which brings with it all the standard
* functionality as well as the inherent bugs on some os versions.
*
* Webviews have a tendency to leak on orientation in older versions of the android OS
* this can be minimized by using an application context, but this will break the launching
* of subwindows (such as alert calls from javascript)
*
*
*/
package com.ormma.view;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;
import android.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.TypedArray;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.webkit.JsResult;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import com.ormma.controller.OrmmaController.Dimensions;
import com.ormma.controller.OrmmaController.Properties;
import com.ormma.controller.OrmmaUtilityController;
/**
* This is the view to place into a layout to implement ormma functionality. It
* can be used either via xml or programatically
*
* It is a subclass of the standard WebView which brings with it all the
* standard functionality as well as the inherent bugs on some os versions.
*
* Webviews have a tendency to leak on orientation in older versions of the
* android OS this can be minimized by using an application context, but this
* will break the launching of subwindows (such as alert calls from javascript)
*
* It is important to not use any of the layout constants elsewhere in the same
* view as things will get confused. Normally this is not an issue as generated
* layout constants will not interfere.
*/
public class OrmmaView extends WebView implements OnGlobalLayoutListener {
/**
* enum representing possible view states
*/
public enum ViewState {
DEFAULT,
RESIZED,
EXPANDED,
HIDDEN,
LEFT_BEHIND,
OPENED;
}
//static for accessing xml attributes
private static int[] attrs = { R.attr.maxWidth, R.attr.maxHeight };
// Messaging constants
private static final int MESSAGE_RESIZE = 1000;
private static final int MESSAGE_CLOSE = 1001;
private static final int MESSAGE_HIDE = 1002;
private static final int MESSAGE_SHOW = 1003;
private static final int MESSAGE_EXPAND = 1004;
private static final int MESSAGE_SEND_EXPAND_CLOSE = 1005;
private static final int MESSAGE_OPEN = 1006;
// Extra constants
private static final String EXPAND_DIMENSIONS = "expand_initial_dimensions";
private static final String EXPAND_URL = "expand_url";
private static final String EXPAND_PROPERTIES = "expand_properties";
private static final String RESIZE_WIDTH = "resize_width";
private static final String RESIZE_HEIGHT = "resize_height";
private static final String CURRENT_FILE = "_ormma_current";
private static final String AD_PATH = "AD_PATH";
// Debug message constant
private static final String TAG = "OrmmaView";
// layout constants
protected static final int BACKGROUND_ID = 101;
protected static final int PLACEHOLDER_ID = 100;
public static final int ORMMA_ID = 102;
// private constants
private TimeOut mTimeOut; // timeout for loading a url
private static String mScriptPath = null; // holds the path for the ormma.js
private static String mBridgeScriptPath = null; // holds the path for the
// ormma_bridge.js
private boolean bPageFinished = false; // boolean flag holding the loading
// state of a page
private OrmmaUtilityController mUtilityController; // primary javascript
// bridge
private float mDensity; // screen pixel density
private int mContentViewHeight; // height of the content
private boolean bKeyboardOut; // state of the keyboard
private int mDefaultHeight; // default height of the view
private int mDefaultWidth; // default width of the view
private int mInitLayoutHeight; // initial height of the view
private int mInitLayoutWidth; // initial height of the view
private int mIndex; // index of the view within its viewgroup
private GestureDetector mGestureDetector; // gesture detector for capturing
// unwanted gestures
private ViewState mViewState = ViewState.DEFAULT; //holds current view state
private OrmmaViewListener mListener; //listener for communicated events (back to the parent)
public String mDataToInject = null; //javascript to inject into the view
private String mLocalFilePath; //local path the the ad html
/**
* Instantiates a new ormma view.
*
* @param context
* the context
* @param listener
* the listener
*/
public OrmmaView(Context context, OrmmaViewListener listener) {
super(context);
setListener(listener);
setScrollContainer(false);
setVerticalScrollBarEnabled(false);
setHorizontalScrollBarEnabled(false);
mGestureDetector = new GestureDetector(new ScrollEater());
initialize();
}
/**
* Sets the listener.
*
* @param listener
* the new listener
*/
public void setListener(OrmmaViewListener listener) {
mListener = listener;
}
/**
* Removes the listener.
*/
public void removeListener() {
mListener = null;
}
/**
* Instantiates a new ormma view.
*
* @param context
* the context
*/
public OrmmaView(Context context) {
super(context);
setScrollContainer(false);
setVerticalScrollBarEnabled(false);
setHorizontalScrollBarEnabled(false);
mGestureDetector = new GestureDetector(new ScrollEater());
initialize();
}
/**
* Sets the max size.
*
* @param w
* the width
* @param h
* the height
*/
public void setMaxSize(int w, int h) {
mUtilityController.setMaxSize(w, h);
}
/**
* The listener interface for receiving ormmaView events. The class that is
* interested in processing a ormmaView event implements this interface, and
* the object created with that class is registered with a component using
* the component's <code>addOrmmaViewListener<code> method. When
* the ormmaView event occurs, that object's appropriate
* method is invoked.
*
* @see OrmmaViewEvent
*/
public interface OrmmaViewListener {
/**
* On ready.
*
* @return true, if successful
*/
abstract boolean onReady();
/**
* On resize.
*
* @return true, if successful
*/
abstract boolean onResize();
/**
* On expand.
*
* @return true, if successful
*/
abstract boolean onExpand();
/**
* On expand close.
*
* @return true, if successful
*/
abstract boolean onExpandClose();
/**
* On resize close.
*
* @return true, if successful
*/
abstract boolean onResizeClose();
/**
* On event fired.
*
* @return true, if successful
*/
abstract boolean onEventFired();
}
/**
* Inject java script into the view
*
* @param str
* the javascript to inject
*/
public void injectJavaScript(String str) {
if (str != null)
super.loadUrl("javascript:" + str);
}
/**
* Load a url into the view
*
* @param url
* the url
* @param dataToInject
* any additional javascript to inject
*/
public void loadUrl(String url, String dataToInject) {
loadUrl(url, false, dataToInject);
}
/*
* @see android.webkit.WebView#loadUrl(java.lang.String)
*/
@Override
public void loadUrl(String url) {
loadUrl(url, false, null);
}
/**
* Load view from html in a local file
*
* @param f
* the file
* @param dataToInject
* any additional javascript to inject
*/
public void loadFile(File f, String dataToInject) {
try {
mDataToInject = dataToInject;
loadInputStream(new FileInputStream(f), dataToInject);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* The Class TimeOut. A timertask for terminating the load if it takes too long
* If it fires three times without making progress, it will cancel the load
*/
class TimeOut extends TimerTask {
int mProgress = 0;
int mCount = 0;
@Override
public void run() {
int progress = getProgress();
if (progress == 100) {
this.cancel();
} else {
if (mProgress == progress) {
mCount++;
if (mCount == 3) {
try{
stopLoading();
}
catch (Exception e){
Log.w(TAG, "error in stopLoading");
e.printStackTrace();
}
this.cancel();
}
}
}
mProgress = progress;
}
}
/*
* (non-Javadoc)
*
* @see android.webkit.WebView#clearView()
*/
@Override
public void clearView() {
reset();
super.clearView();
}
/**
* Reset the view.
*/
private void reset() {
if (mViewState == ViewState.EXPANDED) {
closeExpanded();
} else if (mViewState == ViewState.RESIZED) {
closeResized();
}
invalidate();
mUtilityController.deleteOldAds();
mUtilityController.stopAllListeners();
resetLayout();
}
/**
* Loads the view from an input stream. Does the real loading work
*
* @param is
* the input stream
* @param dataToInject
* the data to inject
*/
private void loadInputStream(InputStream is, String dataToInject) {
String url;
reset();
if (mTimeOut != null) {
mTimeOut.cancel();
}
mTimeOut = new TimeOut();
try {
mLocalFilePath = mUtilityController.writeToDiskWrap(is, CURRENT_FILE, true, mDataToInject,
mBridgeScriptPath, mScriptPath);
url = "file://" + mLocalFilePath + java.io.File.separator + CURRENT_FILE;
Timer timer = new Timer();
timer.schedule(mTimeOut, 2000, 2000);
if (mDataToInject != null) {
injectJavaScript(mDataToInject);
}
super.loadUrl(url);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Load url.
*
* @param url
* the url
* @param dontLoad
* the dont load
* @param dataToInject
* any additional javascript to inject
*/
public void loadUrl(String url, boolean dontLoad, String dataToInject) {
mDataToInject = dataToInject;
if (!dontLoad) {
InputStream is = null;
bPageFinished = false;
try {
URL u = new URL(url);
String name = u.getFile();
//if it is in the asset directory use the assetmanager
if (url.startsWith("file:///android_asset")) {
int lastSep = url.lastIndexOf(java.io.File.separatorChar);
if (lastSep >= 0) {
name = url.substring(url.lastIndexOf(java.io.File.separatorChar) + 1);
}
AssetManager am = getContext().getAssets();
is = am.open(name);
} else {
is = u.openStream();
}
loadInputStream(is, dataToInject);
return;
} catch (MalformedURLException e) {
} catch (IOException e) {
e.printStackTrace();
return;
}
}
super.loadUrl(url);
}
/**
* Instantiates a new ormma view.
*
* @param context
* the context
* @param set
* the set
*/
public OrmmaView(Context context, AttributeSet set) {
super(context, set);
setVerticalScrollBarEnabled(false);
setHorizontalScrollBarEnabled(false);
setScrollContainer(false);
mGestureDetector = new GestureDetector(new ScrollEater());
initialize();
TypedArray a = getContext().obtainStyledAttributes(set, attrs);
int w = a.getDimensionPixelSize(0, -1);
int h = a.getDimensionPixelSize(1, -1);
if (w > 0 && h > 0)
mUtilityController.setMaxSize(w, h);
a.recycle();
}
/*
* (non-Javadoc)
*
* @see android.webkit.WebView#onTouchEvent(android.view.MotionEvent)
*
* used for trapping scroll events
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean ret = mGestureDetector.onTouchEvent(ev);
if (ret)
ev.setAction(MotionEvent.ACTION_CANCEL);
return super.onTouchEvent(ev);
}
/**
* The message handler. To keep things in the ui thread.
*/
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle data = msg.getData();
switch (msg.what) {
case MESSAGE_SEND_EXPAND_CLOSE:
if (mListener != null) {
mListener.onExpandClose();
}
break;
case MESSAGE_RESIZE: {
mViewState = ViewState.RESIZED;
ViewGroup.LayoutParams lp = getLayoutParams();
lp.height = data.getInt(RESIZE_HEIGHT, lp.height);
lp.width = data.getInt(RESIZE_WIDTH, lp.width);
String injection = "window.ormmaview.fireChangeEvent({ state: \'resized\'," + " size: { width: "
+ lp.width + ", " + "height: " + lp.height + "}});";
injectJavaScript(injection);
requestLayout();
if (mListener != null)
mListener.onResize();
break;
}
case MESSAGE_CLOSE: {
switch (mViewState) {
case RESIZED:
closeResized();
break;
case EXPANDED:
closeExpanded();
break;
}
break;
}
case MESSAGE_HIDE: {
setVisibility(View.INVISIBLE);
String injection = "window.ormmaview.fireChangeEvent({ state: \'hidden\' });";
injectJavaScript(injection);
break;
}
case MESSAGE_SHOW: {
String injection = "window.ormmaview.fireChangeEvent({ state: \'default\' });";
injectJavaScript(injection);
setVisibility(View.VISIBLE);
break;
}
case MESSAGE_EXPAND: {
doExpand(data);
break;
}
case MESSAGE_OPEN: {
mViewState = ViewState.LEFT_BEHIND;
break;
}
}
super.handleMessage(msg);
}
};
/**
* Do the real work of an expand
*/
private void doExpand(Bundle data){
mViewState = ViewState.EXPANDED;
Dimensions d = (Dimensions) data.getParcelable(EXPAND_DIMENSIONS);
String url = data.getString(EXPAND_URL);
Properties p = data.getParcelable(EXPAND_PROPERTIES);
if (url != null && !url.equals("undefined"))
loadUrl(url);
FrameLayout contentView = (FrameLayout) getRootView().findViewById(R.id.content);
ViewGroup parent = (ViewGroup) getParent();
FrameLayout.LayoutParams fl = new FrameLayout.LayoutParams((int) (d.width), (int) (d.height));
fl.topMargin = (int) (d.x);
fl.leftMargin = (int) (d.y);
int index = 0;
int count = parent.getChildCount();
for (index = 0; index < count; index++) {
if (parent.getChildAt(index) == OrmmaView.this)
break;
}
mIndex = index;
FrameLayout placeHolder = new FrameLayout(getContext());
placeHolder.setId(PLACEHOLDER_ID);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(getWidth(), getHeight());
parent.addView(placeHolder, index, lp);
parent.removeView(OrmmaView.this);
FrameLayout backGround = new FrameLayout(getContext());
if (p.useBackground) {
int color = p.backgroundColor | ((int) (p.backgroundOpacity * 0xFF) * 0x10000000);
backGround.setBackgroundColor(color);
}
backGround.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
return true;
}
});
FrameLayout.LayoutParams bgfl = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
FrameLayout.LayoutParams.FILL_PARENT);
backGround.setId(BACKGROUND_ID);
backGround.setPadding((int) (d.x), (int) (d.y), 0, 0);
backGround.addView(OrmmaView.this, fl);
contentView.addView(backGround, bgfl);
String injection = "window.ormmaview.fireChangeEvent({ state: \'expanded\'," + " size: " + "{ width: "
+ (int) (d.width / mDensity) + ", " + "height: " + (int) (d.height / mDensity) + "}" + " });";
injectJavaScript(injection);
if (mListener != null)
mListener.onExpand();
}
/**
* Close resized.
*/
private void closeResized() {
if (mListener != null)
mListener.onResizeClose();
String injection = "window.ormmaview.fireChangeEvent({ state: \'default\'," + " size: " + "{ width: "
+ mDefaultWidth + ", " + "height: " + mDefaultHeight + "}" + "});";
injectJavaScript(injection);
resetLayout();
}
/**
* The webview client used for trapping certain events
*/
WebViewClient mWebViewClient = new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d("OrmmaView", "error:" + description);
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void onPageFinished(WebView view, String url) {
mDefaultHeight = (int) (getHeight() / mDensity);
mDefaultWidth = (int) (getWidth() / mDensity);
mUtilityController.init(mDensity);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
String type = null;
try {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
return true;
}
if (url.startsWith("mailto:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
return true;
}
//TODO check registered protocols
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
return true;
} catch (Exception e) {
try {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
return true;
} catch (Exception e2) {
return false;
}
}
}
public void onLoadResource(WebView view, String url) {
// Log.d(TAG,"lr:"+url);
};
};
/**
* The m web chrome client.
*/
WebChromeClient mWebChromeClient = new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d("OrmmaView", message);
return false;
}
};
/**
* The b got layout params.
*/
private boolean bGotLayoutParams;
/**
* Initialize the view
*/
private void initialize() {
setBackgroundColor(0);
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
mDensity = metrics.density;
bPageFinished = false;
getSettings().setJavaScriptEnabled(true);
mUtilityController = new OrmmaUtilityController(this, this.getContext());
addJavascriptInterface(mUtilityController, "ORMMAUtilityControllerBridge");
setWebViewClient(mWebViewClient);
setWebChromeClient(mWebChromeClient);
setScriptPath();
mContentViewHeight = getContentViewHeight();
getViewTreeObserver().addOnGlobalLayoutListener(this);
}
/**
* Gets the content view height.
*
* @return the content view height
*/
private int getContentViewHeight() {
View contentView = getRootView().findViewById(R.id.content);
if (contentView != null) {
return contentView.getHeight();
} else
return -1;
}
/**
* Sets the script path.
*/
private synchronized void setScriptPath() {
if (mScriptPath == null) {
mScriptPath = mUtilityController.copyTextFromJarIntoAssetDir("/js/ormma.js", "js/ormma.js");
}
if (mBridgeScriptPath == null) {
mBridgeScriptPath = mUtilityController.copyTextFromJarIntoAssetDir("/js/ormma_bridge.js",
"js/ormma_bridge.js");
}
}
/**
* Close an expanded view.
*/
protected synchronized void closeExpanded() {
FrameLayout contentView = (FrameLayout) getRootView().findViewById(R.id.content);
FrameLayout placeHolder = (FrameLayout) getRootView().findViewById(PLACEHOLDER_ID);
FrameLayout background = (FrameLayout) getRootView().findViewById(BACKGROUND_ID);
ViewGroup parent = (ViewGroup) placeHolder.getParent();
background.removeView(this);
contentView.removeView(background);
resetLayout();
parent.addView(this, mIndex);
parent.removeView(placeHolder);
parent.invalidate();
String injection = "window.ormmaview.fireChangeEvent({ state: \'default\'," + " size: " + "{ width: "
+ mDefaultWidth + ", " + "height: " + mDefaultHeight + "}" + "});";
injectJavaScript(injection);
mViewState = ViewState.DEFAULT;
mHandler.sendEmptyMessage(MESSAGE_SEND_EXPAND_CLOSE);
setVisibility(VISIBLE);
}
/**
* Close an opened view.
*
* @param openedFrame
* the opened frame
*/
protected void closeOpened(View openedFrame) {
((ViewGroup) ((Activity) getContext()).getWindow().getDecorView()).removeView(openedFrame);
requestLayout();
}
/**
* Gets the state.
*
* @return the state
*/
public String getState() {
return mViewState.toString().toLowerCase();
}
/**
* Resize the view
*
* @param width
* the width
* @param height
* the height
*/
public void resize(int width, int height) {
Message msg = mHandler.obtainMessage(MESSAGE_RESIZE);
Bundle data = new Bundle();
data.putInt(RESIZE_WIDTH, width);
data.putInt(RESIZE_HEIGHT, height);
msg.setData(data);
mHandler.sendMessage(msg);
}
/**
* Close the view
*/
public void close() {
mHandler.sendEmptyMessage(MESSAGE_CLOSE);
}
/**
* Hide the view
*/
public void hide() {
mHandler.sendEmptyMessage(MESSAGE_HIDE);
}
/**
* Show the view
*/
public void show() {
mHandler.sendEmptyMessage(MESSAGE_SHOW);
}
/**
* Gets the connectivity manager.
*
* @return the connectivity manager
*/
public ConnectivityManager getConnectivityManager() {
return (ConnectivityManager) this.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
}
/**
* Dump.
*/
public void dump() {
// TODO Auto-generated method stub
}
/**
* creates an expand message and throws it to the handler for the real work
*
* @param dimensions
* the dimensions
* @param URL
* the uRL
* @param properties
* the properties
*/
public void expand(Dimensions dimensions, String URL, Properties properties) {
Message msg = mHandler.obtainMessage(MESSAGE_EXPAND);
Bundle data = new Bundle();
data.putParcelable(EXPAND_DIMENSIONS, dimensions);
data.putString(EXPAND_URL, URL);
data.putParcelable(EXPAND_PROPERTIES, properties);
msg.setData(data);
mHandler.sendMessage(msg);
}
/**
* Open.
*
* @param url
* the url
* @param back
* show the back button
* @param forward
* show the forward button
* @param refresh
* show the refresh button
*/
public void open(String url, boolean back, boolean forward, boolean refresh) {
Intent i = new Intent(getContext(), Browser.class);
Log.d(TAG, "open:" + url);
i.putExtra(Browser.URL_EXTRA, url);
i.putExtra(Browser.SHOW_BACK_EXTRA, back);
i.putExtra(Browser.SHOW_FORWARD_EXTRA, forward);
i.putExtra(Browser.SHOW_REFRESH_EXTRA, refresh);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(i);
}
public void openMap(String url, boolean fullscreen) {
//TODO
}
public void playAudio(String url, boolean autoPlay, boolean controls, boolean loop, boolean inline, String startStyle, String stopStyle) {
//TODO...needs to be sent into the handler?
}
public void playVideo(String url, boolean audioMuted, boolean autoPlay, boolean controls, boolean loop, int[] inline, String startStyle, String stopStyle) {
//TODO...is the int[] param valid?
//TODO needs to be sent into the handler?
}
/**
* The Class NewLocationReciever.
*/
public static abstract class NewLocationReciever {
/**
* On new location.
*
* @param v
* the v
*/
public abstract void OnNewLocation(ViewState v);
}
/**
* Reset layout.
*/
private void resetLayout() {
ViewGroup.LayoutParams lp = getLayoutParams();
lp.height = mInitLayoutHeight;
lp.width = mInitLayoutWidth;
setVisibility(VISIBLE);
requestLayout();
}
/**
* Checks if is page finished.
*
* @return true, if is page finished
*/
public boolean isPageFinished() {
return bPageFinished;
}
//trap keyboard state and view height/width
@Override
public void onGlobalLayout() {
boolean state = bKeyboardOut;
if (!bKeyboardOut && mContentViewHeight >= 0 && getContentViewHeight() >= 0
&& (mContentViewHeight != getContentViewHeight())) {
state = true;
String injection = "window.ormmaview.fireChangeEvent({ keyboardState: true});";
injectJavaScript(injection);
}
if (bKeyboardOut && mContentViewHeight >= 0 && getContentViewHeight() >= 0
&& (mContentViewHeight == getContentViewHeight())) {
state = false;
String injection = "window.ormmaview.fireChangeEvent({ keyboardState: false});";
injectJavaScript(injection);
}
if (mContentViewHeight < 0) {
mContentViewHeight = getContentViewHeight();
}
bKeyboardOut = state;
}
/**
* Gets the size.
*
* @return the size
*/
public String getSize() {
return "{ width: " + (int) (getWidth() / mDensity) + ", " + "height: " + (int) (getHeight() / mDensity) + "}";
}
/*
* (non-Javadoc)
*
* @see android.webkit.WebView#onAttachedToWindow()
*
* Gather some initial information about the view.
*/
@Override
protected void onAttachedToWindow() {
if (!bGotLayoutParams) {
ViewGroup.LayoutParams lp = getLayoutParams();
mInitLayoutHeight = lp.height;
mInitLayoutWidth = lp.width;
bGotLayoutParams = true;
}
super.onAttachedToWindow();
}
/*
* (non-Javadoc)
*
* @see android.webkit.WebView#saveState(android.os.Bundle)
*/
@Override
public WebBackForwardList saveState(Bundle outState) {
outState.putString(AD_PATH, mLocalFilePath);
return null;
}
/*
* (non-Javadoc)
*
* @see android.webkit.WebView#restoreState(android.os.Bundle)
*/
@Override
public WebBackForwardList restoreState(Bundle savedInstanceState) {
mLocalFilePath = savedInstanceState.getString(AD_PATH);
String url = "file://" + mLocalFilePath + java.io.File.separator + CURRENT_FILE;
super.loadUrl(url);
return null;
}
/**
* The Class ScrollEater.
*/
class ScrollEater extends SimpleOnGestureListener {
/*
* (non-Javadoc)
*
* @see
* android.view.GestureDetector.SimpleOnGestureListener#onScroll(android
* .view.MotionEvent, android.view.MotionEvent, float, float)
*
* Gesture detector for eating scroll events
*/
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return true;
}
}
/**
* Checks if is expanded.
*
* @return true, if is expanded
*/
public boolean isExpanded() {
return mViewState == ViewState.EXPANDED;
}
}
|
package org.batfish.main;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.collections4.map.LRUMap;
import org.batfish.common.BatfishLogger;
import org.batfish.common.BfConsts;
import org.batfish.common.Snapshot;
import org.batfish.common.util.CommonUtil;
import org.batfish.config.Settings;
import org.batfish.config.Settings.EnvironmentSettings;
import org.batfish.config.Settings.TestrigSettings;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.ConfigurationFormat;
import org.batfish.datamodel.DataPlane;
import org.batfish.datamodel.ForwardingAnalysis;
import org.batfish.datamodel.Interface;
import org.batfish.datamodel.collections.BgpAdvertisementsByVrf;
import org.batfish.datamodel.collections.RoutesByVrf;
import org.batfish.dataplane.bdp.BdpDataPlanePlugin;
import org.batfish.dataplane.ibdp.IncrementalDataPlanePlugin;
import org.junit.rules.TemporaryFolder;
public class BatfishTestUtils {
private static Cache<Snapshot, SortedMap<String, Configuration>> makeTestrigCache() {
return CacheBuilder.newBuilder().maximumSize(5).build();
}
private static Map<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>>
makeEnvBgpCache() {
return Collections.synchronizedMap(new LRUMap<>(4));
}
private static Map<EnvironmentSettings, SortedMap<String, RoutesByVrf>> makeEnvRouteCache() {
return Collections.synchronizedMap(new LRUMap<>(4));
}
private static Cache<TestrigSettings, DataPlane> makeDataPlaneCache() {
return CacheBuilder.newBuilder().maximumSize(2).build();
}
private static Cache<TestrigSettings, ForwardingAnalysis> makeForwardingAnalysisCache() {
return CacheBuilder.newBuilder().maximumSize(2).build();
}
private static Batfish initBatfish(
SortedMap<String, Configuration> configurations, @Nonnull TemporaryFolder tempFolder)
throws IOException {
Settings settings = new Settings(new String[] {});
settings.setLogger(new BatfishLogger("debug", false));
final Cache<Snapshot, SortedMap<String, Configuration>> testrigs = makeTestrigCache();
final Cache<Snapshot, SortedMap<String, Configuration>> compressedTestrigs = makeTestrigCache();
Path containerDir = tempFolder.newFolder().toPath();
settings.setContainerDir(containerDir);
if (!configurations.isEmpty()) {
settings.setTestrig("tempTestrig");
settings.setEnvironmentName("tempEnvironment");
Batfish.initTestrigSettings(settings);
settings.getBaseTestrigSettings().getEnvironmentSettings().getEnvPath().toFile().mkdirs();
testrigs.put(new Snapshot("tempTestrig", "tempEnvironment"), configurations);
settings.setActiveTestrigSettings(settings.getBaseTestrigSettings());
}
Batfish batfish =
new Batfish(
settings,
compressedTestrigs,
testrigs,
makeDataPlaneCache(),
makeDataPlaneCache(),
makeEnvBgpCache(),
makeEnvRouteCache(),
makeForwardingAnalysisCache());
if (!configurations.isEmpty()) {
Batfish.serializeAsJson(
settings.getBaseTestrigSettings().getEnvironmentSettings().getSerializedTopologyPath(),
batfish.computeEnvironmentTopology(configurations),
"environment topology");
}
registerDataPlanePlugins(batfish);
return batfish;
}
private static void registerDataPlanePlugins(Batfish batfish) {
BdpDataPlanePlugin bdpPlugin = new BdpDataPlanePlugin();
bdpPlugin.initialize(batfish);
IncrementalDataPlanePlugin ibdpPlugin = new IncrementalDataPlanePlugin();
ibdpPlugin.initialize(batfish);
}
/**
* Get a new Batfish instance with given configurations, tempFolder should be present for
* non-empty configurations
*
* @param testrigText Structure containing names and content of testrig input files
* @param tempFolder Temporary folder to be used to files required for Batfish
* @return Batfish instance pointing at new testrig comprising testrigText
*/
public static Batfish getBatfishFromTestrigText(
TestrigText testrigText, TemporaryFolder tempFolder) throws IOException {
Map<String, String> awsText = testrigText.getAwsText();
Map<String, String> bgpTablesText = testrigText.getBgpTablesText();
Map<String, String> configurationText = testrigText.getConfigurationText();
Map<String, String> hostsText = testrigText.getHostsText();
Map<String, String> iptablesFilesText = testrigText.getIptablesFilesText();
Map<String, String> routingTablesText = testrigText.getRoutingTablesText();
Settings settings = new Settings(new String[] {});
settings.setLogger(new BatfishLogger("debug", false));
settings.setDisableUnrecognized(true);
settings.setHaltOnConvertError(true);
settings.setHaltOnParseError(true);
settings.setThrowOnLexerError(true);
settings.setThrowOnParserError(true);
settings.setVerboseParse(true);
Path containerDir = tempFolder.newFolder().toPath();
settings.setContainerDir(containerDir);
settings.setTestrig("tempTestrig");
settings.setEnvironmentName("tempEnvironment");
Batfish.initTestrigSettings(settings);
Path testrigPath = settings.getBaseTestrigSettings().getTestRigPath();
settings.setActiveTestrigSettings(settings.getBaseTestrigSettings());
EnvironmentSettings envSettings = settings.getBaseTestrigSettings().getEnvironmentSettings();
envSettings.getEnvPath().toFile().mkdirs();
writeTemporaryTestrigFiles(
configurationText, testrigPath.resolve(BfConsts.RELPATH_CONFIGURATIONS_DIR));
writeTemporaryTestrigFiles(awsText, testrigPath.resolve(BfConsts.RELPATH_AWS_CONFIGS_DIR));
writeTemporaryTestrigFiles(bgpTablesText, envSettings.getEnvironmentBgpTablesPath());
writeTemporaryTestrigFiles(hostsText, testrigPath.resolve(BfConsts.RELPATH_HOST_CONFIGS_DIR));
writeTemporaryTestrigFiles(iptablesFilesText, testrigPath.resolve("iptables"));
writeTemporaryTestrigFiles(routingTablesText, envSettings.getEnvironmentRoutingTablesPath());
Batfish batfish =
new Batfish(
settings,
makeTestrigCache(),
makeTestrigCache(),
makeDataPlaneCache(),
makeDataPlaneCache(),
makeEnvBgpCache(),
makeEnvRouteCache(),
makeForwardingAnalysisCache());
registerDataPlanePlugins(batfish);
return batfish;
}
/**
* Get a configuration object with the given interfaces
*
* @param nodeName Host name for the configuration
* @param configFormat Configuration format
* @param interfaceNames All interface names to be included
* @return A new configuration
*/
public static Configuration createTestConfiguration(
String nodeName, ConfigurationFormat configFormat, String... interfaceNames) {
Configuration config = new Configuration(nodeName, configFormat);
for (String interfaceName : interfaceNames) {
config.getInterfaces().put(interfaceName, new Interface(interfaceName, config));
}
return config;
}
/**
* Get a new Batfish instance with given configurations, tempFolder should be present for
* non-empty configurations
*
* @param configurations Map of all Configuration Name -> Configuration Object
* @param tempFolder Temporary folder to be used to files required for Batfish
* @return New Batfish instance
*/
public static Batfish getBatfish(
SortedMap<String, Configuration> configurations, @Nonnull TemporaryFolder tempFolder)
throws IOException {
return initBatfish(configurations, tempFolder);
}
public static Batfish getBatfishForTextConfigs(
TemporaryFolder folder, String... configurationNames) throws IOException {
SortedMap<String, String> configurationTextMap = new TreeMap<>();
for (String configName : configurationNames) {
String configurationText = CommonUtil.readResource(configName);
configurationTextMap.put(new File(configName).getName(), configurationText);
}
return BatfishTestUtils.getBatfishFromTestrigText(
TestrigText.builder().setConfigurationText(configurationTextMap).build(), folder);
}
public static Map<String, Configuration> parseTextConfigs(
TemporaryFolder folder, String... configurationNames) throws IOException {
return getBatfishForTextConfigs(folder, configurationNames).loadConfigurations();
}
private static void writeTemporaryTestrigFiles(
@Nullable Map<String, String> filesText, Path outputDirectory) {
if (filesText != null) {
filesText.forEach(
(filename, text) -> {
outputDirectory.toFile().mkdirs();
CommonUtil.writeFile(outputDirectory.resolve(filename), text);
});
}
}
}
|
// $Id: IntervalManager.java,v 1.7 2002/05/24 21:32:29 mdb Exp $
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
import java.util.Timer;
import java.util.TimerTask;
import com.samskivert.Log;
/**
* Can be used to register an object that is to be called once or
* repeatedly after an interval has expired. This now uses {@link Timer}
* to do all the actual scheduling, but we keep this front end because it
* is static (accessible anywhere), provides a single thread where
* disparate simple intervals can all run happily, and because {@link
* Interval} is an interface, unlike {@link TimerTask}, which is an
* abstract class.
*/
public class IntervalManager
{
/**
* Schedule the intervaled object to get called after an interval.
*
* @param i the intervaled object
* @param timout # of ms until interval is up.
* @param arg object to be passed when interval expires
* @param recur if true, interval gets called every timeout until
* removed.
*
* @return an ID number that will passed to the {@link
* Interval#intervalExpired} method of i along with arg
*/
public static int register (Interval i, long delay, Object arg,
boolean recur)
{
IntervalTask task = new IntervalTask(i, arg, recur);
_hash.put(task.id, task);
if (recur) {
_timer.scheduleAtFixedRate(task, delay, delay);
} else {
_timer.schedule(task, delay);
}
return task.id;
}
/**
* Schedule the interval to be called repeatedly, but at a fixed delay
* instead of fixed rate. This means that the delay between executions
* will be the delay specified below plus the actual execution time it
* takes to run the interval's expire method.
*/
public static int registerAtFixedDelay (Interval i, long delay, Object arg)
{
IntervalTask task = new IntervalTask(i, arg, true);
_hash.put(task.id, task);
_timer.schedule(task, delay, delay);
return task.id;
}
/**
* Non-recurring intervals are removed automatically after they are
* run! This method is only useful if you want to remove a recurring
* {@link Interval} or if you want to remove a non-recurring {@link
* Interval} before it gets run.
*/
public static void remove (int id)
{
IntervalTask task = (IntervalTask) _hash.remove(id);
if (task != null) {
task.cancel();
} else {
Log.warning("remove() called on non-registered " +
"interval [id=" + id + "].");
}
}
/** The timer we use to schedule everything. */
protected static Timer _timer = new Timer(true);
/** Our registered intervals, indexed by id. */
protected static IntMap _hash =
Collections.synchronizedIntMap(new HashIntMap());
/**
* A class to adapt {@link TimerTask} to the smooth action of {@link
* Interval}.
*/
static class IntervalTask extends TimerTask
{
public int id;
protected Interval _i;
protected Object _arg;
protected boolean _onetime;
public IntervalTask (Interval i, Object arg, boolean recur)
{
_i = i;
_arg = arg;
_onetime = !recur;
id = nextID();
}
/**
* Run the interval. It's synchronized so that if we someday have
* multiple threads, the same interval won't be called multiple
* times.
*/
public void run ()
{
// protect our ass.
try {
_i.intervalExpired(id, _arg);
} catch (Exception e) {
Log.warning("Exception while expiring interval: " + e);
Log.logStackTrace(e);
}
// if we're not recurring, be sure to remove from the mgr's hash
if (_onetime) {
_hash.remove(id);
}
}
/**
* Unique ids for each interval item.
*/
private static synchronized int nextID ()
{
return _idseq++;
}
private static int _idseq = 0;
}
}
|
package gov.nih.nci.cabig.caaers.web.ae;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportTree;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.TreeNode;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.UnsatisfiedProperty;
import gov.nih.nci.cabig.caaers.service.ReportService;
import gov.nih.nci.cabig.caaers.web.fields.CompositeField;
import gov.nih.nci.cabig.caaers.web.fields.InputField;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup;
import gov.nih.nci.cabig.caaers.web.fields.TabWithFields;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroupMap;
import gov.nih.nci.cabig.caaers.web.fields.RepeatingFieldGroupFactory;
import gov.nih.nci.cabig.caaers.web.fields.BasePropertyInputFieldGroup;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Arrays;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeanWrapper;
/**
* @author Rhett Sutphin
* @author <a href="mailto:biju.joseph@semanticbits.com">Biju Joseph</a>
*/
public abstract class AeTab extends TabWithFields<ExpeditedAdverseEventInputCommand> {
protected static final String MANDATORY_FIELD_ATTR = "mandatory";
private ExpeditedReportTree expeditedReportTree;
protected ReportService reportService;
public AeTab(String longTitle, String shortTitle, String viewName) {
super(longTitle, shortTitle, viewName);
}
@Override
public final InputFieldGroupMap createFieldGroups(ExpeditedAdverseEventInputCommand command) {
AeInputFieldCreator creator = new AeInputFieldCreator(command);
createFieldGroups(creator, command);
return creator.getMap();
}
/**
* Template method for subclasses to instantiate their fields via the {@link AeInputFieldCreator}.
*/
protected abstract void createFieldGroups(AeInputFieldCreator creator, ExpeditedAdverseEventInputCommand command);
/**
* Will also update the InputField mandatory flag.
*/
@Override
public Map<String, Object> referenceData(ExpeditedAdverseEventInputCommand command) {
Map<String, Object> refData = super.referenceData(command);
Object fieldGroups = refData.get("fieldGroups");
populateMandatoryFlag(fieldGroups, command, refData);
return refData;
}
/**
* Will populate the mandatory flag.
*/
@SuppressWarnings("unchecked")
private void populateMandatoryFlag(Object fieldGroups, ExpeditedAdverseEventInputCommand command, Map<String, Object> refData) {
//TODO: need to see how to manage (this or that) kind mandatory fields
//TODO: Why not this we handle in createFields() of every tab, so that the looping through the fields
// here can be avoided.
Map<String, InputFieldGroup> groupMap = (Map<String, InputFieldGroup>) fieldGroups;
if (groupMap == null) return;
for (InputFieldGroup group : groupMap.values()) {
for (InputField field : group.getFields()) {
if (isMandatory(command.getMandatoryProperties(), field)) {
field.getAttributes().put(MANDATORY_FIELD_ATTR, true);
}
}
}
}
/**
* Tells whether the given field is mandatory.
* In case of Composite fields, the given field (parent) will be marked mandatory if any of its subfields
* are mandatory.
*
* @param field
* @return
*/
private boolean isMandatory(MandatoryProperties mandatoryProps, InputField field) {
boolean mandatory = mandatoryProps.isMandatory(field.getPropertyName().replace("aeReport.", ""));
if (field.getCategory() == InputField.Category.COMPOSITE) {
for (InputField subfield : CompositeField.getSubfields(field))
mandatory |= isMandatory(mandatoryProps, subfield);
}
return mandatory;
}
/**
* Check's whether this tab is mandatory
*/
public boolean isMandatory(ExpeditedAdverseEventInputCommand command) {
Collection<ExpeditedReportSection> sections = command.getMandatorySections();
if (sections == null || sections.isEmpty()) return false;
return sections.contains(section());
}
public boolean hasEmptyMandatoryFields(ExpeditedAdverseEventInputCommand command) {
MandatoryProperties props = command.getMandatoryProperties();
if (props == null) return false;
TreeNode node = expeditedReportTree.getNodeForSection(section());
if (node == null) return false;
List<UnsatisfiedProperty> unsatisfied = props.getUnsatisfied(node, command.getAeReport());
return !unsatisfied.isEmpty();
}
public abstract ExpeditedReportSection section();
public ExpeditedReportTree getExpeditedReportTree() {
return expeditedReportTree;
}
////// CONFIGURATION
public void setExpeditedReportTree(ExpeditedReportTree expeditedReportTree) {
this.expeditedReportTree = expeditedReportTree;
}
public void setReportService(ReportService reportService) {
this.reportService = reportService;
}
protected class AeInputFieldCreator {
protected final ExpeditedAdverseEventInputCommand command;
private BeanWrapper wrappedReport;
private InputFieldGroupMap map;
protected AeInputFieldCreator(ExpeditedAdverseEventInputCommand command) {
this.command = command;
this.wrappedReport = new BeanWrapperImpl(command.getAeReport());
this.map = new InputFieldGroupMap();
}
/**
* Add a RepeatingFieldGroup to the groups for this tab. Note that the
* listProperty should be relative to {@link gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport}
* <em>not</em> the command. That is, it should not begin with <code>aeReport.</code>.
*/
public final AeInputFieldCreator createRepeatingFieldGroup(String basename, String listProperty, InputField... fields) {
return createRepeatingFieldGroup(basename, listProperty, null, fields);
}
public final AeInputFieldCreator createRepeatingFieldGroup(String basename, String listProperty, RepeatingFieldGroupFactory.DisplayNameCreator nameCreator, InputField... fields) {
RepeatingFieldGroupFactory factory = new RepeatingFieldGroupFactory(basename, "aeReport." + listProperty);
TreeNode listNode = expeditedReportTree.find(listProperty);
if (listNode == null) {
throw new CaaersSystemException(listProperty + " does not appear in the expedited report tree");
}
for (InputField field : fields) {
List<String> props = field.getCategory() == InputField.Category.COMPOSITE
? CompositeField.getEffectivePropertyNames(field)
: Arrays.asList(field.getPropertyName());
for (String prop : props) {
setMandatoryAttribute(listNode.find(prop), field);
}
factory.addField(field);
}
Collection<?> list = (Collection<?>) wrappedReport.getPropertyValue(listProperty);
int initialCount = list == null ? 0 : list.size();
if (nameCreator != null) {
factory.setDisplayNameCreator(nameCreator);
}
map.addRepeatingFieldGroupFactory(factory, initialCount);
return this;
}
/**
* Add a normal, single group of fields to this tab. Note that the fields' propertyNames
* should be relative to {@link gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport}
* <em>not</em> the command. That is, they should not begin with <code>aeReport.</code>.
*/
public final AeInputFieldCreator createFieldGroup(String name, InputField... fields) {
return createFieldGroup(name, null, fields);
}
public final AeInputFieldCreator createFieldGroup(
String name, String displayName, InputField... fields
) {
return createFieldGroup(name, displayName, null, fields);
}
public final AeInputFieldCreator createFieldGroup(
String name, String displayName, String baseProperty, InputField... fields
) {
BasePropertyInputFieldGroup group = new BasePropertyInputFieldGroup(name, displayName, "aeReport" + (baseProperty == null ? "" : '.' + baseProperty));
for (InputField field : fields) {
String treePropName = (baseProperty == null ? "" : baseProperty + '.') + field.getPropertyName();
setMandatoryAttribute(expeditedReportTree.find(treePropName), field);
group.addField(field);
}
map.addInputFieldGroup(group);
return this;
}
public InputFieldGroupMap getMap() {
return map;
}
private void setMandatoryAttribute(TreeNode fieldNode, InputField field) {
if (command.getMandatoryProperties() != null) {
if (command.getMandatoryProperties().isMandatory(fieldNode)) {
field.getAttributes().put(MANDATORY_FIELD_ATTR, true);
}
}
}
/**
* Directly add an input field group. This group should not contain any fields which
* represent properties in the command's aeReport.
*
* @param group
*/
public void addUnprocessedFieldGroup(InputFieldGroup group) {
map.addInputFieldGroup(group);
}
}
protected final class SimpleNumericDisplayNameCreator implements RepeatingFieldGroupFactory.DisplayNameCreator {
private String heading;
public SimpleNumericDisplayNameCreator(String heading) {
this.heading = heading;
}
public String createDisplayName(int index) {
return new StringBuilder(heading).append(' ').append(index + 1).toString();
}
}
}
|
package com.sailthru.client;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Map;
/**
*
* @author ianwhite
*/
public class NullSerializingMapTypeAdapter extends TypeAdapter<Map<String, ?>> {
final Gson gson = new GsonBuilder().serializeNulls().create();
public void write(JsonWriter writer, Map<String, ?> map) throws IOException {
if (map == null) {
writer.nullValue();
} else {
gson.toJson(gson.toJsonTree(map), writer);
}
}
@Override
public Map<String, ?> read(JsonReader reader) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package com.mongodb.rhino;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bson.BSONObject;
import org.bson.types.ObjectId;
import org.bson.types.Symbol;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import com.mongodb.BasicDBObject;
/**
* Direct conversion between native Rhino objects and BSON.
* <p>
* This class can be used directly in Rhino.
*
* @author Tal Liron
*/
public class BSON
{
// Static operations
/**
* Convert from native Rhino to BSON.
*
* @param object
* A Rhino native object
* @return A BSON object
*/
public static BSONObject to( ScriptableObject object )
{
BasicDBObject bson = new BasicDBObject();
Object[] ids = object.getAllIds();
for( Object id : ids )
{
String key = id.toString();
Object value = forBson( ScriptableObject.getProperty( object, key ), key );
bson.put( key, value );
}
return bson;
}
/**
* Convert from BSON to native Rhino.
*
* @param bson
* A BSON object
* @return A Rhino native object
*/
public static NativeObject from( BSONObject bson )
{
if( bson == null )
return null;
NativeObject object = new NativeObject();
for( String key : bson.keySet() )
{
Object value = forRhino( bson.get( key ) );
ScriptableObject.putProperty( object, key, value );
}
return object;
}
// Private
/**
* If necessary, convert from native Rhino to a type supported by BSON.
*
* @param object
* An object
* @param key
* The key used for the object (optional)
* @return An object ready to be put inside a BSON object
*/
private static Object forBson( Object object, String key )
{
if( object instanceof NativeJavaObject )
{
// This happens either because the developer purposely creates a
// Java object, or because it was returned from a Java call and
// wrapped by Rhino.
return ( (NativeJavaObject) object ).unwrap();
}
else if( object instanceof NativeArray )
{
// Convert Rhino array to list
NativeArray array = (NativeArray) object;
int length = (int) array.getLength();
List<Object> list = new ArrayList<Object>( length );
for( int i = 0; i < length; i++ )
list.add( forBson( ScriptableObject.getProperty( array, i ), null ) );
return list;
}
else if( object instanceof ScriptableObject )
{
ScriptableObject scriptable = (ScriptableObject) object;
if( scriptable.getClassName().equals( "Date" ) )
{
// The NativeDate class is private in Rhino, but we can access
// it like a regular object.
Object time = ScriptableObject.callMethod( scriptable, "getTime", null );
if( time instanceof Number )
return new Date( ( (Number) time ).longValue() );
}
// Convert
return to( scriptable );
}
else if( "_id".equals( key ) )
{
return new ObjectId( object.toString() );
}
else
return object;
}
/**
* If necessary, convert from BSON to a type supported by Rhino.
*
* @param object
* An object
* @return An object ready to be put inside a Rhino object
*/
private static Object forRhino( Object object )
{
// System.out.println( object.getClass() );
if( object instanceof BSONObject )
{
// Convert
return from( (BSONObject) object );
}
else if( object instanceof List<?> )
{
// Convert list to NativeArray
List<?> list = (List<?>) object;
NativeArray array = new NativeArray( list.size() );
int index = 0;
for( Object item : list )
ScriptableObject.putProperty( array, index++, forRhino( item ) );
return array;
}
else if( object instanceof Date )
{
// The NativeDate class is private in Rhino, but we can create
// it indirectly like a regular object.
Date date = (Date) object;
Context context = Context.getCurrentContext();
Scriptable scope = ScriptRuntime.getTopCallScope( context );
Scriptable nativeDate = context.newObject( scope, "Date", new Object[]
{
date.getTime()
} );
return nativeDate;
}
else if( object instanceof ObjectId )
{
return ( (ObjectId) object ).toStringMongod();
}
else if( object instanceof Symbol )
{
return ( (Symbol) object ).getSymbol();
}
else
return object;
}
}
|
package com.spiddekauga.android.ui.list;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.annotation.ColorInt;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.spiddekauga.android.AppActivity;
import com.spiddekauga.android.R;
import com.spiddekauga.android.ui.ColorHelper;
import java.util.HashMap;
import java.util.Map;
/**
* Add ability to remove items by swiping
*/
class SwipeRemoveFunctionality<T> implements ViewHolderFunctionality<T> {
private boolean mUndoFunctionality = false;
private String mRemovedMessage = AppActivity.getActivity().getResources().getString(R.string.item_removed);
private RemoveListener<T> mListener;
@ColorInt
private int mColor = ColorHelper.getColor(AppActivity.getActivity().getResources(), R.color.remove, null);
private AdvancedAdapter<T, ?> mAdapter;
private Map<T, Runnable> mPendingRemoves = new HashMap<>();
private Handler mHandler = new Handler();
private boolean mRemoving = false;
public SwipeRemoveFunctionality(AdvancedAdapter<T, ?> adapter, RemoveListener<T> listener) {
mAdapter = adapter;
mListener = listener;
}
public SwipeRemoveFunctionality(AdvancedAdapter<T, ?> adapter, RemoveListener<T> listener, boolean undoFunctionality) {
mAdapter = adapter;
mListener = listener;
mUndoFunctionality = undoFunctionality;
}
public SwipeRemoveFunctionality(AdvancedAdapter<T, ?> adapter, RemoveListener<T> listener, boolean undoFunctionality, String removedMessage) {
mAdapter = adapter;
mListener = listener;
mUndoFunctionality = undoFunctionality;
mRemovedMessage = removedMessage;
}
public UndoViewHolder onCreateViewHolder(ViewGroup parent) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.undo_list_item, parent, false);
return new UndoViewHolder(itemView);
}
@Override
public int getViewType() {
return AdvancedAdapter.ViewTypes.UNDO.ordinal();
}
@Override
public Class<UndoViewHolder> getViewHolderClass() {
return UndoViewHolder.class;
}
@Override
public void onBindViewHolder(AdvancedAdapter<T, ?> adapter, RecyclerView.ViewHolder view, int position) {
UndoViewHolder undoView = (UndoViewHolder) view;
// undoView.itemView.setBackgroundColor(mColor);
undoView.mRemovedTextView.setText(mRemovedMessage);
if (mUndoFunctionality) {
final T item = mAdapter.getItem(position);
undoView.mUndoButton.setVisibility(View.VISIBLE);
undoView.mUndoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Runnable pendingRemovalRunnable = mPendingRemoves.get(item);
if (pendingRemovalRunnable != null) {
mPendingRemoves.remove(item);
mHandler.removeCallbacks(pendingRemovalRunnable);
mAdapter.removeItemViewHolder(item, SwipeRemoveFunctionality.this);
int currentPos = mAdapter.getItemPosition(item);
if (currentPos != -1) {
mAdapter.notifyItemChanged(currentPos);
}
}
}
});
} else {
undoView.mUndoButton.setVisibility(View.GONE);
}
}
@Override
public void applyFunctionality(AdvancedAdapter<T, ?> adapter, RecyclerView recyclerView) {
// Item touch helper
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new TransactionRemoveCallback());
itemTouchHelper.attachToRecyclerView(recyclerView);
// Red background when erasing
BackgroundDecoration backgroundDecoration = new BackgroundDecoration();
recyclerView.addItemDecoration(backgroundDecoration);
}
/**
* Undo ViewHolder that views the undo functionality
*/
static class UndoViewHolder extends RecyclerView.ViewHolder {
private TextView mRemovedTextView;
private Button mUndoButton;
public UndoViewHolder(View itemView) {
super(itemView);
mRemovedTextView = (TextView) itemView.findViewById(R.id.remove_message);
mUndoButton = (Button) itemView.findViewById(R.id.undo_button);
}
}
/**
* Callback when a transaction has been swiped (and should be removed)
* Draws the red background together with the trash can while the list item is being swiped
*/
class TransactionRemoveCallback extends ItemTouchHelper.Callback {
private static final int UNDO_DURATION = 3000; // 3sec
private final int mTrashMargin = (int) AppActivity.getActivity().getResources().getDimension(R.dimen.margin);
private Drawable mBackground = new ColorDrawable(mColor);
private Drawable mTrash = ContextCompat.getDrawable(AppActivity.getActivity(), R.drawable.delete_24dp);
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
// Don't allow undo view holders to be swiped
if (viewHolder instanceof UndoViewHolder) {
return 0;
} else {
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(0, swipeFlags);
}
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public boolean isItemViewSwipeEnabled() {
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int swipedPosition = viewHolder.getAdapterPosition();
final T item = mAdapter.getItem(swipedPosition);
// Ability to undo
if (mUndoFunctionality) {
mAdapter.setItemViewHolder(item, SwipeRemoveFunctionality.this);
Runnable pendingRemovalRunnable = new Runnable() {
@Override
public void run() {
onRemove(item);
}
};
mPendingRemoves.put(item, pendingRemovalRunnable);
mAdapter.notifyItemChanged(swipedPosition);
mHandler.postDelayed(pendingRemovalRunnable, UNDO_DURATION);
}
// No undo
else {
onRemove(item);
}
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
View itemView = viewHolder.itemView;
// not sure why, but this method get's called for viewholder that are already swiped away
if (viewHolder.getAdapterPosition() == -1) {
// not interested in those
return;
}
// draw red background
// To the right
if (dX < 0) {
mBackground.setBounds(itemView.getRight() + (int) dX, itemView.getTop(), itemView.getRight(), itemView.getBottom());
}
// To the left
else {
mBackground.setBounds(itemView.getLeft(), itemView.getTop(), itemView.getLeft() + (int) dX, itemView.getBottom());
}
mBackground.draw(c);
// draw trash mark
int itemHeight = itemView.getBottom() - itemView.getTop();
int intrinsicWidth = mTrash.getIntrinsicWidth();
int intrinsicHeight = mTrash.getIntrinsicWidth();
int trashTop = itemView.getTop() + (itemHeight - intrinsicHeight) / 2;
int trashBottom = trashTop + intrinsicHeight;
int trashLeft = Integer.MIN_VALUE;
int trashRight = Integer.MIN_VALUE;
// Right
if (dX < 0) {
trashLeft = itemView.getRight() - mTrashMargin - intrinsicWidth;
trashRight = itemView.getRight() - mTrashMargin;
}
// Left
else if (dX > 0) {
trashLeft = itemView.getLeft() + mTrashMargin;
trashRight = itemView.getLeft() + mTrashMargin + intrinsicWidth;
}
mTrash.setBounds(trashLeft, trashTop, trashRight, trashBottom);
mTrash.draw(c);
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
private void onRemove(T item) {
mRemoving = true;
mAdapter.remove(item);
mPendingRemoves.remove(item);
if (mListener != null) {
mListener.onRemoved(item);
}
}
}
/**
* Draws the red background during the remove animation. I.e. after the list item has been removed
*/
class BackgroundDecoration extends RecyclerView.ItemDecoration {
private Drawable mBackground = new ColorDrawable(mColor);
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
// only if animation is in progress
if (mRemoving && parent.getItemAnimator().isRunning()) {
// some items might be animating down and some items might be animating up to close the gap left by the removed item
// this is not exclusive, both movement can be happening at the same time
// to reproduce this leave just enough items so the first one and the last one would be just a little off screen
// then remove one from the middle
// find first child with translationY > 0
// and last one with translationY < 0
// we're after a rect that is not covered in recycler-view views at this point in time
View lastViewComingDown = null;
View firstViewComingUp = null;
// this is fixed
int left = 0;
int right = parent.getWidth();
// this we need to find out
int top = 0;
int bottom = 0;
// find relevant translating views
int childCount = parent.getLayoutManager().getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getLayoutManager().getChildAt(i);
if (child.getTranslationY() < 0) {
// view is coming down
lastViewComingDown = child;
} else if (child.getTranslationY() > 0) {
// view is coming up
if (firstViewComingUp == null) {
firstViewComingUp = child;
}
}
}
if (lastViewComingDown != null && firstViewComingUp != null) {
// views are coming down AND going up to fill the void
top = lastViewComingDown.getBottom() + (int) lastViewComingDown.getTranslationY();
bottom = firstViewComingUp.getTop() + (int) firstViewComingUp.getTranslationY();
} else if (lastViewComingDown != null) {
// views are going down to fill the void
top = lastViewComingDown.getBottom() + (int) lastViewComingDown.getTranslationY();
bottom = lastViewComingDown.getBottom();
} else if (firstViewComingUp != null) {
// views are coming up to fill the void
top = firstViewComingUp.getTop();
bottom = firstViewComingUp.getTop() + (int) firstViewComingUp.getTranslationY();
}
mBackground.setBounds(left, top, right, bottom);
mBackground.draw(c);
} else {
mRemoving = false;
}
super.onDraw(c, parent, state);
}
}
}
|
package DP_entity_linking.search;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import java.util.*;
public class ResultPreprocessing {
private List<Document> newList;
private List<Integer> indexes;
public List<Integer> getIndexes() {
return indexes;
}
public void setIndexes(List<Integer> indexes) {
this.indexes = indexes;
}
public ResultPreprocessing() {
newList = new ArrayList<Document>();
indexes = new ArrayList<Integer>();
}
public List<Document> getNewList() {
return newList;
}
public void setNewList(List<Document> newList) {
this.newList = newList;
}
/**
*
* @param question
* @param list
* @return
*/
private String findCanonic (String question, List<Document> list) {
String canonic = list.get(0).get("title").replaceAll(" ", "_");
for (int i = 0; i < list.size(); i++) {
boolean stop = false;
IndexableField[] alts = list.get(i).getFields("alt");
String fb_name = list.get(i).get("fb_name");
String fb_alias = list.get(i).get("fb_alias");
String entittyTitle = list.get(i).get("title");
List<String> altNames = new ArrayList<String>();
for (IndexableField indexableField : alts) {
altNames.add(indexableField.toString());
}
altNames.add(entittyTitle);
altNames.add(fb_name);
altNames.add(fb_alias);
for (String altName : altNames) {
if (altName == null) {
continue;
}
if (altName.indexOf(">") != -1) {
altName = altName.substring(altName.indexOf(":") + 1, altName.indexOf(">") );
}
if (question.toLowerCase().contains(altName.toLowerCase())) {
canonic = list.get(i).get("title").replaceAll(" ", "_");
stop = true;
break;
}
}
if (stop) {
break;
}
}
return canonic;
}
/**
*
* @param question
* @param list
* @return
*/
public List<List<String>> results(String question, List<Document> list){
String canonic = findCanonic(question,list);
List<List<String>> result = new ArrayList<>();
List<String> canonicList = new ArrayList<String>();
this.setNewList(list);
canonicList = this.addCorrespondingEntities(canonic);
result.add(canonicList);
question = question.replaceAll("[^a-zA-Z0-9]+", " ").toLowerCase().trim();
for (Document l : newList) {
boolean checkAlreadyExist = false;
for (List<String> res : result){
if (res.contains(l.get("title").trim().replaceAll(" ", "_"))){
checkAlreadyExist = true;
continue;
}
}
if (checkAlreadyExist){
continue;
}
List<String> grouped = new ArrayList<String>();
String prepararedQuery = l.get("title");
if (prepararedQuery.indexOf("(") != -1) {
prepararedQuery = prepararedQuery.substring(0, prepararedQuery.indexOf("("));
} else if (prepararedQuery.indexOf(",") != -1) {
prepararedQuery = prepararedQuery.substring(0, prepararedQuery.indexOf(","));
}
List<Integer> indexesFirst = this.findIndexes(question, prepararedQuery.trim().replaceAll(" ", "_"));
if (indexes != null){
for (Document indexList : newList) {
checkAlreadyExist = false;
for (List<String> res : result){
if (res.contains(indexList.get("title").trim().replaceAll(" ", "_"))){
checkAlreadyExist = true;
continue;
}
}
if (checkAlreadyExist){
continue;
}
String comparedQuery = indexList.get("title");
if (comparedQuery.indexOf("(") != -1) {
comparedQuery = comparedQuery.substring(0, comparedQuery.indexOf("("));
} else if (comparedQuery.indexOf(",") != -1) {
comparedQuery = comparedQuery.substring(0, comparedQuery.indexOf(","));
}
List<Integer> comparedIndexes = this.findIndexes(question, comparedQuery.trim().replaceAll(" ", "_"));
if (indexesFirst != null) {
int size = indexesFirst.size();
indexesFirst.retainAll(comparedIndexes);
if (size != (size - indexesFirst.size())){
grouped.add(indexList.get("title").replaceAll(" ", "_"));
}
}
}
if (grouped.size() > 0) {
result.add(grouped);
}
}
this.setIndexes(indexesFirst);
}
return result;
}
/**
* Find indexes of backmapped words in question
* @param question
* @param query
* @return
*/
public List<Integer> findIndexes(String question, String query){
List<Integer> indexes = new ArrayList<Integer>();
String[] canonicArray = query.split("_");
for (String s : canonicArray) {
int index = question.indexOf(s.toLowerCase().replaceAll("[^a-zA-Z0-9]+", " ").trim());
if (index > -1){
indexes.add(index);
}
}
return indexes;
}
/**
* delete corresponding entities to canonic entity
* @param canonic
*/
private List<String> addCorrespondingEntities(String canonic){
String[] canonicArray = canonic.split("_");
Collections.sort(Arrays.asList(canonicArray), new Comparator<String>() {
@Override
public int compare(String s, String t1) {
return t1.length() - s.length();
}
});
List<String> canonicList = new ArrayList<String>();
for (int i = 0; i < newList.size(); i++) {
boolean delete = false;
String entittyTitle = newList.get(i).get("title");
if (entittyTitle.indexOf("(") != -1) {
if (entittyTitle.substring(0, entittyTitle.indexOf("(") ).length() >= canonic.toLowerCase().length()) {
entittyTitle = entittyTitle.substring(0, entittyTitle.indexOf("("));
} else {
delete = true;
}
} else if (entittyTitle.indexOf(",") != -1) {
if (entittyTitle.substring(0, entittyTitle.indexOf(",") ).length() >= canonic.toLowerCase().length()) {
entittyTitle = entittyTitle.substring(0, entittyTitle.indexOf(","));
} else {
delete = true;
}
}
if (canonic.toLowerCase().contains(entittyTitle.toLowerCase().trim().replaceAll(" ", "_").trim())
|| entittyTitle.toLowerCase().trim().replaceAll(" ", "_").contains(canonic.toLowerCase())
) {
if (newList.get(i).get("title").replaceAll( " ", "_").length() >= canonic.length()) {
canonicList.add(newList.get(i).get("title").replaceAll(" ", "_"));
delete = true;
} else {
delete = true;
}
} else {
int countOfMapped = 0;
for(String c : canonicArray){
if (entittyTitle.toLowerCase().trim().contains(c.toLowerCase()))
countOfMapped++;
}
if(countOfMapped > 0){
delete = true;
}
}
if (delete) {
newList.remove(i);
i
if (newList.size() == 1) {
i = -1;
}
}
}
return canonicList;
}
}
|
package org.micromanager.pipelineUI;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.plaf.basic.BasicArrowButton;
import java.util.List;
import mmcorej.TaggedImage;
import net.miginfocom.swing.MigLayout;
import org.micromanager.api.DataProcessor;
import org.micromanager.api.ScriptInterface;
import org.micromanager.utils.ReportingUtils;
public class ProcessorPanel extends javax.swing.JPanel {
// The DataProcessor we are displaying controls for.
DataProcessor<TaggedImage> processor_;
// We need access to the ScriptInterface to enable/disable the Processor.
ScriptInterface gui_;
// Checkbox for enabling/disabling the Processor.
javax.swing.JCheckBox activeBox_;
// Preferred width of the panel.
public static int preferredWidth = 400;
// Preferred height of the panel.
public static int preferredHeight = 100;
ProcessorPanel(String name, DataProcessor<TaggedImage> processor,
ScriptInterface gui) {
// The central element is the processor name, i.e. the only element
// of variable size. We want it to be of fixed size so that elements
// to its right are properly-aligned.
super(new net.miginfocom.swing.MigLayout("wrap 3",
"[][200!][]"));
processor_ = processor;
gui_ = gui;
activeBox_ = new javax.swing.JCheckBox(
"Active:", processor.getIsEnabled());
activeBox_.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
toggleActive();
}
});
add(activeBox_);
JLabel label = new JLabel(name);
add(label);
// Move the processor up (earlier) in the pipeline.
javax.swing.plaf.basic.BasicArrowButton upButton = new javax.swing.plaf.basic.BasicArrowButton(javax.swing.plaf.basic.BasicArrowButton.NORTH);
upButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveProcessor(-1);
}
});
add(upButton);
JButton configButton = new JButton("Configure");
configButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
processor_.makeConfigurationGUI();
}
});
add(configButton);
JButton deleteButton = new JButton("Delete");
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui_.removeImageProcessor(processor_);
}
});
add(deleteButton);
// Move the processor down (later) in the pipeline.
javax.swing.plaf.basic.BasicArrowButton downButton = new javax.swing.plaf.basic.BasicArrowButton(
javax.swing.plaf.basic.BasicArrowButton.SOUTH);
downButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveProcessor(1);
}
});
add(downButton);
}
// Overriding this method so that layout of these panels works properly.
public java.awt.Dimension getPreferredSize() {
return new java.awt.Dimension(
ProcessorPanel.preferredWidth, ProcessorPanel.preferredHeight);
}
// Toggle whether or not this Processor belongs in the pipeline.
private void toggleActive() {
processor_.setEnabled(activeBox_.isSelected());
}
// Adjust the processor's position in the pipeline by the given offset.
private void moveProcessor(int offset) {
List<DataProcessor<TaggedImage>> pipeline = gui_.getImageProcessorPipeline();
// NB for some reason using List.indexOf doesn't work here, so we
// manually scan the list for a matching Processor.
int curIndex = 0;
for (DataProcessor<TaggedImage> altProcessor : pipeline) {
if (altProcessor.hashCode() == processor_.hashCode()) {
break;
}
curIndex++;
}
if (curIndex == pipeline.size()) {
ReportingUtils.logError("Tried to move a processor that isn't actually in the pipeline!");
return;
}
int targetIndex = curIndex + offset;
if (targetIndex < 0 || targetIndex >= pipeline.size()) {
// Processor is already at the end of the pipeline and can't be
// moved further.
return;
}
pipeline.remove(processor_);
pipeline.add(targetIndex, processor_);
gui_.setImageProcessorPipeline(pipeline);
}
}
|
package org.domokit.oknet;
import android.content.Context;
import android.util.Log;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;
import org.chromium.mojo.bindings.InterfaceRequest;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.DataPipe;
import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojo.system.MojoException;
import org.chromium.mojom.mojo.CookieStore;
import org.chromium.mojom.mojo.HttpServerDelegate;
import org.chromium.mojom.mojo.NetAddress;
import org.chromium.mojom.mojo.NetworkService;
import org.chromium.mojom.mojo.TcpBoundSocket;
import org.chromium.mojom.mojo.TcpConnectedSocket;
import org.chromium.mojom.mojo.UdpSocket;
import org.chromium.mojom.mojo.UrlLoader;
import org.chromium.mojom.mojo.UrlLoaderInterceptorFactory;
import org.chromium.mojom.mojo.WebSocket;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* OkHttp implementation of NetworkService.
*/
public class NetworkServiceImpl implements NetworkService {
private static final String TAG = "NetworkServiceImpl";
private static ExecutorService sThreadPool;
private static OkHttpClient sClient;
private Core mCore;
public NetworkServiceImpl(Context context, Core core, MessagePipeHandle pipe) {
assert core != null;
mCore = core;
if (sThreadPool == null) {
sThreadPool = Executors.newCachedThreadPool();
}
if (sClient == null) {
sClient = new OkHttpClient();
try {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
File cacheDirectory = new File(context.getCacheDir(), "ok_http_cache");
Cache cache = new Cache(cacheDirectory, cacheSize);
sClient.setCache(cache);
} catch (IOException e) {
Log.e(TAG, "Unable to create HTTP cache", e);
}
}
NetworkService.MANAGER.bind(this, pipe);
}
@Override
public void close() {}
@Override
public void onConnectionError(MojoException e) {}
@Override
public void createUrlLoader(InterfaceRequest<UrlLoader> loader) {
UrlLoader.MANAGER.bind(new UrlLoaderImpl(mCore, sClient, sThreadPool), loader);
}
@Override
public void getCookieStore(InterfaceRequest<CookieStore> cookieStore) {
cookieStore.close();
}
@Override
public void createWebSocket(InterfaceRequest<WebSocket> socket) {
socket.close();
}
@Override
public void createTcpBoundSocket(NetAddress localAddress,
InterfaceRequest<TcpBoundSocket> boundSocket, CreateTcpBoundSocketResponse callback) {
boundSocket.close();
}
@Override
public void createTcpConnectedSocket(NetAddress remoteAddress,
DataPipe.ConsumerHandle sendStream, DataPipe.ProducerHandle receiveStream,
InterfaceRequest<TcpConnectedSocket> clientSocket,
CreateTcpConnectedSocketResponse callback) {
sendStream.close();
receiveStream.close();
clientSocket.close();
}
@Override
public void createUdpSocket(InterfaceRequest<UdpSocket> socket) {
socket.close();
}
@Override
public void createHttpServer(NetAddress localAddress, HttpServerDelegate delegate,
CreateHttpServerResponse callback) {
delegate.close();
}
@Override
public void registerUrlLoaderInterceptor(UrlLoaderInterceptorFactory factory) {
factory.close();
}
}
|
package HxCKDMS.HxCEnchants.Handlers;
import HxCKDMS.HxCCore.Handlers.NBTFileIO;
import HxCKDMS.HxCCore.HxCCore;
import HxCKDMS.HxCCore.api.Utils.AABBUtils;
import HxCKDMS.HxCCore.api.Utils.LogHelper;
import HxCKDMS.HxCCore.api.Utils.Teleporter;
import HxCKDMS.HxCEnchants.Configurations;
import HxCKDMS.HxCEnchants.enchantment.Enchants;
import HxCKDMS.HxCEnchants.lib.Reference;
import net.minecraft.block.Block;
import net.minecraft.block.BlockCrops;
import net.minecraft.block.IGrowable;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.monster.EntityGolem;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.monster.EntitySlime;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.DamageSource;
import net.minecraft.world.ChunkPosition;
import net.minecraft.world.World;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.event.world.BlockEvent;
import java.io.File;
import java.util.*;
import static HxCKDMS.HxCEnchants.EnchantConfigHandler.getData;
import static HxCKDMS.HxCEnchants.EnchantConfigHandler.isEnabled;
import static HxCKDMS.HxCEnchants.lib.Reference.*;
@SuppressWarnings({"unchecked", "ConstantConditions"})
public class EnchantHandlers implements IEnchantHandler {
private int ShouldRepair = 60, CanRegen = 60, flyTimer = 1200, swiftTimer = 600, vitTimer = 600, stealthTimer = 600;
FurnaceRecipes furnaceRecipes = FurnaceRecipes.instance();
public static boolean OverCharge = false, FlashButton = false;
private short[] DeadlyAura = new short[4], FieryAura = new short[4],
ToxicAura = new short[4], ThickAura = new short[4],
DarkAura = new short[4], GaiaAura = new short[4],
IcyAura = new short[4], HealingAura = new short[4],
MagneticAura = new short[4], RepulsiveAura = new short[4];
@Override
public void handleHelmetEnchant(EntityPlayerMP player, ItemStack helmet, long itemCharge) {
if (isEnabled("Gluttony", "armor")) {
short gluttony = (short)EnchantmentHelper.getEnchantmentLevel(Enchants.Gluttony.effectId, helmet);
LinkedHashMap<Boolean, Item> tmp = hasFood(player);
if (gluttony > 0 && !tmp.isEmpty() && player.getFoodStats().getFoodLevel() <= (gluttony / 2) + 5 && tmp.containsKey(true) && tmp.get(true) != null) {
player.getFoodStats().addStats(((ItemFood) Items.apple).getHealAmount(new ItemStack(tmp.get(true))), ((ItemFood) Items.apple).getSaturationModifier(new ItemStack(tmp.get(true))));
for (short slot = 0; slot < player.inventory.mainInventory.length; slot++) {
if (player.inventory.mainInventory[slot] != null && player.inventory.mainInventory[slot].getItem() instanceof ItemFood && player.inventory.mainInventory[slot].getItem() == tmp.get(true)) {
player.inventory.decrStackSize(slot, 1);
if (Configurations.enableChargesSystem)
helmet.getTagCompound().setLong("HxCEnchantCharge", itemCharge - getData("Gluttony", "armor")[4]);
break;
}
}
}
}
}
@Override
public void handleChestplateEnchant(EntityPlayerMP player, ItemStack chestplate, long itemCharge) {
if (isEnabled("Vitality", "armor")) {
long charge = chestplate.getTagCompound().getInteger("HxCEnchantCharge");
vitTimer
IAttributeInstance ph = player.getEntityAttribute(SharedMonsterAttributes.maxHealth);
short vitalityLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.Vitality.effectId, chestplate);
double vitality = vitalityLevel * 0.5F;
AttributeModifier HealthBuff = new AttributeModifier(HealthUUID, "HealthBuffedChestplate", vitality, 1);
if (!ph.func_111122_c().contains(HealthBuff) && vitalityLevel != 0 && (charge > getData("Vitality", "armor")[4] || !Configurations.enableChargesSystem))
ph.applyModifier(HealthBuff);
if (ph.func_111122_c().contains(HealthBuff) && vitalityLevel == 0)
ph.removeModifier(HealthBuff);
if (vitTimer <= 0 && Configurations.enableChargesSystem && vitalityLevel > 0) {
chestplate.getTagCompound().setLong("HxCEnchantCharge", charge - getData("Vitality", "armor")[4]);
vitTimer = 600;
}
}
}
@Override
public void handleLeggingEnchant(EntityPlayerMP player, ItemStack leggings, long itemCharge) {
if (isEnabled("Swiftness", "armor")) {
swiftTimer
IAttributeInstance ps = player.getEntityAttribute(SharedMonsterAttributes.movementSpeed);
short speedLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.Swiftness.effectId, leggings);
double speedBoost = speedLevel * 0.2;
AttributeModifier SpeedBuff = new AttributeModifier(SpeedUUID, "SpeedBuffedPants", speedBoost, 1);
if (!ps.func_111122_c().contains(SpeedBuff) && speedLevel != 0 && (itemCharge > getData("Swiftness", "armor")[4] || !Configurations.enableChargesSystem))
ps.applyModifier(SpeedBuff);
if (ps.func_111122_c().contains(SpeedBuff) && speedLevel == 0)
ps.removeModifier(SpeedBuff);
if (swiftTimer <= 0 && Configurations.enableChargesSystem && itemCharge > getData("Swiftness", "armor")[4] && speedLevel > 0) {
leggings.getTagCompound().setLong("HxCEnchantCharge", itemCharge - getData("Swiftness", "armor")[4]);
swiftTimer = 600;
}
}
}
@Override
public void handleBootEnchant(EntityPlayerMP player, ItemStack boots, long itemCharges) {
String UUID = player.getUniqueID().toString();
File CustomPlayerData = new File(HxCCore.HxCCoreDir, "HxC-" + UUID + ".dat");
if (isEnabled("Fly", "armor")) {
short flyLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.Fly.effectId, boots);
if (flyLevel > 0 && player.capabilities.isFlying && !player.capabilities.isCreativeMode)
flyTimer
if (flyTimer <= 0 && Configurations.enableChargesSystem) {
flyTimer = 1200;
boots.getTagCompound().setLong("HxCEnchantCharge", itemCharges - getData("Fly", "armor")[4]);
}
boolean flyhbt = false;
try {
flyhbt = NBTFileIO.getBoolean(CustomPlayerData, "EFlyHasChanged");
} catch (Exception ignored) {}
if (flyLevel > 0 && !player.capabilities.allowFlying && (itemCharges > getData("Fly", "armor")[4] * 2 || !Configurations.enableChargesSystem)) {
player.capabilities.allowFlying = true;
player.sendPlayerAbilities();
NBTFileIO.setBoolean(CustomPlayerData, "EFlyHasChanged", true);
if (Configurations.enableChargesSystem)
boots.getTagCompound().setLong("HxCEnchantCharge", itemCharges - getData("Fly", "armor")[4]);
}
if ((flyLevel < 1 && flyhbt) || (flyLevel > 0 && itemCharges < getData("Fly", "armor")[4])) {
player.capabilities.allowFlying = false;
player.capabilities.isFlying = false;
player.sendPlayerAbilities();
NBTFileIO.setBoolean(CustomPlayerData, "EFlyHasChanged", false);
}
if (player.capabilities.isFlying && flyLevel > 0 && !player.capabilities.isCreativeMode)
player.worldObj.spawnParticle("smoke", player.posX + Math.random() - 0.5d,
player.posY - 1.62d, player.posZ + Math.random() - 0.5d, 0.0d, 0.0d, 0.0d);
}
if (isEnabled("Stealth", "armor")) {
stealthTimer
short stealthLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.Stealth.effectId, boots);
if (stealthLevel > 0) {
Stealth(player, stealthLevel);
if (stealthTimer <= 0 && Configurations.enableChargesSystem) {
boots.getTagCompound().setLong("HxCEnchantCharge", itemCharges - getData("Stealth", "armor")[4]);
stealthTimer = 600;
}
}
}
if (isEnabled("FlashStep", "armor") && FlashButton && itemCharges >= getData("FlashStep", "armor")[4]) {
int FlashLevel = EnchantmentHelper.getEnchantmentLevel(Enchants.FlashStep.effectId, boots);
if (FlashLevel > 0) {
World world = player.worldObj;
double vx, vy, vz, x, y, z;
x = player.posX;
y = player.posY;
z = player.posZ;
vx = player.getLookVec().xCoord;
vy = player.getLookVec().yCoord;
vz = player.getLookVec().zCoord;
for (int i = 10; i < 10 + (3 * FlashLevel); i++) {
if (world.getBlock((int) Math.round(x + vx * i), (int) Math.round(y + vy * i), (int) Math.round(z + vz * i)) != Blocks.air && world.getBlock((int) Math.round(x + vx * i), (int) Math.round(y + vy * i) + 2, (int) Math.round(z + vz * i)) == Blocks.air) {
player.playerNetServerHandler.setPlayerLocation((int) Math.round(x + vx * i), (int) Math.round(y + vy * i) + 2, (int) Math.round(z + vz * i), player.cameraYaw, player.cameraPitch);
if (Configurations.enableChargesSystem)
boots.getTagCompound().setLong("HxCEnchantCharge", itemCharges - getData("FlashStep", "armor")[4]);
} else if (world.getBlock((int) Math.round(x + vx * i), (int) Math.round(y + i), (int) Math.round(z + vz * i)) != Blocks.air && world.getBlock((int) Math.round(x + vx * i), (int) Math.round(y + i) + 2, (int) Math.round(z + vz * i)) == Blocks.air) {
player.playerNetServerHandler.setPlayerLocation((int) Math.round(x + vx * i), (int) Math.round(y + i) + 2, (int) Math.round(z + vz * i), player.cameraYaw, player.cameraPitch);
if (Configurations.enableChargesSystem)
boots.getTagCompound().setLong("HxCEnchantCharge", itemCharges - getData("FlashStep", "armor")[4]);
} else if (world.getBlock((int) Math.round(x + vx * i), (int) Math.round(y + -i), (int) Math.round(z + vz * i)) != Blocks.air && world.getBlock((int) Math.round(x + vx * i), (int) Math.round(y + -i) + 2, (int) Math.round(z + vz * i)) == Blocks.air) {
player.playerNetServerHandler.setPlayerLocation((int) Math.round(x + vx * i), (int) Math.round(y + -i) + 2, (int) Math.round(z + vz * i), player.cameraYaw, player.cameraPitch);
if (Configurations.enableChargesSystem)
boots.getTagCompound().setLong("HxCEnchantCharge", itemCharges - getData("FlashStep", "armor")[4]);
}
}
}
FlashButton = false;
}
}
@Override
public void handleDeathEvent(EntityPlayerMP player, EntityLivingBase victim, ItemStack stack, long itemCharge) {
short vampireLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.Vampirism.effectId, stack);
short examineLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.Examine.effectId, stack);
if (examineLevel > 0 && (itemCharge > getData("Examine", "weapon")[4] || !Configurations.enableChargesSystem))
if (victim instanceof EntityLiving) {
victim.worldObj.spawnEntityInWorld(new EntityXPOrb(victim.worldObj, victim.posX, victim.posY + 1, victim.posZ, examineLevel * getData("Examine", "weapon")[4]));
if (Configurations.enableChargesSystem)
stack.getTagCompound().setLong("HxCEnchantCharge", itemCharge - getData("Examine", "weapon")[4]);
}
if (vampireLevel > 0 && (itemCharge > getData("Vampirism", "weapon")[4] || !Configurations.enableChargesSystem)) {
if (victim instanceof EntityAnimal)
player.getFoodStats().addStats(1, 0.3F);
else if (victim instanceof EntityPlayerMP)
player.getFoodStats().addStats(10, 0.5F);
else if (victim instanceof EntityVillager)
player.getFoodStats().addStats(5, 0.5F);
else if (victim.isEntityUndead())
player.getFoodStats().addStats(0, 0);
else if (victim instanceof EntitySlime)
player.getFoodStats().addStats(1, 0.1F);
else if (victim instanceof EntityEnderman)
player.getFoodStats().addStats(2, 0.2F);
else if (victim instanceof EntityMob)
player.getFoodStats().addStats(3, 0.2F);
else player.getFoodStats().addStats(1, 0.1F);
if (HxCKDMS.HxCCore.Configs.Configurations.DebugMode)
LogHelper.warn(player + "has had their hunger increased by Vampirism.", Reference.MOD_ID);
if (Configurations.enableChargesSystem)
stack.getTagCompound().setLong("HxCEnchantCharge", itemCharge - getData("Vampirism", "weapon")[4]);
}
}
@Override
public void playerTickEvent(EntityPlayerMP player) {
if (isEnabled("OverCharge", "weapon") && player.getHeldItem() != null && player.getHeldItem().isItemEnchanted() && player.getHeldItem().getTagCompound() != null) {
long HeldCharges = 0;
if (Configurations.enableChargesSystem) {
HeldCharges = player.getHeldItem().getTagCompound().getLong("HxCEnchantCharge");
}
boolean stored = player.getHeldItem().getTagCompound().getBoolean("StoredCharge");
int temp = EnchantmentHelper.getEnchantmentLevel(Enchants.Overcharge.effectId, player.getHeldItem()), RequiredCharge = getData("OverCharge", "weapon")[4];
if (temp > 0 && (HeldCharges >= RequiredCharge || !Configurations.enableChargesSystem) && !stored) {
if (OverCharge && player.getHeldItem().getTagCompound().getInteger("HxCOverCharge") != 0) {
player.addChatComponentMessage(new ChatComponentText("You have just stored a charge of " + player.getHeldItem().getTagCompound().getInteger("HxCOverCharge") + "!"));
player.getHeldItem().getTagCompound().setBoolean("StoredCharge", true);
OverCharge = false;
if (Configurations.enableChargesSystem)
player.getHeldItem().getTagCompound().setLong("HxCEnchantCharge", HeldCharges - RequiredCharge);
}
if (!OverCharge && player.getHeldItem().getTagCompound().getInteger("HxCOverCharge") != 0 && HeldCharges >= RequiredCharge * 2) {
player.getHeldItem().getTagCompound().setInteger("HxCOverCharge", player.getHeldItem().getTagCompound().getInteger("HxCOverCharge") + 1);
if (Configurations.enableChargesSystem)
player.getHeldItem().getTagCompound().setLong("HxCEnchantCharge", HeldCharges - RequiredCharge);
}
if (OverCharge && player.getHeldItem().getTagCompound().getInteger("HxCOverCharge") == 0 && HeldCharges >= RequiredCharge * 2) {
OverCharge = false;
player.getHeldItem().getTagCompound().setInteger("HxCOverCharge", player.getHeldItem().getTagCompound().getInteger("HxCOverCharge") + 1);
if (Configurations.enableChargesSystem)
player.getHeldItem().getTagCompound().setLong("HxCEnchantCharge", HeldCharges - RequiredCharge);
}
}
}
if (player.inventory.armorItemInSlot(0) != null && player.inventory.armorItemInSlot(0).hasTagCompound() && player.inventory.armorItemInSlot(0).isItemEnchanted() && player.motionY < -0.8 && !player.isSneaking()) {
int tmp = 0, tmp2 = 0;
if (isEnabled("FeatherFall", "armor") && player.inventory.armorItemInSlot(0).getTagCompound().getLong("HxCEnchantCharge") > getData("FeatherFall", "armor")[4])
tmp = EnchantmentHelper.getEnchantmentLevel(Enchants.FeatherFall.effectId, player.inventory.armorItemInSlot(0));
if (isEnabled("MeteorFall", "armor") && player.inventory.armorItemInSlot(0).getTagCompound().getLong("HxCEnchantCharge") > getData("MeteorFall", "armor")[4])
tmp2 = EnchantmentHelper.getEnchantmentLevel(Enchants.MeteorFall.effectId, player.inventory.armorItemInSlot(0));
if (tmp > 0) {
player.motionY += (0.01f * (tmp / 2));
if (Configurations.enableChargesSystem)
player.inventory.armorItemInSlot(0).getTagCompound().setLong("HxCEnchantCharge", player.inventory.armorItemInSlot(0).getTagCompound().getLong("HxCEnchantCharge") - getData("FeatherFall", "armor")[4]);
}
if (tmp2 > 0) {
player.motionY -= (0.02f * tmp2);
if (Configurations.enableChargesSystem)
player.inventory.armorItemInSlot(0).getTagCompound().setLong("HxCEnchantCharge", player.inventory.armorItemInSlot(0).getTagCompound().getLong("HxCEnchantCharge") - getData("MeteorFall", "armor")[4]);
}
}
}
@Override
public void delayedPlayerTickEvent(EntityPlayerMP player) {
ShouldRepair--; CanRegen--;
if (isEnabled("Repair", "other") && ShouldRepair <= 0) {
RepairItems(player);
ShouldRepair = (getData("Repair", "other")[5]);
}
if (isEnabled("Regen", "armor") && CanRegen <= 0) {
short H = 0, C = 0, L = 0, B = 0;
byte Regen = 0;
if (player.inventory.armorItemInSlot(3) != null)
H = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.ArmorRegen.effectId, player.inventory.armorItemInSlot(3));
if (player.inventory.armorItemInSlot(2) != null)
C = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.ArmorRegen.effectId, player.inventory.armorItemInSlot(2));
if (player.inventory.armorItemInSlot(1) != null)
L = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.ArmorRegen.effectId, player.inventory.armorItemInSlot(1));
if (player.inventory.armorItemInSlot(0) != null)
B = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.ArmorRegen.effectId, player.inventory.armorItemInSlot(0));
if (H > 0) Regen += 1;
if (B > 0) Regen += 1;
if (C > 0) Regen += 1;
if (L > 0) Regen += 1;
ItemStack ArmourHelm = player.inventory.armorItemInSlot(3),
ArmourChest = player.inventory.armorItemInSlot(2),
ArmourLegs = player.inventory.armorItemInSlot(1),
ArmourBoots = player.inventory.armorItemInSlot(0);
long HChrg = -1, CChrg = -1, LChrg = -1, BChrg = -1;
if (Configurations.enableChargesSystem) {
if (ArmourHelm != null && ArmourHelm.getTagCompound() != null)
HChrg = ArmourHelm.getTagCompound().getLong("HxCEnchantCharge");
if (ArmourChest != null && ArmourChest.getTagCompound() != null)
CChrg = ArmourChest.getTagCompound().getLong("HxCEnchantCharge");
if (ArmourLegs != null && ArmourLegs.getTagCompound() != null)
LChrg = ArmourLegs.getTagCompound().getLong("HxCEnchantCharge");
if (ArmourBoots != null && ArmourBoots.getTagCompound() != null)
BChrg = ArmourBoots.getTagCompound().getLong("HxCEnchantCharge");
}
if (player.getHealth() < player.getMaxHealth() && Regen > 0) {
float hp = player.getMaxHealth() - player.getHealth();
CanRegen = getData("Regen", "armor")[4];
if (H > 0 && (HChrg > (hp * 2) / Regen || !Configurations.enableChargesSystem)) {
if (Configurations.enableChargesSystem)
ArmourHelm.getTagCompound().setLong("HxCEnchantCharge", HChrg - H * getData("Regen", "armor")[4]);
player.heal(H / 2);
}
if (C > 0 && (CChrg > (hp * 2) / Regen || !Configurations.enableChargesSystem)) {
if (Configurations.enableChargesSystem)
ArmourChest.getTagCompound().setLong("HxCEnchantCharge", CChrg - C * getData("Regen", "armor")[4]);
player.heal(C / 2);
}
if (L > 0 && (LChrg > (hp * 2) / Regen || !Configurations.enableChargesSystem)) {
if (Configurations.enableChargesSystem)
ArmourLegs.getTagCompound().setLong("HxCEnchantCharge", LChrg - L * getData("Regen", "armor")[4]);
player.heal(L / 2);
}
if (B > 0 && (BChrg > (hp * 2) / Regen || !Configurations.enableChargesSystem)) {
if (Configurations.enableChargesSystem)
ArmourBoots.getTagCompound().setLong("HxCEnchantCharge", BChrg - B * getData("Regen", "armor")[4]);
player.heal(B / 2);
}
}
}
if (player.inventory.armorItemInSlot(0) != null && player.inventory.armorItemInSlot(1) != null &&
player.inventory.armorItemInSlot(2) != null && player.inventory.armorItemInSlot(3) != null &&
player.inventory.armorItemInSlot(0).hasTagCompound() && player.inventory.armorItemInSlot(1).hasTagCompound() &&
player.inventory.armorItemInSlot(2).hasTagCompound() && player.inventory.armorItemInSlot(3).hasTagCompound() &&
player.inventory.armorItemInSlot(0).isItemEnchanted() && player.inventory.armorItemInSlot(1).isItemEnchanted() &&
player.inventory.armorItemInSlot(2).isItemEnchanted() && player.inventory.armorItemInSlot(3).isItemEnchanted()) {
World world = player.getEntityWorld();
long[] chrgs = new long[]{0, 0, 0, 0};
for (short i = 0; i < 4; i++) {
if (player.inventory.armorItemInSlot(i) != null) {
if (isEnabled("AuraDeadly", "armor"))
DeadlyAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.AuraDeadly.effectId, player.inventory.armorItemInSlot(i));
if (isEnabled("AuraDark", "armor"))
DarkAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.AuraDark.effectId, player.inventory.armorItemInSlot(i));
if (isEnabled("AuraFiery", "armor"))
FieryAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.AuraFiery.effectId, player.inventory.armorItemInSlot(i));
if (isEnabled("AuraThick", "armor"))
ThickAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.AuraThick.effectId, player.inventory.armorItemInSlot(i));
if (isEnabled("AuraToxic", "armor"))
ToxicAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.AuraToxic.effectId, player.inventory.armorItemInSlot(i));
if (isEnabled("GaiaAura", "armor"))
GaiaAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.GaiaAura.effectId, player.inventory.armorItemInSlot(i));
if (isEnabled("IcyAura", "armor"))
IcyAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.IcyAura.effectId, player.inventory.armorItemInSlot(i));
if (isEnabled("HealingAura", "armor"))
HealingAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.HealingAura.effectId, player.inventory.armorItemInSlot(i));
if (isEnabled("AuraMagnetic", "armor"))
MagneticAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.AuraMagnetic.effectId, player.inventory.armorItemInSlot(i));
if (isEnabled("RepulsiveAura", "armor"))
RepulsiveAura[i] = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.RepulsiveAura.effectId, player.inventory.armorItemInSlot(i));
if (player.inventory.armorItemInSlot(i).getTagCompound() != null && Configurations.enableChargesSystem)
chrgs[i] = player.inventory.armorItemInSlot(i).getTagCompound().getLong("HxCEnchantCharge");
}
}
if (DeadlyAura[0] > 0 && DeadlyAura[1] > 0 && DeadlyAura[2] > 0 && DeadlyAura[3] > 0 && ((chrgs[0] > getData("AuraDeadly", "armor")[4] && chrgs[1] > getData("AuraDeadly", "armor")[4] && chrgs[2] > getData("AuraDeadly", "armor")[4] && chrgs[3] > getData("AuraDeadly", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((DeadlyAura[0] + DeadlyAura[1] + DeadlyAura[2] + DeadlyAura[3]) / 4);
List<EntityLivingBase> list = player.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (EntityLivingBase entity : list)
if ((Configurations.PlayerAuraDeadly || !(entity instanceof EntityPlayer)) && entity != player && !(entity instanceof EntityGolem) && !entity.isDead && !(entity instanceof EntityAnimal) && !entity.isPotionActive(Potion.wither)) {
entity.addPotionEffect(new PotionEffect(Potion.wither.getId(), 100, 1, true));
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - DeadlyAura[i]);
}
}
if (DarkAura[0] > 0 && DarkAura[1] > 0 && DarkAura[2] > 0 && DarkAura[3] > 0 && ((chrgs[0] > getData("AuraDark", "armor")[4] && chrgs[1] > getData("AuraDark", "armor")[4] && chrgs[2] > getData("AuraDark", "armor")[4] && chrgs[3] > getData("AuraDark", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((DarkAura[0] + DarkAura[1] + DarkAura[2] + DarkAura[3]) / 4);
List list = player.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (EntityLivingBase entity : (List<EntityLivingBase>) list)
if ((Configurations.PlayerAuraDark || !(entity instanceof EntityPlayer)) && entity != player && !(entity instanceof EntityGolem) && !entity.isDead && !(entity instanceof EntityAnimal) && !entity.isPotionActive(Potion.blindness)) {
entity.addPotionEffect(new PotionEffect(Potion.blindness.getId(), 100, 1, true));
entity.addPotionEffect(new PotionEffect(Potion.confusion.getId(), 100, 1, true));
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - DarkAura[i]);
}
}
if (FieryAura[0] > 0 && FieryAura[1] > 0 && FieryAura[2] > 0 && FieryAura[3] > 0 && ((chrgs[0] > getData("AuraFiery", "armor")[4] && chrgs[1] > getData("AuraFiery", "armor")[4] && chrgs[2] > getData("AuraFiery", "armor")[4] && chrgs[3] > getData("AuraFiery", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((FieryAura[0] + FieryAura[1] + FieryAura[2] + FieryAura[3]) / 4);
List list = player.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (EntityLivingBase entity : (List<EntityLivingBase>) list)
if ((Configurations.PlayerAuraFiery || !(entity instanceof EntityPlayer)) && entity != player && !(entity instanceof EntityGolem) && !entity.isDead && !(entity instanceof EntityAnimal) && !entity.isBurning()) {
entity.setFire(100);
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - FieryAura[i]);
}
}
if (ThickAura[0] > 0 && ThickAura[1] > 0 && ThickAura[2] > 0 && ThickAura[3] > 0 && ((chrgs[0] > getData("AuraThick", "armor")[4] && chrgs[1] > getData("AuraThick", "armor")[4] && chrgs[2] > getData("AuraThick", "armor")[4] && chrgs[3] > getData("AuraThick", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((ThickAura[0] + ThickAura[1] + ThickAura[2] + ThickAura[3]) / 4);
List list = player.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (EntityLivingBase entity : (List<EntityLivingBase>) list)
if ((Configurations.PlayerAuraThick || !(entity instanceof EntityPlayer)) && entity != player && !(entity instanceof EntityGolem) && !entity.isDead && !(entity instanceof EntityAnimal) && !entity.isPotionActive(Potion.moveSlowdown)) {
entity.addPotionEffect(new PotionEffect(Potion.digSlowdown.getId(), 100, 1, true));
entity.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), 100, 1, true));
entity.addPotionEffect(new PotionEffect(Potion.weakness.getId(), 100, 1, true));
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - ThickAura[i]);
}
}
if (ToxicAura[0] > 0 && ToxicAura[1] > 0 && ToxicAura[2] > 0 && ToxicAura[3] > 0 && ((chrgs[0] > getData("AuraToxic", "armor")[4] && chrgs[1] > getData("AuraToxic", "armor")[4] && chrgs[2] > getData("AuraToxic", "armor")[4] && chrgs[3] > getData("AuraToxic", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((ToxicAura[0] + ToxicAura[1] + ToxicAura[2] + ToxicAura[3]) / 4);
List list = player.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (EntityLivingBase entity : (List<EntityLivingBase>) list)
if ((Configurations.PlayerAuraToxic || !(entity instanceof EntityPlayer)) && entity != player && !(entity instanceof EntityGolem) && !entity.isDead && !(entity instanceof EntityAnimal) && !entity.isPotionActive(Potion.poison)) {
entity.addPotionEffect(new PotionEffect(Potion.poison.getId(), 500, 1, true));
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - ToxicAura[i]);
}
}
if (GaiaAura[0] > 0 && GaiaAura[1] > 0 && GaiaAura[2] > 0 && GaiaAura[3] > 0 && ((chrgs[0] > getData("GaiaAura", "armor")[4] && chrgs[1] > getData("GaiaAura", "armor")[4] && chrgs[2] > getData("GaiaAura", "armor")[4] && chrgs[3] > getData("GaiaAura", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((GaiaAura[0] + GaiaAura[1] + GaiaAura[2] + GaiaAura[3]) / 4);
int ran = world.rand.nextInt(Math.round(80 / level));
if (ran == 0) {
List<ChunkPosition> crops = getCropsWithinAABB(player.worldObj, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (ChunkPosition pos : crops) {
player.worldObj.getBlock(pos.chunkPosX, pos.chunkPosY, pos.chunkPosZ).updateTick(player.worldObj, pos.chunkPosX, pos.chunkPosY, pos.chunkPosZ, new Random());
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - getData("GaiaAura", "armor")[4]);
}
}
}
if (HealingAura[0] > 0 && HealingAura[1] > 0 && HealingAura[2] > 0 && HealingAura[3] > 0 && ((chrgs[0] > getData("HealingAura", "armor")[4] && chrgs[1] > getData("HealingAura", "armor")[4] && chrgs[2] > getData("HealingAura", "armor")[4] && chrgs[3] > getData("HealingAura", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((HealingAura[0] + HealingAura[1] + HealingAura[2] + HealingAura[3]) / 4);
List list = player.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (EntityLivingBase entity : (List<EntityLivingBase>) list)
if ((Configurations.PlayerHealingAura || !(entity instanceof EntityPlayer)) && entity != player && !(entity instanceof EntityMob) && !entity.isDead && !entity.isPotionActive(Potion.regeneration)) {
entity.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), 500, Math.round(level / 3), true));
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - HealingAura[i]);
}
}
if (IcyAura[0] > 0 && IcyAura[1] > 0 && IcyAura[2] > 0 && IcyAura[3] > 0 && ((chrgs[0] > getData("IcyAura", "armor")[4] && chrgs[1] > getData("IcyAura", "armor")[4] && chrgs[2] > getData("IcyAura", "armor")[4] && chrgs[3] > getData("IcyAura", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((IcyAura[0] + IcyAura[1] + IcyAura[2] + IcyAura[3]) / 4);
List list = player.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
List<ChunkPosition> blocks = getFreezablesWithinAABB(player.worldObj, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (EntityLivingBase entity : (List<EntityLivingBase>) list)
if ((Configurations.PlayerIcyAura || !(entity instanceof EntityPlayer)) && entity != player && !(entity instanceof EntityGolem) && !entity.isDead && !(entity instanceof EntityAnimal) && !entity.isPotionActive(Potion.poison)) {
entity.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), 500, 1, true));
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - IcyAura[i]);
}
for (ChunkPosition pos : blocks) {
if (world.getBlock(pos.chunkPosX, pos.chunkPosY, pos.chunkPosZ) == Blocks.lava)
world.setBlock(pos.chunkPosX, pos.chunkPosY, pos.chunkPosZ, Blocks.obsidian);
if (world.getBlock(pos.chunkPosX, pos.chunkPosY, pos.chunkPosZ) == Blocks.flowing_lava)
world.setBlock(pos.chunkPosX, pos.chunkPosY, pos.chunkPosZ, Blocks.cobblestone);
if (world.getBlock(pos.chunkPosX, pos.chunkPosY, pos.chunkPosZ) == Blocks.water)
world.setBlock(pos.chunkPosX, pos.chunkPosY, pos.chunkPosZ, Blocks.ice);
}
}
if (MagneticAura[0] > 0 && MagneticAura[1] > 0 && MagneticAura[2] > 0 && MagneticAura[3] > 0 && ((chrgs[0] > getData("AuraMagnetic", "armor")[4] && chrgs[1] > getData("AuraMagnetic", "armor")[4] && chrgs[2] > getData("AuraMagnetic", "armor")[4] && chrgs[3] > getData("AuraMagnetic", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((MagneticAura[0] + MagneticAura[1] + MagneticAura[2] + MagneticAura[3]) / 4);
List items = player.worldObj.getEntitiesWithinAABB(EntityItem.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
List exp = player.worldObj.getEntitiesWithinAABB(EntityXPOrb.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (EntityItem item : (List<EntityItem>) items) {
double motionX = player.posX - item.posX;
double motionY = player.boundingBox.minY + player.height - item.posY;
double motionZ = player.posZ - item.posZ;
item.setVelocity(motionX / 8, motionY / 8, motionZ / 8);
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - MagneticAura[i]);
}
for (EntityXPOrb xp : (List<EntityXPOrb>) exp) {
double motionX = player.posX - xp.posX;
double motionY = player.boundingBox.minY + player.height - xp.posY;
double motionZ = player.posZ - xp.posZ;
xp.setVelocity(motionX / 2, motionY / 2, motionZ / 2);
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - MagneticAura[i]);
}
}
if (RepulsiveAura[0] > 0 && RepulsiveAura[1] > 0 && RepulsiveAura[2] > 0 && RepulsiveAura[3] > 0 && ((chrgs[0] > getData("RepulsiveAura", "armor")[4] && chrgs[1] > getData("RepulsiveAura", "armor")[4] && chrgs[2] > getData("RepulsiveAura", "armor")[4] && chrgs[3] > getData("RepulsiveAura", "armor")[4]) || !Configurations.enableChargesSystem)) {
short level = (short) ((RepulsiveAura[0] + RepulsiveAura[1] + RepulsiveAura[2] + RepulsiveAura[3]) / 4);
List list = player.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AABBUtils.getAreaBoundingBox((short) Math.round(player.posX), (short) Math.round(player.posY), (short) Math.round(player.posZ), level));
for (EntityLivingBase ent : (List<EntityLivingBase>) list)
if (ent != player && !(ent instanceof EntityAnimal || ent instanceof EntityVillager || ent instanceof EntityGolem || ent instanceof EntityPlayer)) {
double motionX = player.posX - ent.posX;
double motionY = player.boundingBox.minY + player.height - ent.posY;
double motionZ = player.posZ - ent.posZ;
ent.setVelocity(-motionX / 8, -motionY / 8, -motionZ / 8);
if (Configurations.enableChargesSystem)
for (short i = 0; i < 4; i++)
player.inventory.armorItemInSlot(i).getTagCompound().setLong("HxCEnchantCharge", chrgs[i] - RepulsiveAura[i]);
}
}
}
}
@Override
public void handleAttackEvent(EntityPlayerMP player, EntityLivingBase victim, ItemStack weapon, float damage, long itemCharge) {
if (isEnabled("LifeSteal", "weapon") && (itemCharge > getData("LifeSteal", "weapon")[4] || !Configurations.enableChargesSystem)) {
short lifeStealLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.LifeSteal.effectId, weapon);
if (lifeStealLevel > 0) {
player.heal(damage/10 * lifeStealLevel);
if (Configurations.enableChargesSystem)
weapon.getTagCompound().setLong("HxCEnchantCharge", itemCharge - getData("LifeSteal", "weapon")[4]);
}
}
if (isEnabled("Piercing", "weapon") && (itemCharge > getData("Piercing", "weapon")[4] || !Configurations.enableChargesSystem)) {
short piercingLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.Piercing.effectId, weapon);
if (piercingLevel > 0)
victim.attackEntityFrom(new DamageSource("Piercing").setDamageBypassesArmor().setDamageAllowedInCreativeMode()
.setDamageIsAbsolute(), damage * Configurations.PiercingPercent);
if (Configurations.enableChargesSystem)
weapon.getTagCompound().setLong("HxCEnchantCharge", itemCharge - getData("Piercing", "weapon")[4]);
}
if (isEnabled("Vorpal", "weapon") && (itemCharge > getData("Vorpal", "weapon")[4] || !Configurations.enableChargesSystem)) {
short vorpalLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.Vorpal.effectId, weapon);
if (vorpalLevel > 0) victim.attackEntityFrom(new DamageSource("Vorpal").setDamageBypassesArmor().setDamageAllowedInCreativeMode().setDamageIsAbsolute(), vorpalLevel * getData("Vorpal", "weapon")[4]);
if (Configurations.enableChargesSystem)
weapon.getTagCompound().setLong("HxCEnchantCharge", itemCharge - getData("Vorpal", "weapon")[4]);
}
if (isEnabled("SCurse", "weapon") && (itemCharge > getData("SCurse", "weapon")[4] || !Configurations.enableChargesSystem)) {
short SCurseLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.SCurse.effectId, weapon);
if (SCurseLevel > 0) {
victim.attackEntityFrom(new DamageSource("scurse").setDamageBypassesArmor().setDamageAllowedInCreativeMode().setDamageIsAbsolute(), getData("SCurse", "weapon")[5] * SCurseLevel);
player.addPotionEffect(new PotionEffect(Potion.digSlowdown.getId(), 120 * SCurseLevel, SCurseLevel, true));
player.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), 120, Math.round(SCurseLevel /3), true));
player.addPotionEffect(new PotionEffect(Potion.weakness.getId(), 120 * SCurseLevel, SCurseLevel * getData("SCurse", "weapon")[5], true));
if (Configurations.enableChargesSystem)
weapon.getTagCompound().setLong("HxCEnchantCharge", itemCharge - getData("SCurse", "weapon")[4]);
}
}
if (isEnabled("OverCharge", "weapon") && weapon.getTagCompound().getBoolean("StoredCharge")) {
int OverChage = EnchantmentHelper.getEnchantmentLevel(Enchants.Overcharge.effectId, weapon);
int storedCharge = weapon.getTagCompound().getInteger("HxCOverCharge");
if (OverChage > 0) {
List<EntityLivingBase> list = player.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AABBUtils.getAreaBoundingBox((int)Math.round(player.posX), (int)Math.round(player.posY), (int)Math.round(player.posZ), OverChage*5));
int ndamage = storedCharge/list.size();
for (EntityLivingBase liv : list) {
if (liv != player) {
liv.attackEntityFrom(new DamageSource("OverCharge").setDamageIsAbsolute().setDamageAllowedInCreativeMode(), ndamage);
}
}
weapon.getTagCompound().setInteger("HxCOverCharge", 0);
weapon.getTagCompound().setBoolean("StoredCharge", false);
Map<Integer, Integer> enchs = EnchantmentHelper.getEnchantments(weapon);
enchs.remove((int)getData("OverCharge", "weapon")[0]);
if (OverChage > 1) enchs.put((int) getData("OverCharge", "weapon")[0], OverChage - 1);
EnchantmentHelper.setEnchantments(enchs, weapon);
}
}
}
@Override
public void playerMineBlockEvent(EntityPlayer player, ItemStack tool, long itemCharge, BlockEvent.HarvestDropsEvent event) {
if (isEnabled("FlameTouch", "tool")) {
int AutoSmeltLevel = (short)EnchantmentHelper.getEnchantmentLevel(Enchants.FlameTouch.effectId, tool);
if (AutoSmeltLevel > 0 && (tool.getTagCompound().getLong("HxCEnchantCharge") > getData("FlameTouch", "tool")[4] || !Configurations.enableChargesSystem)) {
for (int i = 0; i < event.drops.size(); i++) {
ItemStack smelted = furnaceRecipes.getSmeltingResult(event.drops.get(i));
if (smelted != null) {
ItemStack drop = smelted.copy();
drop.stackSize *= AutoSmeltLevel;
event.drops.set(i, drop);
if (Configurations.enableChargesSystem)
tool.getTagCompound().setLong("HxCEnchantCharge", tool.getTagCompound().getLong("HxCEnchantCharge") - (getData("FlameTouch", "tool")[4] * AutoSmeltLevel));
}
}
}
}
if (isEnabled("VoidTouch", "tool")) {
short voidLevel = (short) EnchantmentHelper.getEnchantmentLevel(Enchants.VoidTouch.effectId, tool);
if (voidLevel > 0 && (tool.getTagCompound().getLong("HxCEnchantCharge") > getData("VoidTouch", "tool")[4] || !Configurations.enableChargesSystem)) {
for(String block : Configurations.VoidedItems)
event.drops.remove(new ItemStack(Block.getBlockFromName(block)));
if (Configurations.enableChargesSystem)
tool.getTagCompound().setLong("HxCEnchantCharge", tool.getTagCompound().getLong("HxCEnchantCharge") - (getData("VoidTouch", "tool")[4] * voidLevel));
}
}
}
@Override
public void playerHurtEvent(EntityPlayerMP player, DamageSource source, float ammount) {
boolean allowEffect = !(source.damageType.equalsIgnoreCase("wither") ||
source.damageType.equalsIgnoreCase("starve") ||
source.damageType.equalsIgnoreCase("fall") ||
source.damageType.equalsIgnoreCase("explosion.player") ||
source.damageType.equalsIgnoreCase("explosion") ||
source.damageType.equalsIgnoreCase("inWall") ||
source.damageType.equalsIgnoreCase("poison"));
ItemStack ArmourHelm = player.inventory.armorItemInSlot(3),
ArmourChest = player.inventory.armorItemInSlot(2);
int AdrenalineBoostLevel = 0, BattleHealingLevel = 0, WitherProt = 0, DivineInterventionLevel = 0, ExplosiveDischarge = 0;
if (ArmourChest != null && ArmourChest.hasTagCompound() && ArmourChest.isItemEnchanted()) {
if (isEnabled("BattleHealing", "armor"))
BattleHealingLevel = EnchantmentHelper.getEnchantmentLevel(Enchants.BattleHealing.effectId, ArmourChest);
if (isEnabled("DivineIntervention", "armor"))
DivineInterventionLevel = EnchantmentHelper.getEnchantmentLevel(Enchants.DivineIntervention.effectId, ArmourChest);
if (isEnabled("ExplosiveDischarge", "armor") && allowEffect)
ExplosiveDischarge = EnchantmentHelper.getEnchantmentLevel(Enchants.ExplosiveDischarge.effectId, ArmourChest);
if (BattleHealingLevel > 0 && source.damageType.equalsIgnoreCase("generic") && (ArmourChest.getTagCompound().getLong("HxCEnchantCharge") > getData("BattleHealing", "armor")[4] || !Configurations.enableChargesSystem)) {
player.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), BattleHealingLevel * 60, BattleHealingLevel));
if (Configurations.enableChargesSystem)
ArmourChest.getTagCompound().setLong("HxCEnchantCharge", ArmourHelm.getTagCompound().getLong("HxCEnchantCharge") - getData("BattleHealing", "armor")[4]);
}
if (DivineInterventionLevel > 0 && player.prevHealth - ammount <= 1) {
player.heal(5);
int x, y, z;
if (player.getBedLocation(0) != null) {
x = player.getBedLocation(0).posX;
y = player.getBedLocation(0).posY;
z = player.getBedLocation(0).posZ;
} else {
ChunkCoordinates coords = HxCCore.server.worldServerForDimension(0).getSpawnPoint();
x = coords.posX;
y = coords.posY;
z = coords.posZ;
}
if (player.dimension != 0) Teleporter.transferPlayerToDimension(player, 0, x, y, z);
else player.playerNetServerHandler.setPlayerLocation(x, y, z, 90, 0);
Map<Integer, Integer> enchs = EnchantmentHelper.getEnchantments(ArmourChest);
enchs.remove((int)getData("DivineIntervention", "armor")[0]);
if (DivineInterventionLevel > 1) enchs.put((int)getData("DivineIntervention", "armor")[0], DivineInterventionLevel - 1);
EnchantmentHelper.setEnchantments(enchs, ArmourChest);
}
if (ExplosiveDischarge > 0 && (ArmourChest.getTagCompound().getLong("HxCEnchantCharge") > getData("ExplosiveDischarge", "armor")[4] || !Configurations.enableChargesSystem)) {
player.worldObj.createExplosion(player, player.posX, player.posY, player.posZ, 2f * ExplosiveDischarge, false);
if (Configurations.enableChargesSystem)
ArmourChest.getTagCompound().setLong("HxCEnchantCharge", ArmourChest.getTagCompound().getLong("HxCEnchantCharge") - getData("ExplosiveDischarge", "armor")[4]);
}
}
if (ArmourHelm != null && ArmourHelm.hasTagCompound() && ArmourHelm.isItemEnchanted()) {
if (isEnabled("AdrenalineBoost", "armor"))
AdrenalineBoostLevel = EnchantmentHelper.getEnchantmentLevel(Enchants.AdrenalineBoost.effectId, ArmourHelm);
if (isEnabled("WitherProtection", "armor"))
WitherProt = EnchantmentHelper.getEnchantmentLevel(Enchants.WitherProtection.effectId, ArmourHelm);
if (WitherProt > 0 && source.damageType.equalsIgnoreCase("wither") && (ArmourHelm.getTagCompound().getLong("HxCEnchantCharge") > getData("WitherProtection", "armor")[4] || !Configurations.enableChargesSystem)) {
player.removePotionEffect(Potion.wither.getId());
if (Configurations.enableChargesSystem)
ArmourHelm.getTagCompound().setLong("HxCEnchantCharge", ArmourHelm.getTagCompound().getLong("HxCEnchantCharge") - getData("WitherProtection", "armor")[4]);
}
if(AdrenalineBoostLevel > 0 && allowEffect && (ArmourHelm.getTagCompound().getLong("HxCEnchantCharge") > getData("AdrenalineBoost", "armor")[4] || !Configurations.enableChargesSystem)) {
player.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), 60, AdrenalineBoostLevel));
player.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), 60, AdrenalineBoostLevel));
player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 60, AdrenalineBoostLevel));
player.addPotionEffect(new PotionEffect(Potion.jump.getId(), 60, AdrenalineBoostLevel));
player.addPotionEffect(new PotionEffect(Potion.resistance.getId(), 60, AdrenalineBoostLevel));
if (Configurations.enableChargesSystem)
ArmourHelm.getTagCompound().setLong("HxCEnchantCharge", ArmourHelm.getTagCompound().getLong("HxCEnchantCharge") - getData("AdrenalineBoost", "armor")[4]);
}
}
}
private LinkedHashMap<Boolean, Item> hasFood(EntityPlayerMP player) {
LinkedHashMap<Boolean, Item> meh = new LinkedHashMap<>();
for (ItemStack item : player.inventory.mainInventory)
if (item != null && item.getItem() instanceof ItemFood)
meh.put(true, item.getItem());
return meh;
}
private void RepairItems(EntityPlayerMP player){
ItemStack Inv;
ItemStack Armor;
long tmp = 0;
for(int j = 0; j < 36; j++){
Inv = player.inventory.getStackInSlot(j);
if (Inv != null && Inv.isItemStackDamageable() && Inv.hasTagCompound() && Inv.isItemEnchanted() && Inv.getMaxDurability() != Inv.getCurrentDurability()){
if (Configurations.enableChargesSystem)
tmp = Inv.getTagCompound().getLong("HxCEnchantCharge");
int a = EnchantmentHelper.getEnchantmentLevel(Enchants.Repair.effectId, Inv);
int b = Inv.getCurrentDurability() - a;
if (Inv.getCurrentDurability() > 0 && (tmp >= Inv.getCurrentDurability() || !Configurations.enableChargesSystem)) {
Inv.setMetadata(b);
if (Configurations.enableChargesSystem)
Inv.getTagCompound().setLong("HxCEnchantCharge", tmp - a * getData("Repair", "other")[4]);
}
}
}
for(int j = 0; j < 4; j++){
Armor = player.getCurrentArmor(j);
if (Armor != null && Armor.isItemStackDamageable() && Armor.hasTagCompound() && Armor.isItemEnchanted()){
if (Configurations.enableChargesSystem)
tmp = Armor.getTagCompound().getLong("HxCEnchantCharge");
int c = EnchantmentHelper.getEnchantmentLevel(Enchants.Repair.effectId, Armor);
int d = Armor.getCurrentDurability() - c;
if (Armor.getCurrentDurability() > 0 && (tmp >= Armor.getCurrentDurability() || !Configurations.enableChargesSystem)) {
Armor.setMetadata(d);
if (Configurations.enableChargesSystem)
Armor.getTagCompound().setLong("HxCEnchantCharge", tmp - c * getData("Repair", "other")[4]);
}
}
}
}
private void Stealth (EntityPlayerMP player, int StealthLevel) {
int px = Math.round((float)player.posX); int py = Math.round((float)player.posY); int pz = Math.round((float) player.posZ);
List list = player.worldObj.getEntitiesWithinAABB(EntityMob.class, AABBUtils.getAreaBoundingBox(px, py, pz, 24));
for (EntityMob entity : (List<EntityMob>) list) {
IAttributeInstance fr = entity.getEntityAttribute(SharedMonsterAttributes.followRange);
AttributeModifier StealthBuff = new AttributeModifier(StealthUUID, "StealthDeBuff", (fr.getBaseValue()-StealthLevel), 1);
fr.removeModifier(StealthBuff);
fr.applyModifier(StealthBuff);
}
}
private static ArrayList<ChunkPosition> getCropsWithinAABB(World world, AxisAlignedBB box) {
ArrayList<ChunkPosition> crops = new ArrayList();
for(int x = (int)box.minX; (double)x <= box.maxX; ++x) {
for(int y = (int)box.minY; (double)y <= box.maxY; ++y) {
for(int z = (int)box.minZ; (double)z <= box.maxZ; ++z) {
Block block = world.getBlock(x, y, z);
if(block != null && (block instanceof BlockCrops || block instanceof IGrowable || block == Blocks.cactus || block instanceof IPlantable || block == Blocks.vine))
crops.add(new ChunkPosition(x, y, z));
}
}
}
return crops;
}
private static ArrayList<ChunkPosition> getFreezablesWithinAABB(World world, AxisAlignedBB box) {
ArrayList<ChunkPosition> blocks = new ArrayList();
for(int x = (int)box.minX; (double)x <= box.maxX; ++x) {
for(int y = (int)box.minY; (double)y <= box.maxY; ++y) {
for(int z = (int)box.minZ; (double)z <= box.maxZ; ++z) {
Block block = world.getBlock(x, y, z);
if(block != null && (block == Blocks.lava || block == Blocks.flowing_lava || block == Blocks.water))
blocks.add(new ChunkPosition(x, y, z));
}
}
}
return blocks;
}
}
|
package ai.elimu.web.content.word;
import ai.elimu.dao.AllophoneDao;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import ai.elimu.dao.WordDao;
import ai.elimu.model.Contributor;
import ai.elimu.model.content.Allophone;
import ai.elimu.model.content.Word;
import ai.elimu.model.enums.Locale;
import ai.elimu.web.content.number.NumberListController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/content/word/list")
public class WordListController {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private WordDao wordDao;
@Autowired
private AllophoneDao allophoneDao;
@RequestMapping(method = RequestMethod.GET)
public String handleRequest(Model model, HttpSession session) {
logger.info("handleRequest");
Contributor contributor = (Contributor) session.getAttribute("contributor");
// To ease development/testing, auto-generate Words
List<Allophone> allophones = allophoneDao.readAllOrderedByUsage(contributor.getLocale());
List<Word> wordsGenerated = generateWords(contributor.getLocale());
for (Word word : wordsGenerated) {
Word existingWord = wordDao.readByText(word.getLocale(), word.getText());
if (existingWord == null) {
// Verify that only valid Allophones are used (copied from WordCreateController#handleSubmit)
String allAllophonesCombined = "";
for (Allophone allophone : allophones) {
allAllophonesCombined += allophone.getValueIpa();
}
if (StringUtils.isNotBlank(word.getPhonetics())) {
for (char allophoneCharacter : word.getPhonetics().toCharArray()) {
String allophone = String.valueOf(allophoneCharacter);
if (!allAllophonesCombined.contains(allophone)) {
throw new IllegalArgumentException("Invalid Allophone in the Word \"" + word.getText() + "\": /" + allophone + "/");
}
}
}
wordDao.create(word);
}
}
List<Word> words = wordDao.readAllOrderedByUsage(contributor.getLocale());
model.addAttribute("words", words);
int maxUsageCount = 0;
for (Word word : words) {
if (word.getUsageCount() > maxUsageCount) {
maxUsageCount = word.getUsageCount();
}
}
model.addAttribute("maxUsageCount", maxUsageCount);
return "content/word/list";
}
/**
* Note: these number words should be generated _before_ their corresponding numbers (see
* {@link NumberListController#generateNumbers(ai.elimu.model.enums.Locale)}).
*/
private List<Word> generateWords(Locale locale) {
List<Word> words = new ArrayList<>();
// Add number words
Word wordZero = new Word();
wordZero.setLocale(locale);
wordZero.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordZero.setText("zero");
wordZero.setPhonetics("ˈzɪrɔʊ");
} else if (locale == Locale.FI) {
wordZero.setText("sero");
wordZero.setPhonetics("sɛr̩ɔ");
} else if (locale == Locale.SW) {
wordZero.setText("sifuri");
wordZero.setPhonetics("siˈfuɾi");
}
words.add(wordZero);
Word wordOne = new Word();
wordOne.setLocale(locale);
wordOne.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordOne.setText("one");
wordOne.setPhonetics("wʌn");
} else if (locale == Locale.FI) {
wordOne.setText("isa");
wordOne.setPhonetics("ɪsɑ");
} else if (locale == Locale.SW) {
wordOne.setText("moja");
wordOne.setPhonetics("ˈmɔjɑ");
wordOne.setUsageCount(29);
}
words.add(wordOne);
Word wordTwo = new Word();
wordTwo.setLocale(locale);
wordTwo.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordTwo.setText("two");
wordTwo.setPhonetics("tu");
} else if (locale == Locale.FI) {
wordTwo.setText("dalawa");
wordTwo.setPhonetics("dɑlɑwɑ");
} else if (locale == Locale.SW) {
wordTwo.setText("mbili");
wordTwo.setPhonetics("mˈbili");
}
words.add(wordTwo);
Word wordThree = new Word();
wordThree.setLocale(locale);
wordThree.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordThree.setText("three");
wordThree.setPhonetics("θri");
} else if (locale == Locale.FI) {
wordThree.setText("tatlo");
wordThree.setPhonetics("tɑtlɔ");
} else if (locale == Locale.SW) {
wordThree.setText("tatu");
wordThree.setPhonetics("ˈtɑtu");
wordThree.setUsageCount(6);
}
words.add(wordThree);
Word wordFour = new Word();
wordFour.setLocale(locale);
wordFour.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordFour.setText("four");
wordFour.setPhonetics("fɔr");
} else if (locale == Locale.FI) {
wordFour.setText("apat");
wordFour.setPhonetics("ɑpɑt");
} else if (locale == Locale.SW) {
wordFour.setText("nne");
wordFour.setPhonetics("nˈnɛ");
}
words.add(wordFour);
Word wordFive = new Word();
wordFive.setLocale(locale);
wordFive.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordFive.setText("five");
wordFive.setPhonetics("fɑɪv");
} else if (locale == Locale.FI) {
wordFive.setText("lima");
wordFive.setPhonetics("lɪmɑ");
} else if (locale == Locale.SW) {
wordFive.setText("tano");
wordFive.setPhonetics("ˈtɑnɔ");
}
words.add(wordFive);
Word wordSix = new Word();
wordSix.setLocale(locale);
wordSix.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordSix.setText("six");
wordSix.setPhonetics("sɪks");
} else if (locale == Locale.FI) {
wordSix.setText("anim");
wordSix.setPhonetics("ɑnɪm");
} else if (locale == Locale.SW) {
wordSix.setText("sita");
wordSix.setPhonetics("ˈsitɑ");
wordSix.setUsageCount(3);
}
words.add(wordSix);
Word wordSeven = new Word();
wordSeven.setLocale(locale);
wordSeven.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordSeven.setText("seven");
wordSeven.setPhonetics("ˈsɛvən");
} else if (locale == Locale.FI) {
wordSeven.setText("pito");
wordSeven.setPhonetics("pɪtɔ");
} else if (locale == Locale.SW) {
wordSeven.setText("saba");
wordSeven.setPhonetics("ˈsɑbɑ");
wordSeven.setUsageCount(4);
}
words.add(wordSeven);
Word wordEight = new Word();
wordEight.setLocale(locale);
wordEight.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordEight.setText("eight");
wordEight.setPhonetics("ɛɪt");
} else if (locale == Locale.FI) {
wordEight.setText("walo");
wordEight.setPhonetics("wɑlɔ");
} else if (locale == Locale.SW) {
wordEight.setText("nane");
wordEight.setPhonetics("ˈnɑnɛ");
wordEight.setUsageCount(1);
}
words.add(wordEight);
Word wordNine = new Word();
wordNine.setLocale(locale);
wordNine.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordNine.setText("nine");
wordNine.setPhonetics("nɑɪn");
} else if (locale == Locale.FI) {
wordNine.setText("siyam");
wordNine.setPhonetics("ʃɑm");
} else if (locale == Locale.SW) {
wordNine.setText("tisa");
wordNine.setPhonetics("ˈtisɑ");
}
words.add(wordNine);
Word wordTen = new Word();
wordTen.setLocale(locale);
wordTen.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordTen.setText("ten");
wordTen.setPhonetics("tɛn");
} else if (locale == Locale.FI) {
wordTen.setText("sampu");
wordTen.setPhonetics("sɑmpu");
} else if (locale == Locale.SW) {
wordTen.setText("kumi");
wordTen.setPhonetics("kumi");
wordTen.setUsageCount(2);
}
words.add(wordTen);
if (locale == Locale.SW) {
// E.g. "kumi na mbili", which literally means "ten and two" (12)
Word wordNa = new Word();
wordNa.setLocale(locale);
wordNa.setTimeLastUpdate(Calendar.getInstance());
wordNa.setText("na");
wordNa.setPhonetics("nɑ");
wordNa.setUsageCount(179);
words.add(wordNa);
}
Word wordEleven = new Word();
wordEleven.setLocale(locale);
wordEleven.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordEleven.setText("eleven");
wordEleven.setPhonetics("ɪˈlɛvən");
} else if (locale == Locale.FI) {
wordEleven.setText("labing-isa"); // TODO: handle "labing" and "isa" as separate words?
wordEleven.setPhonetics("ˌˌˌ"); // TODO
}
words.add(wordEleven);
Word wordTwelve = new Word();
wordTwelve.setLocale(locale);
wordTwelve.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordTwelve.setText("twelve");
wordTwelve.setPhonetics("twɛlv");
} else if (locale == Locale.FI) {
wordTwelve.setText("labindalawa");
wordTwelve.setPhonetics("ˌˌˌ"); // TODO
}
words.add(wordTwelve);
Word wordThirteen = new Word();
wordThirteen.setLocale(locale);
wordThirteen.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordThirteen.setText("thirteen");
wordThirteen.setPhonetics("θɛrtin");
} else if (locale == Locale.FI) {
wordThirteen.setText("labintatlo");
wordThirteen.setPhonetics("ˌˌˌ"); // TODO
}
words.add(wordThirteen);
Word wordFourteen = new Word();
wordFourteen.setLocale(locale);
wordFourteen.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordFourteen.setText("fourteen");
wordFourteen.setPhonetics("ˈfɔrˈtin");
} else if (locale == Locale.FI) {
wordFourteen.setText("labing-apat");
wordFourteen.setPhonetics("ˌˌˌ"); // TODO
}
words.add(wordFourteen);
Word wordFifteen = new Word();
wordFifteen.setLocale(locale);
wordFifteen.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordFifteen.setText("fifteen");
wordFifteen.setPhonetics("fɪfˈtin");
} else if (locale == Locale.FI) {
wordFifteen.setText("labinlima");
wordFifteen.setPhonetics("ˌˌˌ"); // TODO
}
words.add(wordFifteen);
Word wordSixteen = new Word();
wordSixteen.setLocale(locale);
wordSixteen.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordSixteen.setText("sixteen");
wordSixteen.setPhonetics("sɪkˈstin");
} else if (locale == Locale.FI) {
wordSixteen.setText("labing-anim");
wordSixteen.setPhonetics("ˌˌˌ"); // TODO
}
words.add(wordSixteen);
Word wordSeventeen = new Word();
wordSeventeen.setLocale(locale);
wordSeventeen.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordSeventeen.setText("seventeen");
wordSeventeen.setPhonetics("ˈsɛvənˈtin");
} else if (locale == Locale.FI) {
wordSeventeen.setText("labimpito");
wordSeventeen.setPhonetics("ˌˌˌ"); // TODO
}
words.add(wordSeventeen);
Word wordEighteen = new Word();
wordEighteen.setLocale(locale);
wordEighteen.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordEighteen.setText("eighteen");
wordEighteen.setPhonetics("ɛɪtin");
} else if (locale == Locale.FI) {
wordEighteen.setText("labingwalo");
wordEighteen.setPhonetics("ˌˌˌ"); // TODO
}
words.add(wordEighteen);
Word wordNineteen = new Word();
wordNineteen.setLocale(locale);
wordNineteen.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordNineteen.setText("nineteen");
wordNineteen.setPhonetics("ˈnaɪnˈtin");
} else if (locale == Locale.FI) {
wordNineteen.setText("labinsiyam");
wordNineteen.setPhonetics("ˌˌˌ"); // TODO
}
words.add(wordNineteen);
Word wordTwenty = new Word();
wordTwenty.setLocale(locale);
wordTwenty.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordTwenty.setText("twenty");
wordTwenty.setPhonetics("ˈtwɛnti");
} else if (locale == Locale.FI) {
wordTwenty.setText("dalawampu");
wordTwenty.setPhonetics("ˌˌˌ"); // TODO
} else if (locale == Locale.SW) {
wordTwenty.setText("ishirini");
wordTwenty.setPhonetics("iʃiɾini");
}
words.add(wordTwenty);
if (locale == Locale.FI) {
// "dalawampu't" = "dalawampu at", e.g. in "dalawampu't isa" (21)
Word wordTwentyAnd = new Word();
wordTwentyAnd.setLocale(locale);
wordTwentyAnd.setTimeLastUpdate(Calendar.getInstance());
wordTwentyAnd.setText("dalawampu't"); // TODO: handle apostrophe in "dalawampu't" ("dalawampu at")
wordTwentyAnd.setPhonetics("ˌˌˌ"); // TODO
words.add(wordTwentyAnd);
}
if (locale == Locale.EN) {
Word wordTwentyOne = new Word();
wordTwentyOne.setLocale(locale);
wordTwentyOne.setTimeLastUpdate(Calendar.getInstance());
wordTwentyOne.setText("twenty-one"); // TODO: handle words separated by hyphen
wordTwentyOne.setPhonetics("ˈtwɛntiˈwʌn"); // TODO: handle pauses (whitespaces)
words.add(wordTwentyOne);
Word wordTwentyTwo = new Word();
wordTwentyTwo.setLocale(locale);
wordTwentyTwo.setTimeLastUpdate(Calendar.getInstance());
wordTwentyTwo.setText("twenty-two"); // TODO: handle words separated by hyphen
wordTwentyTwo.setPhonetics("ˈtwɛntiˈtu"); // TODO: handle pauses (whitespaces)
words.add(wordTwentyTwo);
}
Word wordThirty = new Word();
wordThirty.setLocale(locale);
wordThirty.setTimeLastUpdate(Calendar.getInstance());
if (locale == Locale.EN) {
wordThirty.setText("thirty");
wordThirty.setPhonetics("ˈθɝtɪ");
} else if (locale == Locale.FI) {
wordThirty.setText("tatlumpu");
wordThirty.setPhonetics("ˌˌˌ"); // TODO
} else if (locale == Locale.SW) {
wordThirty.setText("thelathini");
wordThirty.setPhonetics("θɛlɑθini");
}
words.add(wordThirty);
// TODO: add
return words;
}
}
|
package acromusashi.stream.example.bolt;
import java.text.MessageFormat;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import acromusashi.stream.bolt.BaseConfigurationBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Tuple;
/**
* Bolt
* <ul>
* <li> )How</li>
* <li>Bolt </li>
* <li> How 5</li>
* </ul>
*
* @author kimura
*/
public class WordCountBolt extends BaseConfigurationBolt
{
/** serialVersionUID */
private static final long serialVersionUID = 9080948772140456741L;
/** logger */
private static final Logger logger = LoggerFactory.getLogger(WordCountBolt.class);
private Map<String, Integer> counts = new TreeMap<String, Integer>();
private static final long DEFAULT_INTERVAL = 100;
private long interval = DEFAULT_INTERVAL;
private long receiveCount;
/**
* {@inheritDoc}
*/
@Override
public void execute(Tuple input)
{
String word = input.getStringByField("word");
word = word.toLowerCase();
Integer count = this.counts.get(word);
if (count == null)
{
count = 0;
}
count++;
this.counts.put(word, count);
this.receiveCount++;
if (this.receiveCount % this.interval == 0)
{
String logFormat = "WordCount Result. : CountResult={0}";
logger.info(MessageFormat.format(logFormat, this.counts.toString()));
}
}
/**
* {@inheritDoc}
*/
@Override
public void declareOutputFields(OutputFieldsDeclarer arg0)
{
// Bolt
}
/**
* @param interval interval
*/
public void setInterval(long interval)
{
this.interval = interval;
}
}
|
package au.gov.dva.sopref.interfaces.model;
import java.time.LocalDate;
import java.util.Optional;
public interface Operation {
String getName();
ServiceType getServiceType();
LocalDate getStartDate();
Optional<LocalDate> getEndDate();
}
|
package se.chalmers.dat255.sleepfighter.activities;
import java.util.HashSet;
import java.util.Locale;
import se.chalmers.dat255.sleepfighter.IntentUtils;
import se.chalmers.dat255.sleepfighter.R;
import se.chalmers.dat255.sleepfighter.SFApplication;
import se.chalmers.dat255.sleepfighter.TimepickerPreference;
import se.chalmers.dat255.sleepfighter.model.Alarm;
import se.chalmers.dat255.sleepfighter.model.AlarmList;
import se.chalmers.dat255.sleepfighter.utils.DateTextUtils;
import se.chalmers.dat255.sleepfighter.utils.MetaTextUtils;
import android.content.SharedPreferences;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.Toast;
public class AlarmSettingsActivity extends PreferenceActivity {
private final String NAME = "pref_alarm_name";
private final String TIME = "pref_alarm_time";
private final String DAYS = "pref_enabled_days";
private final String REPEAT = "pref_alarm_repeat";
private final String DELETE = "pref_delete_alarm";
// is used in sBindPreferenceSummaryToValueListener
private String[] weekdayStrings;
private Alarm alarm;
private AlarmList alarmList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
weekdayStrings = AlarmSettingsActivity.this.getResources().getStringArray(R.array.week_days);
final int id = new IntentUtils( this.getIntent() ).getAlarmId();
alarmList = ((SFApplication) getApplication()).getAlarms();
alarm = alarmList.getById(id);
if (alarm == null) {
// TODO: Better handling for final product
Toast.makeText(this, "Alarm is null (ID: " + id + ")", Toast.LENGTH_SHORT).show();
finish();
}
this.setTitle(MetaTextUtils.printAlarmName(this, alarm));
// TODO: Remove this debug thing
this.setTitle(this.getTitle() + " (ID: " + alarm.getId() + ")");
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
int hour = alarm.getHour();
int minute = alarm.getMinute();
editor.putString(TIME, (hour < 10 ? "0" : "") + hour + ":" + (minute < 10 ? "0" : "") + minute);
editor.commit();
setupSimplePreferencesScreen();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
// Using deprecated methods because we need to support Android API level 8
@SuppressWarnings("deprecation")
private void setupSimplePreferencesScreen() {
addPreferencesFromResource(R.xml.pref_alarm_general);
bindPreferenceSummaryToValue(findPreference(TIME));
bindPreferenceSummaryToValue(findPreference(NAME));
bindPreferenceSummaryToValue(findPreference(DAYS));
bindPreferenceSummaryToValue(findPreference(REPEAT));
findPreference(DELETE).setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alarmList.remove(alarm);
finish();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(AlarmSettingsActivity.this);
builder.setMessage("Do you really want to delete this alarm?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", null).show();
return false;
}
});
}
private Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (TIME.equals(preference.getKey())) {
TimepickerPreference tpPref = (TimepickerPreference) preference;
int hour = tpPref.getHour();
int minute = tpPref.getMinute();
alarm.setTime(hour, minute);
preference.setSummary((hour < 10 ? "0" : "") + hour + ":" + (minute < 10 ? "0" : "") + minute);
}
else if (NAME.equals(preference.getKey())) {
alarm.setName(stringValue);
preference.setSummary(stringValue);
}
else if(DAYS.equals(preference.getKey())) {
boolean[] enabledDays = { false, false, false, false, false, false, false };
// a set of all the selected weekdays.
@SuppressWarnings("unchecked")
HashSet<String> set = (HashSet<String>)value;
for(int i = 0; i < weekdayStrings.length; ++i) {
if(set.contains(weekdayStrings [i])) {
enabledDays[i] = true;
}
}
alarm.setEnabledDays(enabledDays);
preference.setSummary(DateTextUtils.makeEnabledDaysText(alarm));
}
else if (REPEAT.equals(preference.getKey())) {
alarm.setRepeat(("true".equals(stringValue)) ? true : false);
}
return true;
}
};
private void bindPreferenceSummaryToValue(Preference preference) {
preference.setPersistent(false);
if (NAME.equals(preference.getKey())) {
preference.setSummary(MetaTextUtils.printAlarmName(this, alarm));
}
else if (TIME.equals(preference.getKey())) {
preference.setSummary(alarm.getTimeString());
}
else if(DAYS.equals(preference.getKey())) {
preference.setSummary(DateTextUtils.makeEnabledDaysText(alarm));
}
else if (REPEAT.equals(preference.getKey())) {
((CheckBoxPreference) preference).setChecked(alarm.isRepeating());
}
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
}
}
|
package at.ac.tuwien.inso.initializer;
import at.ac.tuwien.inso.entity.*;
import at.ac.tuwien.inso.repository.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;
import java.math.*;
import java.util.ArrayList;
import java.util.*;
import java.util.stream.*;
import static java.util.Arrays.*;
@Component
public class DataInitializer {
@Autowired
private CourseRepository courseRepository;
@Autowired
private UserAccountRepository userAccountRepository;
@Autowired
private UisUserRepository uisUserRepository;
@Autowired
private SubjectRepository subjectRepository;
@Autowired
private SemesterRepository semesterRepository;
@Autowired
private StudyPlanRepository studyPlanRepository;
@Autowired
private SubjectForStudyPlanRepository subjectForStudyPlanRepository;
@Autowired
private TagRepository tagRepository;
@Autowired
private PendingAccountActivationRepository pendingAccountActivationRepository;
@Autowired
private GradeRepository gradeRepository;
@Autowired
private StudentRepository studentRepository;
@Autowired
private FeedbackRepository feedbackRepository;
private List<StudyPlan> studyplans;
private List<Semester> semesters;
private List<Subject> subjects;
private List<Course> courses;
private List<Student> students;
private List<Lecturer> lecturers;
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester1 = new HashMap<String, Subject>() {
{
put("VU Programmkonstruktion", new Subject("VU Programmkonstruktion", new BigDecimal(8.8)));
put("UE Studieneingangsgespräch", new Subject("UE Studieneingangsgespräch", new BigDecimal(0.2)));
put("VU Technische Grundlagen der Informatik", new Subject("VU Technische Grundlagen der Informatik", new BigDecimal(6.0)));
put("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik", new Subject("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik", new BigDecimal(4.0)));
put("UE Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik", new Subject("UE Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik", new BigDecimal(5.0)));
put("VU Formale Modellierung", new Subject("VU Formale Modellierung", new BigDecimal(3.0)));
put("VU Datenmodellierung", new Subject("VU Datenmodellierung", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester2 = new HashMap<String, Subject>() {
{
put("VU Algorithmen und Datenstrukturen 1", new Subject("VU Algorithmen und Datenstrukturen 1", new BigDecimal(6.0)));
put("VU Algorithmen und Datenstrukturen 2", new Subject("VU Algorithmen und Datenstrukturen 2", new BigDecimal(3.0)));
put("VU Einführung in Visual Computing", new Subject("VU Einführung in Visual Computing", new BigDecimal(6.0)));
put("VU Gesellschaftliche Spannungsfelder der Informatik", new Subject("VU Gesellschaftliche Spannungsfelder der Informatik", new BigDecimal(3.0)));
put("VU Basics of Human Computer Interaction", new Subject("VU Basics of Human Computer Interaction", new BigDecimal(3.0)));
put("VO Analysis für Informatik und Wirtschaftsinformatik", new Subject("VO Analysis für Informatik und Wirtschaftsinformatik", new BigDecimal(2.0)));
put("UE Analysis für Informatik und Wirtschaftsinformatik", new Subject("UE Analysis für Informatik und Wirtschaftsinformatik", new BigDecimal(4.0)));
put("VU Objektorientierte Modellierung", new Subject("VU Objektorientierte Modellierung", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester3 = new HashMap<String, Subject>() {
{
put("VU Objektorientierte Programmiertechniken", new Subject("VU Objektorientierte Programmiertechniken", new BigDecimal(3.0)));
put("VU Funktionale Programmierung", new Subject("VU Funktionale Programmierung", new BigDecimal(3.0)));
put("VO Betriebssysteme", new Subject("VO Betriebssysteme", new BigDecimal(2.0)));
put("UE Betriebssysteme", new Subject("UE Betriebssysteme", new BigDecimal(4.0)));
put("VU Introduction to Security", new Subject("VU Introduction to Security", new BigDecimal(3.0)));
put("VU Daten- und Informatikrecht", new Subject("VU Daten- und Informatikrecht", new BigDecimal(3.0)));
put("VU Datenbanksysteme", new Subject("VU Datenbanksysteme", new BigDecimal(6.0)));
put("VO Statistik und Wahrscheinlichkeitstheorie", new Subject("VO Statistik und Wahrscheinlichkeitstheorie", new BigDecimal(3.0)));
put("UE Statistik und Wahrscheinlichkeitstheorie", new Subject("UE Statistik und Wahrscheinlichkeitstheorie", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester4 = new HashMap<String, Subject>() {
{
put("VU Einführung in die Künstliche Intelligenz", new Subject("VU Einführung in die Künstliche Intelligenz", new BigDecimal(3.0)));
put("VU Theoretische Informatik und Logik", new Subject("VU Theoretische Informatik und Logik", new BigDecimal(6.0)));
put("VO Software Engineering und Projektmanagement", new Subject("VO Software Engineering und Projektmanagement", new BigDecimal(3.0)));
put("PR Software Engineering und Projektmanagement", new Subject("PR Software Engineering und Projektmanagement", new BigDecimal(6.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester5 = new HashMap<String, Subject>() {
{
put("VO Verteilte Systeme", new Subject("VO Verteilte Systeme", new BigDecimal(3.0)));
put("UE Verteilte Systeme", new Subject("UE Verteilte Systeme", new BigDecimal(3.0)));
put("VU Gesellschaftswissenschaftliche Grundlagen der Informatik", new Subject("VU Gesellschaftswissenschaftliche Grundlagen der Informatik", new BigDecimal(3.0)));
put("VU Interface and Interaction Design", new Subject("VU Interface and Interaction Design", new BigDecimal(3.0)));
put("VU Einführung in wissensbasierte Systeme", new Subject("VU Einführung in wissensbasierte Systeme", new BigDecimal(3.0)));
put("SE Wissenschaftliches Arbeiten", new Subject("SE Wissenschaftliches Arbeiten", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester6 = new HashMap<String, Subject>() {
{
put("PR Bachelorarbeit für Informatik und Wirtschaftsinformatik", new Subject("PR Bachelorarbeit für Informatik und Wirtschaftsinformatik", new BigDecimal(10.0)));
}
};
private Map<String, Subject> subjectsOptionalBachelorSoftwareAndInformationEngineering = new HashMap<String, Subject>() {
{
put("VU Propädeutikum für Informatik", new Subject("VU Propädeutikum für Informatik", new BigDecimal(6.0)));
put("VO Deklaratives Problemlösen", new Subject("VO Deklaratives Problemlösen", new BigDecimal(3.0)));
put("UE Deklaratives Problemlösen", new Subject("UE Deklaratives Problemlösen", new BigDecimal(3.0)));
put("VU Logikprogrammierung und Constraints", new Subject("VU Logikprogrammierung und Constraints", new BigDecimal(6.0)));
put("VO Abstrakte Maschinen", new Subject("VO Abstrakte Maschinen", new BigDecimal(3.0)));
put("UE Abstrakte Maschinen", new Subject("UE Abstrakte Maschinen", new BigDecimal(3.0)));
put("VU Microcontroller", new Subject("VU Microcontroller", new BigDecimal(7.0)));
put("UE Programmierung von Betriebssystemen", new Subject("UE Programmierung von Betriebssystemen", new BigDecimal(3.0)));
put("VU Übersetzerbau", new Subject("VU Übersetzerbau", new BigDecimal(6.0)));
put("VO Echtzeitsysteme", new Subject("VO Echtzeitsysteme", new BigDecimal(2.0)));
put("VU Dependable Systems", new Subject("VU Dependable Systems", new BigDecimal(4.0)));
put("VU Internet Security", new Subject("VU Internet Security", new BigDecimal(3.0)));
put("VU Internet Security", new Subject("VU Internet Security", new BigDecimal(3.0)));
put("VU Privacy Enhancing Technology", new Subject("VU Privacy Enhancing Technology", new BigDecimal(3.0)));
put("UE Daten- und Informatikrecht", new Subject("UE Daten- und Informatikrecht", new BigDecimal(3.0)));
put("VU Vertrags- und Haftungsrecht", new Subject("VU Vertrags- und Haftungsrecht", new BigDecimal(3.0)));
put("VU Semistrukturierte Daten", new Subject("VU Semistrukturierte Daten", new BigDecimal(3.0)));
put("VU Web Engineering", new Subject("VU Web Engineering", new BigDecimal(4.5)));
put("VU Computerstatistik", new Subject("VU Computerstatistik", new BigDecimal(3.0)));
put("VU Datenanalyse", new Subject("VU Datenanalyse", new BigDecimal(3.0)));
put("VU Statistical Computing", new Subject("VU Statistical Computing", new BigDecimal(3.0)));
put("VO Logik für Wissensrepräsentation", new Subject("VO Logik für Wissensrepräsentation", new BigDecimal(3.0)));
put("UE Logik für Wissensrepräsentation", new Subject("UE Logik für Wissensrepräsentation", new BigDecimal(3.0)));
put("VO Computernumerik", new Subject("VO Computernumerik", new BigDecimal(3.0)));
put("UE Computernumerik", new Subject("UE Computernumerik", new BigDecimal(1.5)));
put("VO Multivariate Statistik", new Subject("VO Multivariate Statistik", new BigDecimal(4.5)));
put("UE Multivariate Statistik", new Subject("UE Multivariate Statistik", new BigDecimal(1.5)));
put("VU Statistische Simulation und computerintensive Methoden", new Subject("VU Statistische Simulation und computerintensive Methoden", new BigDecimal(3.0)));
put("VU Argumentieren und Beweisen", new Subject("VU Argumentieren und Beweisen", new BigDecimal(6.0)));
put("VU Programm- und Systemverifikation", new Subject("VU Programm- und Systemverifikation", new BigDecimal(6.0)));
put("VU Softwareprojekt-Beobachtung und -Controlling", new Subject("VU Softwareprojekt-Beobachtung und -Controlling", new BigDecimal(6.0)));
put("VU Software-Qualitätssicherung", new Subject("VU Software-Qualitätssicherung", new BigDecimal(6.0)));
put("VU Usability Engineering", new Subject("VU Usability Engineering", new BigDecimal(3.0)));
put("SE Coaching als Führungsinstrument 2", new Subject("SE Coaching als Führungsinstrument 2", new BigDecimal(3.0)));
put("SE Didaktik in der Informatik", new Subject("SE Didaktik in der Informatik", new BigDecimal(3.0)));
put("VO EDV-Vertragsrecht", new Subject("VO EDV-Vertragsrecht", new BigDecimal(1.5)));
put("VO Einführung in Technik und Gesellschaft", new Subject("VO Einführung in Technik und Gesellschaft", new BigDecimal(3.0)));
put("SE Folgenabschätzung von Informationstechnologien", new Subject("SE Folgenabschätzung von Informationstechnologien", new BigDecimal(3.0)));
put("VU Forschungsmethoden", new Subject("VU Forschungsmethoden", new BigDecimal(3.0)));
put("VU Kommunikation und Moderation", new Subject("VU Kommunikation und Moderation", new BigDecimal(3.0)));
put("VU Kooperatives Arbeiten", new Subject("VU Kooperatives Arbeiten", new BigDecimal(3.0)));
put("SE Rechtsinformationsrecherche im Internet", new Subject("SE Rechtsinformationsrecherche im Internet", new BigDecimal(3.0)));
put("VU Softskills für TechnikerInnen", new Subject("VU Softskills für TechnikerInnen", new BigDecimal(3.0)));
put("VU Techniksoziologie und Technikpsychologie", new Subject("VU Techniksoziologie und Technikpsychologie", new BigDecimal(3.0)));
put("VO Theorie und Praxis der Gruppenarbeit", new Subject("VO Theorie und Praxis der Gruppenarbeit", new BigDecimal(3.0)));
put("SE Wissenschaftliche Methodik", new Subject("SE Wissenschaftliche Methodik", new BigDecimal(3.0)));
put("SE Scientific Presentation and Communication", new Subject("SE Scientific Presentation and Communication", new BigDecimal(3.0)));
put("PV Privatissimum aus Fachdidaktik Informatik", new Subject("PV Privatissimum aus Fachdidaktik Informatik", new BigDecimal(4.0)));
put("VU Präsentation und Moderation", new Subject("VU Präsentation und Moderation", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsFreeChoiceInformatics = new HashMap<String, Subject>() {{
put("VU Pilots in Mobile Interaction: User-centered Interaction Research and Evaluation", new Subject("VU Pilots in Mobile Interaction: User-centered Interaction Research and Evaluation", new BigDecimal(3.0)));
put("VU Robotik für RoboCup", new Subject("VU Robotik für RoboCup", new BigDecimal(6.0)));
put("KO Reflections on ICTs and Society", new Subject("KO Reflections on ICTs and Society", new BigDecimal(6.0)));
put("VU Science of Information 1: Transdisciplinary Foundations of Informatics", new Subject("VU Science of Information 1: Transdisciplinary Foundations of Informatics", new BigDecimal(3.0)));
put("VU Parallel Computing", new Subject("VU Parallel Computing", new BigDecimal(6.0)));
put("PR Praktikum aus IT-Security", new Subject("PR Praktikum aus IT-Security", new BigDecimal(6.0)));
put("SE Formale Semantik natürlicher Sprache", new Subject("SE Formale Semantik natürlicher Sprache", new BigDecimal(3.0)));
put("VO Ausgewählte Kapitel der Technischen Informatik", new Subject("VO Ausgewählte Kapitel der Technischen Informatik", new BigDecimal(3.0)));
put("SE Seminar für DiplomandInnen", new Subject("SE Seminar für DiplomandInnen", new BigDecimal(2.0)));
put("SE Computer Vision Seminar für DiplomandInnen", new Subject("SE Computer Vision Seminar für DiplomandInnen", new BigDecimal(2.0)));
put("VU Softwaretechische Konzepte und Infrastrukturtechnologien zur Identifikation von Objekten und Geräten: RFID, Smartcards, NFC und Mobile Phones", new Subject("VU Softwaretechische Konzepte und Infrastrukturtechnologien zur Identifikation von Objekten und Geräten: RFID, Smartcards, NFC und Mobile Phones", new BigDecimal(3.0)));
put("VU Advanced Services Engineering", new Subject("VU Advanced Services Engineering", new BigDecimal(3.0)));
put("SE Forschungsseminar für DiplomandInnen", new Subject("SE Forschungsseminar für DiplomandInnen", new BigDecimal(3.0)));
put("VO Finanzmärkte, Finanzintermediation und Kapitalanlage", new Subject("VO Finanzmärkte, Finanzintermediation und Kapitalanlage", new BigDecimal(3.5)));
put("VU Methodisches, industrielles Software-Engineering mit Funktionalen Sprachen am Fallbeispiel Haskell", new Subject("VU Methodisches, industrielles Software-Engineering mit Funktionalen Sprachen am Fallbeispiel Haskell", new BigDecimal(3.0)));
put("VU IT Governance", new Subject("VU IT Governance", new BigDecimal(3.0)));
put("VU Current Trends in Computer Science", new Subject("VU Current Trends in Computer Science", new BigDecimal(3.0)));
put("VU Programmierung von Strategie-Spielen", new Subject("VU Programmierung von Strategie-Spielen", new BigDecimal(3.0)));
put("VU Medienanalyse und Medienreflexion", new Subject("VU Medienanalyse und Medienreflexion", new BigDecimal(3.0)));
put("EX Exkursion", new Subject("EX Exkursion", new BigDecimal(3.0)));
put("VU Privacy Enhancing Technologies", new Subject("VU Privacy Enhancing Technologies", new BigDecimal(3.0)));
put("VU Theoretische Informatik und Logik für CI", new Subject("VU Theoretische Informatik und Logik für CI", new BigDecimal(6.0)));
put("SE Theorie und Praxis der Evaluierung von innovativen User Interfaces", new Subject("SE Theorie und Praxis der Evaluierung von innovativen User Interfaces", new BigDecimal(3.0)));
put("VU Brückenkurs Programmierung für Studienanfängerinnen", new Subject("VU Brückenkurs Programmierung für Studienanfängerinnen", new BigDecimal(3.0)));
put("VU Mobile (App) Software Engineering", new Subject("VU Mobile (App) Software Engineering", new BigDecimal(3.0)));
put("VU Runtime Verification", new Subject("VU Runtime Verification", new BigDecimal(3.0)));
put("VU 2D and 3D Image Registration", new Subject("VU 2D and 3D Image Registration", new BigDecimal(3.0)));
put("VU Mobile Robotik", new Subject("VU Mobile Robotik", new BigDecimal(4.5)));
put("SE Critical Algorithm Studies", new Subject("SE Critical Algorithm Studies", new BigDecimal(3.0)));
put("VU Brückenkurs Programmierung für Studienanfänger", new Subject("", new BigDecimal(0.0)));
}};
private Map<String, Subject> subjectsBachelorSoftwareAndInformationEngineering;
private Map<String, Course> coursesBachelorSoftwareAndInformationEngineering;
private Map<String, Tag> tags = new HashMap<String, Tag>() {{
put("Programmieren", new Tag("Programmieren"));
put("Java", new Tag("Java"));
put("Debug", new Tag("Debug"));
put("Rekursion", new Tag("Rekursion"));
put("Boolsche Algebra", new Tag("Boolsche Algebra"));
put("RISC", new Tag("RISC"));
put("CISC", new Tag("CISC"));
put("Pipelining", new Tag("Pipelining"));
put("ROM", new Tag("ROM"));
put("PROM/EPROM", new Tag("PROM/EPROM"));
put("2 Complement", new Tag("2 Complement"));
put("1 Complement", new Tag("1 Complement"));
put("Gatterschaltungen", new Tag("Gatterschaltungen"));
put("Befehlssatz", new Tag("Befehlssatz"));
put("Digital", new Tag("Digital"));
put("Zahlentheorie", new Tag("Zahlentheorie"));
put("Aussagenlogik", new Tag("Aussagenlogik"));
put("Mengenlehre", new Tag("Mengenlehre"));
put("Kombinatorik,", new Tag("Kombinatorik,"));
put("Differenzengleichungen", new Tag("Differenzengleichungen"));
put("Graphentheorie", new Tag("Graphentheorie"));
put("Algebraische Strukturen", new Tag("Algebraische Strukturen"));
put("Lineare Algebra", new Tag("Lineare Algebra"));
put("Codierungstheorie", new Tag("Codierungstheorie"));
put("UE", new Tag("UE"));
put("VU", new Tag("VU"));
put("VO", new Tag("VO"));
put("Automaten", new Tag("Automaten"));
put("reguläre Ausdrücke", new Tag("reguläre Ausdrücke"));
put("Grammatiken", new Tag("Grammatiken"));
put("Petri-Netze", new Tag("Petri-Netze"));
put("Prädikatenlogik", new Tag("Prädikatenlogik"));
put("EER", new Tag("EER"));
put("Relationenmodel", new Tag("Relationenmodel"));
put("Domänenkalkül", new Tag("Domänenkalkül"));
put("Datenbanksprachen", new Tag("Datenbanksprachen"));
put("Relationale Entwurfstheorie", new Tag("Relationale Entwurfstheorie"));
put("Normalformen", new Tag("Normalformen"));
put("Datenintegrität", new Tag("Datenintegrität"));
put("SQL", new Tag("SQL"));
put("JDBC", new Tag("JDBC"));
put("DBMS", new Tag("DBMS"));
put("Algorithmen", new Tag("Algorithmen"));
put("Datenstrukturen", new Tag("Datenstrukturen"));
put("Visual Computing", new Tag("Visual Computing"));
put("MATLAB", new Tag("MATLAB"));
put("Fourier", new Tag("Fourier"));
put("Analysis", new Tag("Analysis"));
put("Langweilig", new Tag("Langweilig"));
put("Theorie", new Tag("Theorie"));
put("Gesellschaft", new Tag("Gesellschaft"));
put("Human Computer Interaction", new Tag("Human Computer Interaction"));
put("Laplace", new Tag("Laplace"));
put("Laplace", new Tag("Laplace"));
put("Folgen", new Tag("Folgen"));
put("Reihen", new Tag("Reihen"));
put("Stetigkeit", new Tag("Stetigkeit"));
put("Grenzwerte", new Tag("Grenzwerte"));
put("Nullstellen", new Tag("Nullstellen"));
put("Differentialrechnung", new Tag("Differentialrechnung"));
put("Funktionen", new Tag("Funktionen"));
put("Integralrechnung", new Tag("Integralrechnung"));
put("Objektorientiert", new Tag("Objektorientiert"));
put("UML", new Tag("UML"));
put("Grundlagen", new Tag("Grundlagen"));
put("Hardware", new Tag("Hardware"));
put("Software", new Tag("Software"));
put("Computer Science", new Tag("Computer Science"));
put("Mathe", new Tag("Mathe"));
put("Spaß", new Tag("Spaß"));
put("Einfach", new Tag("Einfach"));
put("Diffizil", new Tag("Diffizil"));
}};
private Map<String, Student> studentMap = new HashMap<String, Student>() {
{
put("Caroline Black", new Student("s1123960", "Caroline Black", "caroline.black@uis.at", new UserAccount("student", "pass", Role.STUDENT)));
put("Emma Dowd", new Student("s1127157", "Emma Dowd", "emma.dowd@gmail.com", new UserAccount("emma", "pass", Role.STUDENT)));
put("John Terry", new Student("s1126441", "John Terry", "john.terry@uis.at", new UserAccount("john", "pass", Role.STUDENT)));
put("Joan Watson", new Student("s0227157", "Joan Watson", "joan.watson@uit.at"));
put("James Bond", new Student("s1527199", "James Bond", "jamesbond_007@yahoo.com"));
put("Trevor Bond", new Student("s0445157", "Trevor Bond", "trevor@uis.at"));
}
};
private Map<String, Lecturer> lecturerMap = new HashMap<String, Lecturer>() {
{
put("Carol Sanderson", new Lecturer("l0100010", "Carol Sanderson", "carol@uis.at"));
put("Una Walker", new Lecturer("l0100011", "Una Walker", "una.walker@uis.at", new UserAccount("lecturer", "pass", Role.LECTURER)));
put("Connor MacLeod", new Lecturer("l0203019", "Connor MacLeod", "connor@gmail.com"));
put("Eric Wilkins", new Lecturer("l1100010", "Eric Wilkins", "e1234567@tuwien.ac.at", new UserAccount("eric", "pass", Role.LECTURER)));
put("Benjamin Piper", new Lecturer("l9123410", "Benjamin Piper", "ben@uis.at", new UserAccount("ben", "pass", Role.LECTURER)));
}
};
@Transactional
public void initialize() {
userAccountRepository.save(new UserAccount("admin", "pass", Role.ADMIN));
createTags();
createSubjects();
createSemesters();
createCourses();
createStudyPlans();
createUsers();
registerStudentsToStudyPlans();
addPreconditionsToSubjects();
registerSubjectsToLecturers();
addTagsToCourses();
addSubjectsToStudyPlans();
registerCoursesToStudents();
giveGrades();
giveFeedback();
}
private void createTags() {
tagRepository.save(tags.values());
}
private void createSubjects() {
createSubjectsBachelorSoftwareAndInformationEngineering();
Iterable<Subject> subjects = subjectRepository.save(subjectsBachelorSoftwareAndInformationEngineering.values());
this.subjects = StreamSupport.stream(subjects.spliterator(), false).collect(Collectors.toList());
}
private void createSubjectsBachelorSoftwareAndInformationEngineering() {
subjectsBachelorSoftwareAndInformationEngineering = new HashMap<>();
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester1);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester2);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester3);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester4);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester5);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester6);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsOptionalBachelorSoftwareAndInformationEngineering);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsFreeChoiceInformatics);
}
private void createSemesters() {
Iterable<Semester> semesters = semesterRepository.save(asList(
new Semester(2016, SemesterType.SummerSemester),
new Semester(2016, SemesterType.WinterSemester)
));
this.semesters = StreamSupport.stream(semesters.spliterator(), false).collect(Collectors.toList());
}
private void createCourses() {
createCoursesBachelorSoftwareAndInformationEngineering();
Iterable<Course> courses = courseRepository.save(coursesBachelorSoftwareAndInformationEngineering.values());
this.courses = StreamSupport.stream(courses.spliterator(), false).collect(Collectors.toList());
}
private void createCoursesBachelorSoftwareAndInformationEngineering() {
coursesBachelorSoftwareAndInformationEngineering = new HashMap<>();
for (String subjectName : subjectsBachelorSoftwareAndInformationEngineering.keySet()) {
coursesBachelorSoftwareAndInformationEngineering.put(
subjectName,
new Course(subjectsBachelorSoftwareAndInformationEngineering.get(subjectName), semesters.get(1)).setStudentLimits(20)
);
}
}
private void createStudyPlans() {
Iterable<StudyPlan> studyplans = studyPlanRepository.save(asList(
new StudyPlan("Bachelor Software and Information Engineering", new EctsDistribution(new BigDecimal(90), new BigDecimal(60), new BigDecimal(30))),
new StudyPlan("Master Business Informatics", new EctsDistribution(new BigDecimal(30), new BigDecimal(70), new BigDecimal(20))),
new StudyPlan("Master Computational Intelligence", new EctsDistribution(new BigDecimal(60), new BigDecimal(30), new BigDecimal(30))),
new StudyPlan("Master Visual Computing", new EctsDistribution(new BigDecimal(60), new BigDecimal(30), new BigDecimal(30))),
new StudyPlan("Master Medical Informatics", new EctsDistribution(new BigDecimal(60), new BigDecimal(30), new BigDecimal(30)), false),
new StudyPlan("Master Computer Science", new EctsDistribution(new BigDecimal(60), new BigDecimal(30), new BigDecimal(30)))
));
this.studyplans = StreamSupport.stream(studyplans.spliterator(), false).collect(Collectors.toList());
}
private void createUsers() {
pendingAccountActivationRepository.save(
new PendingAccountActivation("test", new Student("test", "Test User", "test-user@uis.at"))
);
List<UisUser> usersList = new ArrayList<>(studentMap.values());
usersList.addAll(lecturerMap.values());
Iterable<UisUser> users = uisUserRepository.save(usersList);
students = StreamSupport.stream(users.spliterator(), false)
.filter(it -> it instanceof Student)
.map(it -> (Student) it)
.collect(Collectors.toList());
lecturers = StreamSupport.stream(users.spliterator(), false)
.filter(it -> it instanceof Lecturer)
.map(it -> (Lecturer) it)
.collect(Collectors.toList());
}
private void registerStudentsToStudyPlans() {
studentMap.get("John Terry").addStudyplans(new StudyPlanRegistration(studyplans.get(0), semesters.get(1)));
studentMap.get("Caroline Black").addStudyplans(new StudyPlanRegistration(studyplans.get(1), semesters.get(1)));
studentMap.get("Emma Dowd").addStudyplans(new StudyPlanRegistration(studyplans.get(2), semesters.get(0)));
studentMap.get("Joan Watson").addStudyplans(new StudyPlanRegistration(studyplans.get(3), semesters.get(1)));
studentMap.get("James Bond").addStudyplans(new StudyPlanRegistration(studyplans.get(4), semesters.get(1)));
studentMap.get("James Bond").addStudyplans(new StudyPlanRegistration(studyplans.get(5), semesters.get(0)));
studentMap.get("Trevor Bond").addStudyplans(new StudyPlanRegistration(studyplans.get(1), semesters.get(1)));
}
private void addPreconditionsToSubjects() {
subjects.get(2).addRequiredSubjects(subjects.get(1));
}
private void registerSubjectsToLecturers() {
subjectsBachelorSoftwareAndInformationEngineering.get("UE Studieneingangsgespräch").addLecturers(
lecturerMap.get("Carol Sanderson")
);
subjects.get(0).addLecturers(lecturers.get(3));
subjects.get(1).addLecturers(lecturers.get(3));
subjects.get(2).addLecturers(lecturers.get(3), lecturers.get(4));
subjectRepository.save(subjects);
Subject s = subjectsBachelorSoftwareAndInformationEngineering
.get("VU Technische Grundlagen der Informatik");
s.addLecturers(lecturers.get(3));
subjectRepository.save(s);
s = subjectsBachelorSoftwareAndInformationEngineering
.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik");
s.addLecturers(lecturers.get(3));
subjectRepository.save(s);
}
private void addTagsToCourses() {
addTagsToBachelorSoftwareAndInformationEngineeringCourses();
courseRepository.save(coursesBachelorSoftwareAndInformationEngineering.values());
}
private void addTagsToBachelorSoftwareAndInformationEngineeringCourses() {
addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester1();
addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester2();
}
private void addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester1() {
coursesBachelorSoftwareAndInformationEngineering.get("VU Programmkonstruktion").addTags(
tags.get("VU"), tags.get("Programmieren"), tags.get("Java"), tags.get("Debug"),
tags.get("Rekursion"), tags.get("Software"), tags.get("Einfach"), tags.get("Grundlagen"),
tags.get("Objektorientiert")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik").addTags(
tags.get("VU"), tags.get("Boolsche Algebra"), tags.get("RISC"), tags.get("CISC"), tags.get("Pipelining"),
tags.get("ROM"), tags.get("PROM/EPROM"), tags.get("2 Complement"), tags.get("1 Complement"),
tags.get("Gatterschaltungen"), tags.get("Befehlssatz"), tags.get("Digital"), tags.get("Diffizil"), tags.get("Grundlagen"),
tags.get("Hardware")
);
coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik").addTags(
tags.get("VO"), tags.get("Zahlentheorie"), tags.get("Aussagenlogik"), tags.get("Mengenlehre"),
tags.get("Mathe"), tags.get("Kombinatorik"), tags.get("Differenzengleichungen"),
tags.get("Graphentheorie"), tags.get("Algebraische Strukturen"), tags.get("Lineare Algebra"),
tags.get("Codierungstheorie"), tags.get("Einfach"), tags.get("Funktionen"), tags.get("Grundlagen")
);
coursesBachelorSoftwareAndInformationEngineering.get("UE Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik").addTags(
tags.get("UE"), tags.get("Zahlentheorie"), tags.get("Aussagenlogik"), tags.get("Mengenlehre"),
tags.get("Mathe"), tags.get("Kombinatorik"), tags.get("Differenzengleichungen"),
tags.get("Graphentheorie"), tags.get("Algebraische Strukturen"), tags.get("Lineare Algebra"),
tags.get("Codierungstheorie"), tags.get("Einfach"), tags.get("Funktionen"), tags.get("Grundlagen")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Formale Modellierung").addTags(
tags.get("VU"), tags.get("Automaten"), tags.get("reguläre Ausdrücke"), tags.get("formale Grammatiken"),
tags.get("Aussagenlogik"), tags.get("Petri-Netze"), tags.get("Prädikatenlogik"), tags.get("Diffizil"), tags.get("Grundlagen")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Datenmodellierung").addTags(
tags.get("VU"), tags.get("EER"), tags.get("Relationenmodel"), tags.get("Domänenkalkül"),
tags.get("Datenbanksprachen"), tags.get("Normalformen"), tags.get("Relationale Entwurfstheorie"),
tags.get("Datenintegrität"), tags.get("Einfach"), tags.get("SQL"), tags.get("Grundlagen")
);
}
private void addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester2() {
coursesBachelorSoftwareAndInformationEngineering.get("VU Datenbanksysteme").addTags(
tags.get("VU"), tags.get("EER"), tags.get("Relationenmodel"), tags.get("Domänenkalkül"),
tags.get("Datenbanksprachen"), tags.get("Normalformen"), tags.get("SQL"),
tags.get("Datenintegrität"), tags.get("Diffizil"), tags.get("JDBC"), tags.get("DBMS")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Algorithmen und Datenstrukturen 1").addTags(
tags.get("VU"), tags.get("Datenstrukturen"), tags.get("Algorithmen"), tags.get("Java"),
tags.get("Programmieren"), tags.get("Debug"), tags.get("Rekursion"),
tags.get("Software"), tags.get("Graphentheorie"), tags.get("Einfach")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Algorithmen und Datenstrukturen 2").addTags(
tags.get("VU"), tags.get("Datenstrukturen"), tags.get("Algorithmen"), tags.get("Java"),
tags.get("Programmieren"), tags.get("Debug"), tags.get("Rekursion"),
tags.get("Software"), tags.get("Graphentheorie"), tags.get("Diffizil")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Einführung in Visual Computing").addTags(
tags.get("VU"), tags.get("Visual Computing"), tags.get("MATLAB"), tags.get("Mathe"),
tags.get("Fourier"), tags.get("Analysis"), tags.get("Diffizil"), tags.get("Programmieren"),
tags.get("Grundlagen")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Gesellschaftliche Spannungsfelder der Informatik").addTags(
tags.get("VU"), tags.get("Langweilig"), tags.get("Theorie"), tags.get("Einfach"),
tags.get("Gesellschaft")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Basics of Human Computer Interaction").addTags(
tags.get("VU"), tags.get("Human Computer Interaction"), tags.get("Einfach"), tags.get("Grundlagen")
);
coursesBachelorSoftwareAndInformationEngineering.get("VO Analysis für Informatik und Wirtschaftsinformatik").addTags(
tags.get("VU"), tags.get("Mathe"), tags.get("Analysis"), tags.get("Fourier"),
tags.get("Laplace"), tags.get("Diffizil"), tags.get("Folgen"),
tags.get("Reihen"), tags.get("Stetigkeit"), tags.get("Grenzwerte"),
tags.get("Nullstellen"), tags.get("Differentialrechnung"),
tags.get("Integralrechnung"), tags.get("Funktionen")
);
coursesBachelorSoftwareAndInformationEngineering.get("UE Analysis für Informatik und Wirtschaftsinformatik").addTags(
tags.get("UE"), tags.get("Mathe"), tags.get("Analysis"), tags.get("Fourier"),
tags.get("Laplace"), tags.get("Diffizil"), tags.get("Folgen"),
tags.get("Reihen"), tags.get("Stetigkeit"), tags.get("Grenzwerte"),
tags.get("Nullstellen"), tags.get("Differentialrechnung"),
tags.get("Integralrechnung"), tags.get("Funktionen")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Objektorientierte Modellierung").addTags(
tags.get("VU"), tags.get("Objektorientiert"), tags.get("UML"), tags.get("Grundlagen"),
tags.get("Einfach")
);
}
private void addSubjectsToStudyPlans() {
addBachelorSoftwareAndInformationEngineeringSubjectsToStudyPlan();
}
private void addBachelorSoftwareAndInformationEngineeringSubjectsToStudyPlan() {
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester1.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester1.get(subjectName), studyplans.get(0), true, 1)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester2.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester2.get(subjectName), studyplans.get(0), true, 2)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester3.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester3.get(subjectName), studyplans.get(0), true, 3)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester4.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester4.get(subjectName), studyplans.get(0), true, 4)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester5.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester5.get(subjectName), studyplans.get(0), true, 5)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester6.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester6.get(subjectName), studyplans.get(0), true, 6)
);
}
for (String subjectName : subjectsOptionalBachelorSoftwareAndInformationEngineering.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsOptionalBachelorSoftwareAndInformationEngineering.get(subjectName), studyplans.get(0), false)
);
}
}
private void registerCoursesToStudents() {
// Joan Watson
coursesBachelorSoftwareAndInformationEngineering.get("UE Studieneingangsgespräch").addStudents(studentMap.get("Joan Watson"));
coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik").addStudents(studentMap.get("Joan Watson"));
coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik").addStudents(studentMap.get("Joan Watson"));
// Emma Dowd
coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik").addStudents(studentMap.get("Emma Dowd"));
coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik").addStudents(studentMap.get("Emma Dowd"));
// Caroline Black
coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik").addStudents(studentMap.get("Caroline Black"));
// John Terry
Student john = studentMap.get("John Terry");
coursesBachelorSoftwareAndInformationEngineering.get("VU Datenmodellierung").addStudents(john);
coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik").addStudents(john);
coursesBachelorSoftwareAndInformationEngineering.get("VU Programmkonstruktion").addStudents(john);
}
private void giveGrades() {
Course course = coursesBachelorSoftwareAndInformationEngineering.get("UE Studieneingangsgespräch");
Student student = course.getStudents().get(0);
Lecturer lecturer = course.getSubject().getLecturers().get(0);
Grade grade = new Grade(course, lecturer, student, Mark.EXCELLENT);
gradeRepository.save(grade);
course = coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik");
student = studentMap.get("Emma Dowd");
lecturer = course.getSubject().getLecturers().get(0);
grade = new Grade(course, lecturer, student, Mark.EXCELLENT);
gradeRepository.save(grade);
course = coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik");
student = studentMap.get("Emma Dowd");
lecturer = course.getSubject().getLecturers().get(0);
grade = new Grade(course, lecturer, student, Mark.FAILED);
gradeRepository.save(grade);
grade = new Grade(
coursesBachelorSoftwareAndInformationEngineering.get("VU Datenmodellierung"),
lecturer,
studentMap.get("John Terry"),
Mark.EXCELLENT);
gradeRepository.save(grade);
}
private void giveFeedback() {
Course course = coursesBachelorSoftwareAndInformationEngineering.get("VU Datenmodellierung");
Student johnTerry = studentMap.get("John Terry");
Feedback feedback = new Feedback(johnTerry, course);
feedbackRepository.save(feedback);
course = coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik");
Student joanWatson = studentMap.get("Joan Watson");
Student emmaDowd = studentMap.get("Emma Dowd");
Student carolineBlack = studentMap.get("Caroline Black");
Feedback feedback1 = new Feedback(
joanWatson,
course,
Feedback.Type.LIKE, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec enim ligula. " +
"Sed eget posuere tellus. Aenean fermentum maximus tempor. Ut ultricies dapibus nulla vitae mollis. " +
"Suspendisse a nunc nisi. Sed ut sapien eu odio sodales laoreet eu ac turpis. " +
"In id sapien id ante sollicitudin consectetur at laoreet mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Suspendisse quam sem, ornare eget pellentesque sit amet, tincidunt id metus. Sed scelerisque neque sed laoreet elementum. " +
"Integer eros neque, vulputate a hendrerit at, ullamcorper in orci. Donec sit amet risus hendrerit, hendrerit magna non, dapibus nibh. " +
"Suspendisse sed est feugiat, dapibus ante non, aliquet neque. Cras magna sapien, pharetra ut ante ut, malesuada hendrerit erat. " +
"Mauris fringilla mattis dapibus. Nullam iaculis nunc in tortor gravida, id tempor justo elementum.");
Feedback feedback2 = new Feedback(
emmaDowd,
course,
Feedback.Type.DISLIKE, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec enim ligula. " +
"Sed eget posuere tellus. Aenean fermentum maximus tempor. Ut ultricies dapibus nulla vitae mollis. " +
"Suspendisse a nunc nisi. Sed ut sapien eu odio sodales laoreet eu ac turpis. " +
"In id sapien id ante sollicitudin consectetur at laoreet mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Suspendisse quam sem, ornare eget pellentesque sit amet, tincidunt id metus. Sed scelerisque neque sed laoreet elementum. " +
"Integer eros neque, vulputate a hendrerit at, ullamcorper in orci. Donec sit amet risus hendrerit, hendrerit magna non, dapibus nibh. " +
"Suspendisse sed est feugiat, dapibus ante non, aliquet neque. Cras magna sapien, pharetra ut ante ut, malesuada hendrerit erat. " +
"Mauris fringilla mattis dapibus. Nullam iaculis nunc in tortor gravida, id tempor justo elementum.");
Feedback feedback3 = new Feedback(
carolineBlack,
course,
Feedback.Type.LIKE, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec enim ligula. " +
"Sed eget posuere tellus. Aenean fermentum maximus tempor. Ut ultricies dapibus nulla vitae mollis. " +
"Suspendisse a nunc nisi. Sed ut sapien eu odio sodales laoreet eu ac turpis. " +
"In id sapien id ante sollicitudin consectetur at laoreet mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Suspendisse quam sem, ornare eget pellentesque sit amet, tincidunt id metus. Sed scelerisque neque sed laoreet elementum. " +
"Integer eros neque, vulputate a hendrerit at, ullamcorper in orci. Donec sit amet risus hendrerit, hendrerit magna non, dapibus nibh. " +
"Suspendisse sed est feugiat, dapibus ante non, aliquet neque. Cras magna sapien, pharetra ut ante ut, malesuada hendrerit erat. " +
"Mauris fringilla mattis dapibus. Nullam iaculis nunc in tortor gravida, id tempor justo elementum.");
feedbackRepository.save(asList(feedback1, feedback2, feedback3));
}
}
|
package bammerbom.ultimatecore.sponge.utils;
import bammerbom.ultimatecore.sponge.UltimateCore;
import bammerbom.ultimatecore.sponge.config.GeneralConfig;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.asset.Asset;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.serializer.TextParseException;
import org.spongepowered.api.text.serializer.TextSerializers;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class Messages {
private static Map<String, String> EN_US = new HashMap<>();
private static Map<String, String> custom = new HashMap<>();
public static void reloadMessages() {
reloadEnglishMessages();
reloadCustomMessages();
}
public static void reloadEnglishMessages() {
try {
EN_US = loadFromFile("EN_US");
} catch (IOException e) {
log(Text.of("Failed to load english messages file."));
e.printStackTrace();
}
}
public static void reloadCustomMessages() {
String lang = GeneralConfig.get().getNode("language", "language").getString();
if (lang.equals("EN_US")) {
return;
}
try {
custom = loadFromFile(lang);
} catch (IOException e) {
log(Text.of("Failed to load " + lang + " messages file."));
e.printStackTrace();
}
}
/**
* Retrieves a Map of all keys and values of a language file
*
* @param lang The name of the language file, for example `english` for the file 'EN_US.properties'
* @return A map of all keys and values
* @throws IOException When the file was not found, was invalid, or failed to load in any other way
*/
private static Map<String, String> loadFromFile(String lang) throws IOException {
Asset asset = Sponge.getAssetManager().getAsset(UltimateCore.get(), "language/" + lang + ".properties").orElse(null);
File file = new File(UltimateCore.get().getConfigFolder().toUri().getPath() + "/language/", lang + ".properties");
if (!file.exists()) {
file.getParentFile().mkdirs();
asset.copyToFile(file.toPath());
}
//Properties of the file in the dir
Properties prop = new Properties();
InputStream stream = new FileInputStream(file);
prop.load(stream);
Map<String, String> map = toMap(prop);
stream.close();
//Only check for missing keys if non-custom language file
if (asset != null) {
//Properties of the file in the jar
Properties lprop = new Properties();
InputStream lstream = asset.getUrl().openStream();
lprop.load(lstream);
Map<String, String> lmap = toMap(lprop);
lstream.close();
//Copy missing keys
boolean missing = false;
for (String key : lmap.keySet()) {
if (!map.containsKey(key)) {
map.put(key, lmap.get(key));
prop.put(key, lmap.get(key));
missing = true;
Messages.log("Added missing key " + key + "=" + lmap.get(key) + " to language file " + lang);
}
}
if (missing) {
FileOutputStream ostream = new FileOutputStream(file);
prop.store(ostream, "UltimateCore language file - " + lang);
ostream.close();
}
}
return map;
}
private static Map<String, String> toMap(Properties prop) {
Map<String, String> map = new HashMap<>();
for (Object key : prop.keySet()) {
map.put(key.toString(), prop.getProperty(key.toString()));
}
return map;
}
/**
* Get a string with all available formatting, including click and hover actions.
*
* @param key The key of the message to get
* @param vars The variables to replace. When {Banana, Apple} is provided Banana will be replaced with Apple
* @return The ampersand-formatted message
*/
public static Text getFormatted(String key, Object... vars) {
String raw = get(key, vars);
try {
return TextSerializers.JSON.deserialize(raw);
} catch (TextParseException ex) {
try {
return TextSerializers.TEXT_XML.deserialize(raw);
} catch (TextParseException ex2) {
try {
return TextSerializers.FORMATTING_CODE.deserialize(raw);
} catch (Exception ex3) {
return Text.of(raw);
}
}
}
}
/**
* Get a string which is formatted with Ampersands.
*
* @param key The key of the message to get
* @param vars The variables to replace. When {Banana, Apple} is provided Banana will be replaced with Apple
* @return The ampersand-formatted message
*/
public static String getColored(String key, Object... vars) {
return TextSerializers.FORMATTING_CODE.serialize(getFormatted(key, vars));
}
/**
* Get the pure text without any formatting from the language file.
*
* @param key The key of the message to get
* @param vars The variables to replace. When {Banana, Apple} is provided Banana will be replaced with Apple
* @return The plain-text message
*/
public static String getPlain(String key, Object... vars) {
return getFormatted(key, vars).toPlain();
}
/**
* Get a raw message from the language file.
*
* @param key The key of the message to get
* @param vars The variables to replace. When {Banana, Apple} is provided Banana will be replaced with Apple
* @return The raw message
*/
public static String get(String key, Object... vars) {
String raw;
if (custom.containsKey(key)) {
raw = custom.get(key);
} else if (EN_US.containsKey(key)) {
raw = EN_US.get(key);
} else {
raw = ""; //TODO what to do? Optional?
}
String first = null;
for (Object var : vars) {
if (first == null) {
first = var.toString();
} else {
if (var instanceof Text) {
Text text = (Text) var;
var = TextSerializers.FORMATTING_CODE.serialize(text); //TODO does this work?
}
raw = raw.replace(first, var.toString());
first = null;
}
}
return raw;
}
/**
* Print the message to the console, with the UC prefix in front of it.
*
* @param message The message to print
*/
public static void log(Object message) {
Text logo = Text.of("[UC] ");
if (message == null) {
log("null");
return;
}
Sponge.getServer().getConsole().sendMessage(logo.toBuilder().append(Text.of(message)).build());
}
/**
* Does exactly the same as .log(), but can be found using ctrl + f so I can remove them later
*/
public static void debug(Object message) {
log(message);
}
/**
* Convert a String to a Text object
*/
public static Text toText(String raw) {
try {
return TextSerializers.JSON.deserialize(raw);
} catch (TextParseException ex) {
try {
return TextSerializers.TEXT_XML.deserialize(raw);
} catch (TextParseException ex2) {
try {
return TextSerializers.FORMATTING_CODE.deserialize(raw);
} catch (Exception ex3) {
return Text.of(raw);
}
}
}
}
}
|
package retrofit.http;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.name.Named;
import junit.framework.TestCase;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicStatusLine;
import org.easymock.Capture;
import org.easymock.IAnswer;
import org.junit.Before;
import retrofit.core.Callback;
import retrofit.core.MainThread;
import retrofit.internal.gson.Gson;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.Executor;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static retrofit.http.RestAdapter.service;
public class RestAdapterTest extends TestCase {
private static final String ID = "123";
private static final String ENTITY = "entity";
private static final String ENTITY_PATH_PARAM = "entity/{id}";
private static final String BASE_URL = "http://host/api/entity";
private static final String PATH_URL_PREFIX = BASE_URL + "/";
private static final String GET_DELETE_SIMPLE_URL = BASE_URL + "?";
private Injector injector;
private HttpClient mockHttpClient;
private Executor mockExecutor;
private MainThread mockMainThread;
private Headers mockHeaders;
@SuppressWarnings("rawtypes") private Callback mockCallback;
private HttpResponse mockResponse;
private Gson gson = new Gson();
@Override @Before public void setUp() throws Exception {
mockHttpClient = createMock(HttpClient.class);
mockExecutor = createMock(Executor.class);
mockMainThread = createMock(MainThread.class);
mockHeaders = createMock(Headers.class);
mockCallback = createMock(Callback.class);
mockResponse = createMock(HttpResponse.class);
injector = Guice.createInjector(
new AbstractModule() {
@Override protected void configure() {
bind(Server.class).toInstance(new Server("http://host/api/",
"http://host/web/", true));
bind(HttpClient.class).toInstance(mockHttpClient);
bind(Executor.class).toInstance(mockExecutor);
bind(MainThread.class).toInstance(mockMainThread);
bind(Headers.class).toInstance(mockHeaders);
install(service(DeleteService.class));
install(service(GetService.class));
install(service(PostService.class));
install(service(PutService.class));
}
});
}
@SuppressWarnings("unchecked") public void testServiceDeleteSimple() throws IOException {
expectLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL);
replayAll();
DeleteService service = injector.getInstance(DeleteService.class);
service.delete(mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServiceDeleteParam() throws IOException {
expectLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL + "id=" + ID);
replayAll();
DeleteService service = injector.getInstance(DeleteService.class);
service.deleteWithParam(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServiceDeleteWithFixedParam() throws IOException {
expectLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL + "filter=merchant&"
+ "id=" + ID);
replayAll();
DeleteService service = injector.getInstance(DeleteService.class);
service.deleteWithFixedParam(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked")
public void testServiceDeleteWithMultipleFixedParam() throws IOException {
expectLifecycle(HttpDelete.class, GET_DELETE_SIMPLE_URL
+ "filter=merchant&name2=value2&"+ "id=" + ID);
replayAll();
DeleteService service = injector.getInstance(DeleteService.class);
service.deleteWithMultipleFixedParams(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServiceDeletePathParam() throws IOException {
expectLifecycle(HttpDelete.class, PATH_URL_PREFIX + ID + "?");
replayAll();
DeleteService service = injector.getInstance(DeleteService.class);
service.deleteWithPathParam(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServiceGetSimple() throws IOException {
expectLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL);
replayAll();
GetService service = injector.getInstance(GetService.class);
service.get(mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServiceGetParam() throws IOException {
expectLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL + "id=" + ID);
replayAll();
GetService service = injector.getInstance(GetService.class);
service.getWithParam(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServiceGetWithFixedParam() throws IOException {
expectLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL + "filter=merchant&"
+ "id=" + ID);
replayAll();
GetService service = injector.getInstance(GetService.class);
service.getWithFixedParam(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked")
public void testServiceGetWithMultipleFixedParams() throws IOException {
expectLifecycle(HttpGet.class, GET_DELETE_SIMPLE_URL
+ "filter=merchant&name2=value2&"+ "id=" + ID);
replayAll();
GetService service = injector.getInstance(GetService.class);
service.getWithMultipleFixedParams(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServiceGetPathParam() throws IOException {
expectLifecycle(HttpGet.class, PATH_URL_PREFIX + ID + "?");
replayAll();
GetService service = injector.getInstance(GetService.class);
service.getWithPathParam(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServicePostSimple() throws IOException {
expectLifecycle(HttpPost.class, BASE_URL);
replayAll();
PostService service = injector.getInstance(PostService.class);
service.post(mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServicePostSimpleClientError() throws IOException {
expectLifecycleClientError(HttpPost.class, BASE_URL);
replayAll();
PostService service = injector.getInstance(PostService.class);
service.post(mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServicePostSimpleServerError() throws IOException {
expectLifecycleServerError(HttpPost.class, BASE_URL);
replayAll();
PostService service = injector.getInstance(PostService.class);
service.post(mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServicePostParam() throws IOException {
expectLifecycle(HttpPost.class, BASE_URL);
replayAll();
PostService service = injector.getInstance(PostService.class);
service.postWithParam(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServicePostPathParam() throws IOException {
expectLifecycle(HttpPost.class, PATH_URL_PREFIX + ID);
replayAll();
PostService service = injector.getInstance(PostService.class);
service.postWithPathParam(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServicePutSimple() throws IOException {
expectLifecycle(HttpPut.class, BASE_URL);
replayAll();
PutService service = injector.getInstance(PutService.class);
service.put(mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServicePutParam() throws IOException {
expectLifecycle(HttpPut.class, BASE_URL);
replayAll();
PutService service = injector.getInstance(PutService.class);
service.putWithParam(ID, mockCallback);
verifyAll();
}
@SuppressWarnings("unchecked") public void testServicePutPathParam() throws IOException {
expectLifecycle(HttpPut.class, PATH_URL_PREFIX + ID);
replayAll();
PutService service = injector.getInstance(PutService.class);
service.putWithPathParam(ID, mockCallback);
verifyAll();
}
// Utility Methods:
private void replayAll() {
replay(mockExecutor, mockHeaders, mockHttpClient, mockMainThread, mockCallback, mockResponse);
}
private void verifyAll() {
verify(mockExecutor, mockHeaders, mockHttpClient, mockMainThread, mockCallback, mockResponse);
}
private <T extends HttpUriRequest> void expectLifecycle(Class<T> requestClass,
String requestUrl) throws IOException {
Response response = expectCallAndResponse(requestClass, requestUrl);
expectResponseCalls(gson.toJson(response), 200);
expectHttpClientExecute();
expectCallbacks(response);
}
private <T extends HttpUriRequest> void expectLifecycleClientError(Class<T> requestClass,
String requestUrl) throws IOException {
Response response = expectCallAndResponse(requestClass, requestUrl);
expectResponseCalls(gson.toJson(response), 409);
expectHttpClientExecute();
expectClientErrorCallbacks(response, 409);
}
private <T extends HttpUriRequest> void expectLifecycleServerError(Class<T> requestClass,
String requestUrl) throws IOException {
Response response = expectCallAndResponse(requestClass, requestUrl);
expectResponseCalls(gson.toJson(response), 501);
expectHttpClientExecute();
expectServerErrorCallbacks(501);
}
private <T extends HttpUriRequest> Response expectCallAndResponse(Class<T> requestClass,
String requestUrl) {
expectExecution(mockExecutor);
expectExecution(mockMainThread); // For preInvoke()
expectExecution(mockMainThread); // For call()
expectSetOnWithRequest(requestClass, requestUrl);
return new Response("some text");
}
@SuppressWarnings("unchecked") private void expectCallbacks(Response response) {
mockCallback.preInvoke();
expectLastCall().once();
mockCallback.call(response);
expectLastCall().once();
}
@SuppressWarnings("unchecked") private void expectClientErrorCallbacks(Response response,
int statusCode) {
mockCallback.preInvoke();
expectLastCall().once();
mockCallback.clientError(response, statusCode);
expectLastCall().once();
}
@SuppressWarnings("unchecked") private void expectServerErrorCallbacks(int statusCode) {
mockCallback.preInvoke();
expectLastCall().once();
mockCallback.serverError(null, statusCode);
expectLastCall().once();
}
private void expectHttpClientExecute() throws IOException {
final Capture<GsonResponseHandler<?>> capture
= new Capture<GsonResponseHandler<?>>();
mockHttpClient.execute(isA(HttpUriRequest.class), capture(capture));
expectLastCall().andAnswer(new IAnswer<Object>() {
@Override public Object answer() throws Throwable {
GsonResponseHandler<?> responseHandler = capture.getValue();
responseHandler.handleResponse(mockResponse);
return null;
}
});
}
private void expectResponseCalls(String jsonToReturn, int statusCode)
throws UnsupportedEncodingException {
expect(mockResponse.getEntity()).andReturn(new StringEntity(jsonToReturn));
expect(mockResponse.getStatusLine()).andReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), statusCode, ""));
}
private <T extends HttpUriRequest> void expectSetOnWithRequest(
final Class<T> expectedRequestClass, final String expectedUri) {
final Capture<HttpMessage> capture = new Capture<HttpMessage>();
final Capture<String> captureMime = new Capture<String>();
mockHeaders.setOn(capture(capture), capture(captureMime));
expectLastCall().andAnswer(new IAnswer<Object>() {
@Override public Object answer() throws Throwable {
T request = expectedRequestClass.cast(capture.getValue());
assertEquals("uri should match expectations", expectedUri, request.getURI().toString());
return null;
}
});
}
private void expectExecution(Executor executor) {
final Capture<Runnable> capture = new Capture<Runnable>();
executor.execute(capture(capture));
expectLastCall().andAnswer(new IAnswer<Object>() {
@Override public Object answer() throws Throwable {
capture.getValue().run();
return null;
}
});
}
private interface DeleteService {
@DELETE(ENTITY) void delete(Callback<Response> callback);
@DELETE(ENTITY) void deleteWithParam(@Named("id") String id,
Callback<Response> callback);
@DELETE(ENTITY) @QueryParam(name="filter", value="merchant")
void deleteWithFixedParam(@Named("id") String id,
Callback<Response> callback);
@DELETE(ENTITY)
@QueryParams({
@QueryParam(name="filter", value="merchant"),
@QueryParam(name="name2", value="value2")
})
void deleteWithMultipleFixedParams(@Named("id") String id,
Callback<Response> callback);
@DELETE(ENTITY_PATH_PARAM) void deleteWithPathParam(@Named("id") String id,
Callback<Response> callback);
}
private interface GetService {
@GET(ENTITY) void get(Callback<Response> callback);
@GET(ENTITY) void getWithParam(@Named("id") String id,
Callback<Response> callback);
@GET(ENTITY) @QueryParam(name="filter", value="merchant")
void getWithFixedParam(@Named("id") String id, Callback<Response> callback);
@GET(ENTITY)
@QueryParams({
@QueryParam(name="filter", value="merchant"),
@QueryParam(name="name2", value="value2")
})
void getWithMultipleFixedParams(@Named("id") String id,
Callback<Response> callback);
@GET(ENTITY_PATH_PARAM) void getWithPathParam(@Named("id") String id,
Callback<Response> callback);
}
private interface PostService {
@POST(ENTITY) void post(Callback<Response> callback);
@POST(ENTITY) void postWithParam(@Named("id") String id,
Callback<Response> callback);
@POST(ENTITY_PATH_PARAM) void postWithPathParam(@Named("id") String id,
Callback<Response> callback);
}
private interface PutService {
@PUT(ENTITY) void put(Callback<Response> callback);
@PUT(ENTITY) void putWithParam(@Named("id") String id,
Callback<Response> callback);
@PUT(ENTITY_PATH_PARAM) void putWithPathParam(@Named("id") String id,
Callback<Response> callback);
}
private static class Response {
final String text;
@SuppressWarnings("unused") public Response() {
this("");
}
public Response(String text) {
this.text = text;
}
@Override public int hashCode() {
return 7;
}
@Override public boolean equals(Object obj) {
return obj instanceof Response && text.equals(((Response)obj).text);
}
}
}
|
package cn.cerc.mis.ado;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
import javax.persistence.Id;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.cerc.db.core.CacheLevelEnum;
import cn.cerc.db.core.DataRow;
import cn.cerc.db.core.EntityKey;
import cn.cerc.db.core.Handle;
import cn.cerc.db.core.IHandle;
import cn.cerc.db.core.ISqlDatabase;
import cn.cerc.db.core.SqlQuery;
import cn.cerc.db.core.SqlServer;
import cn.cerc.db.core.SqlServerType;
import cn.cerc.db.core.SqlServerTypeException;
import cn.cerc.db.core.SqlText;
import cn.cerc.db.mssql.MssqlDatabase;
import cn.cerc.db.mysql.MysqlDatabase;
import cn.cerc.db.redis.JedisFactory;
import cn.cerc.db.sqlite.SqliteDatabase;
import redis.clients.jedis.Jedis;
public class EntityQuery<T> extends Handle implements EntityQueryOne<T>, EntityQueryList<T> {
private static final Logger log = LoggerFactory.getLogger(EntityQuery.class);
private static final ConcurrentHashMap<Class<?>, ISqlDatabase> buff = new ConcurrentHashMap<>();
// redis
private static final String LUA_SCRIPT_MSETEX = "local keysLen = table.getn(KEYS);local argvLen = table.getn(ARGV);"
+ "local idx=1;local argVIdx=1;for idx=1,keysLen,1 do argVIdx=(idx-1)*2+1; "
+ "redis.call('Set',KEYS[idx],ARGV[argVIdx],'EX',ARGV[argVIdx+1]);end return keysLen;";
private final SqlQuery query;
private final Class<T> clazz;
private Field idFieldDefine = null;
private String idFieldCode = null;
public static ISqlDatabase findDatabase(IHandle handle, Class<?> clazz) {
ISqlDatabase database = buff.get(clazz);
if (database == null) {
SqlServer server = clazz.getAnnotation(SqlServer.class);
SqlServerType sqlServerType = (server != null) ? server.type() : SqlServerType.Mysql;
if (sqlServerType == SqlServerType.Mysql)
database = new MysqlDatabase(handle, clazz);
else if (sqlServerType == SqlServerType.Mssql)
database = new MssqlDatabase(handle, clazz);
else if (sqlServerType == SqlServerType.Sqlite)
database = new SqliteDatabase(handle, clazz);
else
throw new SqlServerTypeException();
// if (ServerConfig.isServerDevelop()) {
// EntityKey ekey = clazz.getDeclaredAnnotation(EntityKey.class);
// if (ekey == null || !ekey.virtual())
// database.createTable(false);
buff.put(clazz, database);
}
return database;
}
public static <T> void registerCacheListener(SqlQuery target, Class<T> clazz, boolean writeCacheAtOpen) {
// open
target.onAfterOpen(self -> self.fields().readDefine(clazz));
EntityKey entityKey = clazz.getDeclaredAnnotation(EntityKey.class);
if (entityKey == null || entityKey.cache() == CacheLevelEnum.Disabled)
return;
// openredis
if (writeCacheAtOpen) {
target.onAfterOpen(query -> {
int count = 0;
EntityCache<T> ec1 = EntityCache.Create(query, clazz);
List<String> batchKeys = new ArrayList<>();
List<String> batchValues = new ArrayList<>();
for (DataRow row : query.records()) {
if (++count > EntityCache.MaxRecord)
break;
Object[] keys = ec1.buildKeys(row);
batchKeys.add(EntityCache.buildKey(keys));
batchValues.add(row.json());
batchValues.add("" + entityKey.expire());
if (entityKey.cache() == CacheLevelEnum.RedisAndSession)
SessionCache.set(keys, row);
}
try (Jedis jedis = JedisFactory.getJedis()) {
jedis.evalsha(jedis.scriptLoad(LUA_SCRIPT_MSETEX), batchKeys, batchValues);
}
});
}
// post(insertupdate)redis
target.onAfterPost(row -> {
EntityCache<T> ec2 = EntityCache.Create(target, clazz);
Object[] keys = ec2.buildKeys(row);
try (Jedis jedis = JedisFactory.getJedis()) {
jedis.setex(EntityCache.buildKey(keys), entityKey.expire(), row.json());
if (entityKey.cache() == CacheLevelEnum.RedisAndSession)
SessionCache.set(keys, row);
}
});
// deleteredis
target.onAfterDelete(row -> {
EntityCache<T> ec3 = EntityCache.Create(target, clazz);
Object[] keys = ec3.buildKeys(row);
try (Jedis jedis = JedisFactory.getJedis()) {
jedis.del(EntityCache.buildKey(keys));
if (entityKey.cache() == CacheLevelEnum.RedisAndSession)
SessionCache.del(keys);
}
});
}
public EntityQuery(IHandle handle, Class<T> clazz, boolean writeCacheAtOpen) {
super(handle);
this.clazz = clazz;
ISqlDatabase database = findDatabase(handle, clazz);
SqlServer server = clazz.getAnnotation(SqlServer.class);
query = new SqlQuery(this, server != null ? server.type() : SqlServerType.Mysql);
query.operator().setTable(database.table());
query.operator().setOid(database.oid());
registerCacheListener(query, clazz, writeCacheAtOpen);
}
public EntityQuery<T> open(SqlText sql) {
query.setSql(sql);
query.open();
query.setReadonly(true);
return this;
}
@Override
public T newEntity() {
try {
return clazz.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
}
}
@Override
public void insert(T entity) {
query.setReadonly(false);
try {
query.append();
if (entity instanceof AdoTable)
((AdoTable) entity).insertTimestamp(query);
query.current().loadFromEntity(entity);
query.post();
} finally {
query.setReadonly(true);
}
}
@Override
public void save(int index, T entity) {
query.setRecNo(index + 1);
save(entity);
}
@Override
public void save(T entity) {
query.setReadonly(false);
try {
if (isNewRecord(entity)) {
query.append();
if (entity instanceof AdoTable)
((AdoTable) entity).insertTimestamp(query);
} else {
query.edit();
if (entity instanceof AdoTable)
((AdoTable) entity).updateTimestamp(query);
}
query.current().loadFromEntity(entity);
query.post();
} finally {
query.setReadonly(true);
}
}
@Override
public void deleteAll() {
query.setReadonly(false);
try {
query.first();
while (!query.eof())
query.delete();
} finally {
query.setReadonly(true);
}
}
@Override
public int deleteIf(Predicate<T> predicate) {
Objects.requireNonNull(predicate);
if (query.eof())
return 0;
query.setReadonly(false);
try {
int result = 0;
query.first();
while (!query.eof()) {
T entity = this.query.current().asEntity(clazz);
if (predicate.test(entity)) {
query.delete();
result++;
} else
query.next();
}
return result;
} finally {
query.setReadonly(true);
}
}
@Override
public Optional<T> updateAll(Consumer<T> action) {
Objects.requireNonNull(action);
T entity = null;
for (int i = 0; i < query.size(); i++) {
DataRow row = query.records().get(i);
entity = row.asEntity(this.clazz);
action.accept(entity);
save(i, entity);
}
return Optional.ofNullable(entity);
}
@Override
public Optional<T> updateIf(Predicate<T> predicate) {
Objects.requireNonNull(predicate);
T entity = null;
for (int i = 0; i < query.size(); i++) {
DataRow row = query.records().get(i);
entity = row.asEntity(this.clazz);
if (predicate.test(entity))
save(i, entity);
}
return Optional.ofNullable(entity);
}
@Override
public int size() {
return query.size();
}
@Override
public T get(int index) {
return query.records().get(index).asEntity(clazz);
}
@Override
public Optional<T> get() {
return this.stream().findFirst();
}
@Override
public Stream<T> stream() {
return query.records().stream().map(item -> item.asEntity(clazz));
}
/**
* @param entity Entity
* @return entity
*/
private boolean isNewRecord(T entity) {
DataRow row = query.current();
if (row == null)
return true;
if (idFieldDefine == null) {
Map<String, Field> items = DataRow.getEntityFields(clazz);
for (String fieldCode : items.keySet()) {
Field field = items.get(fieldCode);
Id id = field.getAnnotation(Id.class);
if (id != null) {
idFieldDefine = field;
idFieldCode = fieldCode;
break;
}
}
}
if (idFieldDefine == null)
throw new IllegalArgumentException("id define not exists");
Object idValue = null;
try {
idValue = idFieldDefine.get(entity);
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
if (idValue == null)
return true;
if (row.getValue(idFieldCode).equals(idValue))
return false;
else {
log.warn("id ");
return true;
}
}
@Override
public boolean isEmpty() {
return query.size() == 0;
}
@Override
public boolean isPresent() {
return query.size() > 0;
}
@Override
public boolean delete() {
if (query.size() == 0)
return false;
query.setReadonly(false);
try {
query.delete();
} finally {
query.setReadonly(true);
}
return true;
}
@Override
public Optional<T> update(Consumer<T> action) {
Objects.requireNonNull(action);
T entity = null;
DataRow row = query.current();
if (row != null) {
entity = row.asEntity(this.clazz);
action.accept(entity);
save(entity);
}
return Optional.ofNullable(entity);
}
@Override
public EntityQueryOne<T> ifEmptyInsert(Consumer<T> action) {
if (this.size() == 0) {
T entity = this.newEntity();
action.accept(entity);
this.insert(entity);
}
return this;
}
@Override
public <X extends Throwable> EntityQueryOne<T> ifEmptyThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (query.size() == 0)
throw exceptionSupplier.get();
return this;
}
@Override
public SqlQuery dataSet() {
return query;
}
@Override
public DataRow current() {
return query.current();
}
}
|
package at.ac.tuwien.inso.initializer;
import at.ac.tuwien.inso.entity.*;
import at.ac.tuwien.inso.repository.*;
import at.ac.tuwien.inso.service.student_subject_prefs.StudentSubjectPreferenceStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static java.util.Arrays.asList;
@Component
public class DataInitializer {
@Autowired
private CourseRepository courseRepository;
@Autowired
private UserAccountRepository userAccountRepository;
@Autowired
private UisUserRepository uisUserRepository;
@Autowired
private SubjectRepository subjectRepository;
@Autowired
private SemesterRepository semesterRepository;
@Autowired
private StudyPlanRepository studyPlanRepository;
@Autowired
private SubjectForStudyPlanRepository subjectForStudyPlanRepository;
@Autowired
private TagRepository tagRepository;
@Autowired
private PendingAccountActivationRepository pendingAccountActivationRepository;
@Autowired
private GradeRepository gradeRepository;
@Autowired
private StudentRepository studentRepository;
@Autowired
private FeedbackRepository feedbackRepository;
@Autowired
private StudentSubjectPreferenceStore studentSubjectPreferenceStore;
private List<StudyPlan> studyplans;
private List<Semester> semesters;
private List<Subject> subjects;
private List<Course> courses;
private List<Student> students;
private List<Lecturer> lecturers;
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester1 = new HashMap<String, Subject>() {
{
put("VU Programmkonstruktion", new Subject("VU Programmkonstruktion", new BigDecimal(8.8)));
put("UE Studieneingangsgespräch", new Subject("UE Studieneingangsgespräch", new BigDecimal(0.2)));
put("VU Technische Grundlagen der Informatik", new Subject("VU Technische Grundlagen der Informatik", new BigDecimal(6.0)));
put("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik", new Subject("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik", new BigDecimal(4.0)));
put("UE Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik", new Subject("UE Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik", new BigDecimal(5.0)));
put("VU Formale Modellierung", new Subject("VU Formale Modellierung", new BigDecimal(3.0)));
put("VU Datenmodellierung", new Subject("VU Datenmodellierung", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester2 = new HashMap<String, Subject>() {
{
put("VU Algorithmen und Datenstrukturen 1", new Subject("VU Algorithmen und Datenstrukturen 1", new BigDecimal(6.0)));
put("VU Algorithmen und Datenstrukturen 2", new Subject("VU Algorithmen und Datenstrukturen 2", new BigDecimal(3.0)));
put("VU Einführung in Visual Computing", new Subject("VU Einführung in Visual Computing", new BigDecimal(6.0)));
put("VU Gesellschaftliche Spannungsfelder der Informatik", new Subject("VU Gesellschaftliche Spannungsfelder der Informatik", new BigDecimal(3.0)));
put("VU Basics of Human Computer Interaction", new Subject("VU Basics of Human Computer Interaction", new BigDecimal(3.0)));
put("VO Analysis für Informatik und Wirtschaftsinformatik", new Subject("VO Analysis für Informatik und Wirtschaftsinformatik", new BigDecimal(2.0)));
put("UE Analysis für Informatik und Wirtschaftsinformatik", new Subject("UE Analysis für Informatik und Wirtschaftsinformatik", new BigDecimal(4.0)));
put("VU Objektorientierte Modellierung", new Subject("VU Objektorientierte Modellierung", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester3 = new HashMap<String, Subject>() {
{
put("VU Objektorientierte Programmiertechniken", new Subject("VU Objektorientierte Programmiertechniken", new BigDecimal(3.0)));
put("VU Funktionale Programmierung", new Subject("VU Funktionale Programmierung", new BigDecimal(3.0)));
put("VO Betriebssysteme", new Subject("VO Betriebssysteme", new BigDecimal(2.0)));
put("UE Betriebssysteme", new Subject("UE Betriebssysteme", new BigDecimal(4.0)));
put("VU Introduction to Security", new Subject("VU Introduction to Security", new BigDecimal(3.0)));
put("VU Daten- und Informatikrecht", new Subject("VU Daten- und Informatikrecht", new BigDecimal(3.0)));
put("VU Datenbanksysteme", new Subject("VU Datenbanksysteme", new BigDecimal(6.0)));
put("VO Statistik und Wahrscheinlichkeitstheorie", new Subject("VO Statistik und Wahrscheinlichkeitstheorie", new BigDecimal(3.0)));
put("UE Statistik und Wahrscheinlichkeitstheorie", new Subject("UE Statistik und Wahrscheinlichkeitstheorie", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester4 = new HashMap<String, Subject>() {
{
put("VU Einführung in die Künstliche Intelligenz", new Subject("VU Einführung in die Künstliche Intelligenz", new BigDecimal(3.0)));
put("VU Theoretische Informatik und Logik", new Subject("VU Theoretische Informatik und Logik", new BigDecimal(6.0)));
put("VO Software Engineering und Projektmanagement", new Subject("VO Software Engineering und Projektmanagement", new BigDecimal(3.0)));
put("PR Software Engineering und Projektmanagement", new Subject("PR Software Engineering und Projektmanagement", new BigDecimal(6.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester5 = new HashMap<String, Subject>() {
{
put("VO Verteilte Systeme", new Subject("VO Verteilte Systeme", new BigDecimal(3.0)));
put("UE Verteilte Systeme", new Subject("UE Verteilte Systeme", new BigDecimal(3.0)));
put("VU Gesellschaftswissenschaftliche Grundlagen der Informatik", new Subject("VU Gesellschaftswissenschaftliche Grundlagen der Informatik", new BigDecimal(3.0)));
put("VU Interface and Interaction Design", new Subject("VU Interface and Interaction Design", new BigDecimal(3.0)));
put("VU Einführung in wissensbasierte Systeme", new Subject("VU Einführung in wissensbasierte Systeme", new BigDecimal(3.0)));
put("SE Wissenschaftliches Arbeiten", new Subject("SE Wissenschaftliches Arbeiten", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester6 = new HashMap<String, Subject>() {
{
put("PR Bachelorarbeit für Informatik und Wirtschaftsinformatik", new Subject("PR Bachelorarbeit für Informatik und Wirtschaftsinformatik", new BigDecimal(10.0)));
}
};
private Map<String, Subject> subjectsOptionalBachelorSoftwareAndInformationEngineering = new HashMap<String, Subject>() {
{
put("VU Propädeutikum für Informatik", new Subject("VU Propädeutikum für Informatik", new BigDecimal(6.0)));
put("VO Deklaratives Problemlösen", new Subject("VO Deklaratives Problemlösen", new BigDecimal(3.0)));
put("UE Deklaratives Problemlösen", new Subject("UE Deklaratives Problemlösen", new BigDecimal(3.0)));
put("VU Logikprogrammierung und Constraints", new Subject("VU Logikprogrammierung und Constraints", new BigDecimal(6.0)));
put("VO Abstrakte Maschinen", new Subject("VO Abstrakte Maschinen", new BigDecimal(3.0)));
put("UE Abstrakte Maschinen", new Subject("UE Abstrakte Maschinen", new BigDecimal(3.0)));
put("VU Microcontroller", new Subject("VU Microcontroller", new BigDecimal(7.0)));
put("UE Programmierung von Betriebssystemen", new Subject("UE Programmierung von Betriebssystemen", new BigDecimal(3.0)));
put("VU Übersetzerbau", new Subject("VU Übersetzerbau", new BigDecimal(6.0)));
put("VO Echtzeitsysteme", new Subject("VO Echtzeitsysteme", new BigDecimal(2.0)));
put("VU Dependable Systems", new Subject("VU Dependable Systems", new BigDecimal(4.0)));
put("VU Internet Security", new Subject("VU Internet Security", new BigDecimal(3.0)));
put("VU Internet Security", new Subject("VU Internet Security", new BigDecimal(3.0)));
put("VU Privacy Enhancing Technology", new Subject("VU Privacy Enhancing Technology", new BigDecimal(3.0)));
put("UE Daten- und Informatikrecht", new Subject("UE Daten- und Informatikrecht", new BigDecimal(3.0)));
put("VU Vertrags- und Haftungsrecht", new Subject("VU Vertrags- und Haftungsrecht", new BigDecimal(3.0)));
put("VU Semistrukturierte Daten", new Subject("VU Semistrukturierte Daten", new BigDecimal(3.0)));
put("VU Web Engineering", new Subject("VU Web Engineering", new BigDecimal(4.5)));
put("VU Computerstatistik", new Subject("VU Computerstatistik", new BigDecimal(3.0)));
put("VU Datenanalyse", new Subject("VU Datenanalyse", new BigDecimal(3.0)));
put("VU Statistical Computing", new Subject("VU Statistical Computing", new BigDecimal(3.0)));
put("VO Logik für Wissensrepräsentation", new Subject("VO Logik für Wissensrepräsentation", new BigDecimal(3.0)));
put("UE Logik für Wissensrepräsentation", new Subject("UE Logik für Wissensrepräsentation", new BigDecimal(3.0)));
put("VO Computernumerik", new Subject("VO Computernumerik", new BigDecimal(3.0)));
put("UE Computernumerik", new Subject("UE Computernumerik", new BigDecimal(1.5)));
put("VO Multivariate Statistik", new Subject("VO Multivariate Statistik", new BigDecimal(4.5)));
put("UE Multivariate Statistik", new Subject("UE Multivariate Statistik", new BigDecimal(1.5)));
put("VU Statistische Simulation und computerintensive Methoden", new Subject("VU Statistische Simulation und computerintensive Methoden", new BigDecimal(3.0)));
put("VU Argumentieren und Beweisen", new Subject("VU Argumentieren und Beweisen", new BigDecimal(6.0)));
put("VU Programm- und Systemverifikation", new Subject("VU Programm- und Systemverifikation", new BigDecimal(6.0)));
put("VU Softwareprojekt-Beobachtung und -Controlling", new Subject("VU Softwareprojekt-Beobachtung und -Controlling", new BigDecimal(6.0)));
put("VU Software-Qualitätssicherung", new Subject("VU Software-Qualitätssicherung", new BigDecimal(6.0)));
put("VU Usability Engineering", new Subject("VU Usability Engineering", new BigDecimal(3.0)));
put("SE Coaching als Führungsinstrument 2", new Subject("SE Coaching als Führungsinstrument 2", new BigDecimal(3.0)));
put("SE Didaktik in der Informatik", new Subject("SE Didaktik in der Informatik", new BigDecimal(3.0)));
put("VO EDV-Vertragsrecht", new Subject("VO EDV-Vertragsrecht", new BigDecimal(1.5)));
put("VO Einführung in Technik und Gesellschaft", new Subject("VO Einführung in Technik und Gesellschaft", new BigDecimal(3.0)));
put("SE Folgenabschätzung von Informationstechnologien", new Subject("SE Folgenabschätzung von Informationstechnologien", new BigDecimal(3.0)));
put("VU Forschungsmethoden", new Subject("VU Forschungsmethoden", new BigDecimal(3.0)));
put("VU Kommunikation und Moderation", new Subject("VU Kommunikation und Moderation", new BigDecimal(3.0)));
put("VU Kooperatives Arbeiten", new Subject("VU Kooperatives Arbeiten", new BigDecimal(3.0)));
put("SE Rechtsinformationsrecherche im Internet", new Subject("SE Rechtsinformationsrecherche im Internet", new BigDecimal(3.0)));
put("VU Softskills für TechnikerInnen", new Subject("VU Softskills für TechnikerInnen", new BigDecimal(3.0)));
put("VU Techniksoziologie und Technikpsychologie", new Subject("VU Techniksoziologie und Technikpsychologie", new BigDecimal(3.0)));
put("VO Theorie und Praxis der Gruppenarbeit", new Subject("VO Theorie und Praxis der Gruppenarbeit", new BigDecimal(3.0)));
put("SE Wissenschaftliche Methodik", new Subject("SE Wissenschaftliche Methodik", new BigDecimal(3.0)));
put("SE Scientific Presentation and Communication", new Subject("SE Scientific Presentation and Communication", new BigDecimal(3.0)));
put("PV Privatissimum aus Fachdidaktik Informatik", new Subject("PV Privatissimum aus Fachdidaktik Informatik", new BigDecimal(4.0)));
put("VU Präsentation und Moderation", new Subject("VU Präsentation und Moderation", new BigDecimal(3.0)));
}
};
private Map<String, Subject> subjectsFreeChoiceInformatics = new HashMap<String, Subject>() {{
put("VU Pilots in Mobile Interaction: User-centered Interaction Research and Evaluation", new Subject("VU Pilots in Mobile Interaction: User-centered Interaction Research and Evaluation", new BigDecimal(3.0)));
put("VU Robotik für RoboCup", new Subject("VU Robotik für RoboCup", new BigDecimal(6.0)));
put("KO Reflections on ICTs and Society", new Subject("KO Reflections on ICTs and Society", new BigDecimal(6.0)));
put("VU Science of Information 1: Transdisciplinary Foundations of Informatics", new Subject("VU Science of Information 1: Transdisciplinary Foundations of Informatics", new BigDecimal(3.0)));
put("VU Parallel Computing", new Subject("VU Parallel Computing", new BigDecimal(6.0)));
put("PR Praktikum aus IT-Security", new Subject("PR Praktikum aus IT-Security", new BigDecimal(6.0)));
put("SE Formale Semantik natürlicher Sprache", new Subject("SE Formale Semantik natürlicher Sprache", new BigDecimal(3.0)));
put("VO Ausgewählte Kapitel der Technischen Informatik", new Subject("VO Ausgewählte Kapitel der Technischen Informatik", new BigDecimal(3.0)));
put("SE Seminar für DiplomandInnen", new Subject("SE Seminar für DiplomandInnen", new BigDecimal(2.0)));
put("SE Computer Vision Seminar für DiplomandInnen", new Subject("SE Computer Vision Seminar für DiplomandInnen", new BigDecimal(2.0)));
put("VU Softwaretechische Konzepte und Infrastrukturtechnologien zur Identifikation von Objekten und Geräten: RFID, Smartcards, NFC und Mobile Phones", new Subject("VU Softwaretechische Konzepte und Infrastrukturtechnologien zur Identifikation von Objekten und Geräten: RFID, Smartcards, NFC und Mobile Phones", new BigDecimal(3.0)));
put("VU Advanced Services Engineering", new Subject("VU Advanced Services Engineering", new BigDecimal(3.0)));
put("SE Forschungsseminar für DiplomandInnen", new Subject("SE Forschungsseminar für DiplomandInnen", new BigDecimal(3.0)));
put("VO Finanzmärkte, Finanzintermediation und Kapitalanlage", new Subject("VO Finanzmärkte, Finanzintermediation und Kapitalanlage", new BigDecimal(3.5)));
put("VU Methodisches, industrielles Software-Engineering mit Funktionalen Sprachen am Fallbeispiel Haskell", new Subject("VU Methodisches, industrielles Software-Engineering mit Funktionalen Sprachen am Fallbeispiel Haskell", new BigDecimal(3.0)));
put("VU IT Governance", new Subject("VU IT Governance", new BigDecimal(3.0)));
put("VU Current Trends in Computer Science", new Subject("VU Current Trends in Computer Science", new BigDecimal(3.0)));
put("VU Programmierung von Strategie-Spielen", new Subject("VU Programmierung von Strategie-Spielen", new BigDecimal(3.0)));
put("VU Medienanalyse und Medienreflexion", new Subject("VU Medienanalyse und Medienreflexion", new BigDecimal(3.0)));
put("EX Exkursion", new Subject("EX Exkursion", new BigDecimal(3.0)));
put("VU Privacy Enhancing Technologies", new Subject("VU Privacy Enhancing Technologies", new BigDecimal(3.0)));
put("VU Theoretische Informatik und Logik für CI", new Subject("VU Theoretische Informatik und Logik für CI", new BigDecimal(6.0)));
put("SE Theorie und Praxis der Evaluierung von innovativen User Interfaces", new Subject("SE Theorie und Praxis der Evaluierung von innovativen User Interfaces", new BigDecimal(3.0)));
put("VU Brückenkurs Programmierung für Studienanfängerinnen", new Subject("VU Brückenkurs Programmierung für Studienanfängerinnen", new BigDecimal(3.0)));
put("VU Mobile (App) Software Engineering", new Subject("VU Mobile (App) Software Engineering", new BigDecimal(3.0)));
put("VU Runtime Verification", new Subject("VU Runtime Verification", new BigDecimal(3.0)));
put("VU 2D and 3D Image Registration", new Subject("VU 2D and 3D Image Registration", new BigDecimal(3.0)));
put("VU Mobile Robotik", new Subject("VU Mobile Robotik", new BigDecimal(4.5)));
put("SE Critical Algorithm Studies", new Subject("SE Critical Algorithm Studies", new BigDecimal(3.0)));
put("VU Brückenkurs Programmierung für Studienanfänger", new Subject("", new BigDecimal(0.0)));
}};
private Map<String, Subject> subjectsBachelorSoftwareAndInformationEngineering;
private Map<String, Course> coursesBachelorSoftwareAndInformationEngineering;
private Map<String, Tag> tags = new HashMap<String, Tag>() {{
put("Programmieren", new Tag("Programmieren"));
put("Java", new Tag("Java"));
put("Debug", new Tag("Debug"));
put("Rekursion", new Tag("Rekursion"));
put("Boolsche Algebra", new Tag("Boolsche Algebra"));
put("RISC", new Tag("RISC"));
put("CISC", new Tag("CISC"));
put("Pipelining", new Tag("Pipelining"));
put("ROM", new Tag("ROM"));
put("PROM/EPROM", new Tag("PROM/EPROM"));
put("2 Complement", new Tag("2 Complement"));
put("1 Complement", new Tag("1 Complement"));
put("Gatterschaltungen", new Tag("Gatterschaltungen"));
put("Befehlssatz", new Tag("Befehlssatz"));
put("Digital", new Tag("Digital"));
put("Zahlentheorie", new Tag("Zahlentheorie"));
put("Aussagenlogik", new Tag("Aussagenlogik"));
put("Mengenlehre", new Tag("Mengenlehre"));
put("Kombinatorik,", new Tag("Kombinatorik,"));
put("Differenzengleichungen", new Tag("Differenzengleichungen"));
put("Graphentheorie", new Tag("Graphentheorie"));
put("Algebraische Strukturen", new Tag("Algebraische Strukturen"));
put("Lineare Algebra", new Tag("Lineare Algebra"));
put("Codierungstheorie", new Tag("Codierungstheorie"));
put("UE", new Tag("UE"));
put("VU", new Tag("VU"));
put("VO", new Tag("VO"));
put("Automaten", new Tag("Automaten"));
put("reguläre Ausdrücke", new Tag("reguläre Ausdrücke"));
put("Grammatiken", new Tag("Grammatiken"));
put("Petri-Netze", new Tag("Petri-Netze"));
put("Prädikatenlogik", new Tag("Prädikatenlogik"));
put("EER", new Tag("EER"));
put("Relationenmodel", new Tag("Relationenmodel"));
put("Domänenkalkül", new Tag("Domänenkalkül"));
put("Datenbanksprachen", new Tag("Datenbanksprachen"));
put("Relationale Entwurfstheorie", new Tag("Relationale Entwurfstheorie"));
put("Normalformen", new Tag("Normalformen"));
put("Datenintegrität", new Tag("Datenintegrität"));
put("SQL", new Tag("SQL"));
put("JDBC", new Tag("JDBC"));
put("DBMS", new Tag("DBMS"));
put("Algorithmen", new Tag("Algorithmen"));
put("Datenstrukturen", new Tag("Datenstrukturen"));
put("Visual Computing", new Tag("Visual Computing"));
put("MATLAB", new Tag("MATLAB"));
put("Fourier", new Tag("Fourier"));
put("Analysis", new Tag("Analysis"));
put("Langweilig", new Tag("Langweilig"));
put("Theorie", new Tag("Theorie"));
put("Praxis", new Tag("Praxis"));
put("Gesellschaft", new Tag("Gesellschaft"));
put("Human Computer Interaction", new Tag("Human Computer Interaction"));
put("Laplace", new Tag("Laplace"));
put("Laplace", new Tag("Laplace"));
put("Folgen", new Tag("Folgen"));
put("Reihen", new Tag("Reihen"));
put("Stetigkeit", new Tag("Stetigkeit"));
put("Grenzwerte", new Tag("Grenzwerte"));
put("Nullstellen", new Tag("Nullstellen"));
put("Differentialrechnung", new Tag("Differentialrechnung"));
put("Funktionen", new Tag("Funktionen"));
put("Integralrechnung", new Tag("Integralrechnung"));
put("Objektorientiert", new Tag("Objektorientiert"));
put("UML", new Tag("UML"));
put("Grundlagen", new Tag("Grundlagen"));
put("Hardware", new Tag("Hardware"));
put("Software", new Tag("Software"));
put("Computer Science", new Tag("Computer Science"));
put("Mathe", new Tag("Mathe"));
put("Spaß", new Tag("Spaß"));
put("Einfach", new Tag("Einfach"));
put("Diffizil", new Tag("Diffizil"));
put("Programmiersprachen", new Tag("Programmiersprachen"));
put("Gruppenarbeit", new Tag("Gruppenarbeit"));
put("Abstraktion", new Tag("Abstraktion"));
put("Teamfaehigkeit", new Tag("Teamfaehigkeit"));
put("Generizität", new Tag("Generizität"));
put("Haskell", new Tag("Haskell"));
put("Funktional", new Tag("Funktional"));
put("Lambda-Kalkuel", new Tag("Lambda-Kalkuel"));
put("Thread", new Tag("Thread"));
put("Prozes", new Tag("Prozes"));
put("Synchronisation", new Tag("Synchronisation"));
put("Betriebssystem", new Tag("Betriebssystem"));
put("C", new Tag("C"));
put("Scheduling", new Tag("Scheduling"));
put("Multithreading", new Tag("Multithreading"));
put("Deadlock", new Tag("Deadlock"));
put("Semaphore", new Tag("Semaphore"));
put("Sequencer", new Tag("Sequencer"));
put("Eventcounts", new Tag("Eventcounts"));
put("Producer-Consumer", new Tag("Producer-Consumer"));
put("Speicherverwaltung", new Tag("Speicherverwaltung"));
put("Filesysteme", new Tag("Filesysteme"));
put("Netzwerke", new Tag("Netzwerke"));
put("Security", new Tag("Security"));
put("Eventcounts", new Tag("Eventcounts"));
put("Social engineering", new Tag("Social engineering"));
put("Physical Break-Ins", new Tag("Physical Break-Ins"));
put("Dumpster Diving", new Tag("Dumpster Diving"));
put("Password Cracking", new Tag("Password Cracking"));
put("Session Hijacking", new Tag("Session Hijacking"));
put("Spoofing", new Tag("Spoofing"));
put("Viruses", new Tag("Viruses"));
put("Worms", new Tag("Worms"));
put("Trojan Horses", new Tag("Trojan Horses"));
put("Phishing", new Tag("Phishing"));
put("Encryption", new Tag("Encryption"));
put("Spyware", new Tag("Spyware"));
put("Phishing", new Tag("Phishing"));
put("Spyware", new Tag("Spyware"));
put("Adware", new Tag("Adware"));
put("Cryptography", new Tag("Cryptography"));
put("Risk Analysis", new Tag("Risk Analysis"));
put("Recht", new Tag("Recht"));
put("Wirtschaft", new Tag("Wirtschaft"));
put("Technik", new Tag("Technik"));
put("Statistik", new Tag("Statistik"));
put("Wahrscheinlichkeitstheorie", new Tag("Wahrscheinlichkeitstheorie"));
put("Verteilung", new Tag("Verteilung"));
put("Histogramm", new Tag("Histogramm"));
put("Grundlagen der Bayes'schen", new Tag("Grundlagen der Bayes'schen"));
put("Wahrscheinlichkeitsraeume", new Tag("Wahrscheinlichkeitsraeume"));
put("Stochastik", new Tag("Stochastik"));
put("Gesetz der großen Zahlen", new Tag("Gesetz der großen Zahlen"));
put("Künstliche Intelligenz", new Tag("Künstliche Intelligenz"));
put("Projektmanagement", new Tag("Projektmanagement"));
put("Planning", new Tag("Planning"));
put("Testing", new Tag("Testing"));
put("Softwarequalitätssicherung", new Tag("Softwarequalitätssicherung"));
put("Risikomanagement", new Tag("Risikomanagement"));
put("Qualitätsmanagement", new Tag("Qualitätsmanagement"));
put("Projektmarketing", new Tag("Projektmarketing"));
put("Risikomanagement", new Tag("Risikomanagement"));
put("Sprint", new Tag("Sprint"));
put("SCRUM", new Tag("SCRUM"));
put("PR", new Tag("PR"));
}};
private Map<String, Student> studentMap = new HashMap<String, Student>() {
{
put("Caroline Black", new Student("s1123960", "Caroline Black", "caroline.black@uis.at", new UserAccount("student", "pass", Role.STUDENT)));
put("Emma Dowd", new Student("s1127157", "Emma Dowd", "emma.dowd@gmail.com", new UserAccount("emma", "pass", Role.STUDENT)));
put("John Terry", new Student("s1126441", "John Terry", "john.terry@uis.at", new UserAccount("john", "pass", Role.STUDENT)));
put("Joan Watson", new Student("s0227157", "Joan Watson", "joan.watson@uit.at"));
put("James Bond", new Student("s1527199", "James Bond", "jamesbond_007@yahoo.com"));
put("Trevor Bond", new Student("s0445157", "Trevor Bond", "trevor@uis.at"));
}
};
private Map<String, Lecturer> lecturerMap = new HashMap<String, Lecturer>() {
{
put("Carol Sanderson", new Lecturer("l0100010", "Carol Sanderson", "carol@uis.at"));
put("Una Walker", new Lecturer("l0100011", "Una Walker", "una.walker@uis.at", new UserAccount("lecturer", "pass", Role.LECTURER)));
put("Connor MacLeod", new Lecturer("l0203019", "Connor MacLeod", "connor@gmail.com"));
put("Eric Wilkins", new Lecturer("l1100010", "Eric Wilkins", "e1234567@tuwien.ac.at", new UserAccount("eric", "pass", Role.LECTURER)));
put("Benjamin Piper", new Lecturer("l9123410", "Benjamin Piper", "ben@uis.at", new UserAccount("ben", "pass", Role.LECTURER)));
}
};
@Transactional
public void initialize() {
userAccountRepository.save(new UserAccount("admin", "pass", Role.ADMIN));
createTags();
createSubjects();
createSemesters();
createCourses();
createStudyPlans();
createUsers();
registerStudentsToStudyPlans();
addPreconditionsToSubjects();
registerSubjectsToLecturers();
addTagsToCourses();
addSubjectsToStudyPlans();
registerCoursesToStudents();
giveGrades();
giveFeedback();
}
private void createTags() {
tagRepository.save(tags.values());
}
private void createSubjects() {
createSubjectsBachelorSoftwareAndInformationEngineering();
Iterable<Subject> subjects = subjectRepository.save(subjectsBachelorSoftwareAndInformationEngineering.values());
this.subjects = StreamSupport.stream(subjects.spliterator(), false).collect(Collectors.toList());
}
private void createSubjectsBachelorSoftwareAndInformationEngineering() {
subjectsBachelorSoftwareAndInformationEngineering = new HashMap<>();
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester1);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester2);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester3);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester4);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester5);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester6);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsOptionalBachelorSoftwareAndInformationEngineering);
subjectsBachelorSoftwareAndInformationEngineering.putAll(subjectsFreeChoiceInformatics);
}
private void createSemesters() {
Iterable<Semester> semesters = semesterRepository.save(asList(
new Semester(2016, SemesterType.SummerSemester),
new Semester(2016, SemesterType.WinterSemester)
));
this.semesters = StreamSupport.stream(semesters.spliterator(), false).collect(Collectors.toList());
}
private void createCourses() {
createCoursesBachelorSoftwareAndInformationEngineering();
Iterable<Course> courses = courseRepository.save(coursesBachelorSoftwareAndInformationEngineering.values());
this.courses = StreamSupport.stream(courses.spliterator(), false).collect(Collectors.toList());
}
private void createCoursesBachelorSoftwareAndInformationEngineering() {
coursesBachelorSoftwareAndInformationEngineering = new HashMap<>();
for (String subjectName : subjectsBachelorSoftwareAndInformationEngineering.keySet()) {
coursesBachelorSoftwareAndInformationEngineering.put(
subjectName,
new Course(subjectsBachelorSoftwareAndInformationEngineering.get(subjectName), semesters.get(1)).setStudentLimits(20)
);
}
}
private void createStudyPlans() {
Iterable<StudyPlan> studyplans = studyPlanRepository.save(asList(
new StudyPlan("Bachelor Software and Information Engineering", new EctsDistribution(new BigDecimal(90), new BigDecimal(60), new BigDecimal(30))),
new StudyPlan("Master Business Informatics", new EctsDistribution(new BigDecimal(30), new BigDecimal(70), new BigDecimal(20))),
new StudyPlan("Master Computational Intelligence", new EctsDistribution(new BigDecimal(60), new BigDecimal(30), new BigDecimal(30))),
new StudyPlan("Master Visual Computing", new EctsDistribution(new BigDecimal(60), new BigDecimal(30), new BigDecimal(30))),
new StudyPlan("Master Medical Informatics", new EctsDistribution(new BigDecimal(60), new BigDecimal(30), new BigDecimal(30)), false),
new StudyPlan("Master Computer Science", new EctsDistribution(new BigDecimal(60), new BigDecimal(30), new BigDecimal(30)))
));
this.studyplans = StreamSupport.stream(studyplans.spliterator(), false).collect(Collectors.toList());
}
private void createUsers() {
pendingAccountActivationRepository.save(
new PendingAccountActivation("test", new Student("test", "Test User", "test-user@uis.at"))
);
List<UisUser> usersList = new ArrayList<>(studentMap.values());
usersList.addAll(lecturerMap.values());
Iterable<UisUser> users = uisUserRepository.save(usersList);
students = StreamSupport.stream(users.spliterator(), false)
.filter(it -> it instanceof Student)
.map(it -> (Student) it)
.collect(Collectors.toList());
lecturers = StreamSupport.stream(users.spliterator(), false)
.filter(it -> it instanceof Lecturer)
.map(it -> (Lecturer) it)
.collect(Collectors.toList());
}
private void registerStudentsToStudyPlans() {
studentMap.get("John Terry").addStudyplans(new StudyPlanRegistration(studyplans.get(0), semesters.get(1)));
studentMap.get("Caroline Black").addStudyplans(new StudyPlanRegistration(studyplans.get(1), semesters.get(1)));
studentMap.get("Emma Dowd").addStudyplans(new StudyPlanRegistration(studyplans.get(2), semesters.get(0)));
studentMap.get("Joan Watson").addStudyplans(new StudyPlanRegistration(studyplans.get(3), semesters.get(1)));
studentMap.get("James Bond").addStudyplans(new StudyPlanRegistration(studyplans.get(4), semesters.get(1)));
studentMap.get("James Bond").addStudyplans(new StudyPlanRegistration(studyplans.get(5), semesters.get(0)));
studentMap.get("Trevor Bond").addStudyplans(new StudyPlanRegistration(studyplans.get(1), semesters.get(1)));
}
private void addPreconditionsToSubjects() {
subjects.get(2).addRequiredSubjects(subjects.get(1));
}
private void registerSubjectsToLecturers() {
subjectsBachelorSoftwareAndInformationEngineering.get("UE Studieneingangsgespräch").addLecturers(
lecturerMap.get("Carol Sanderson")
);
subjects.get(0).addLecturers(lecturers.get(3));
subjects.get(1).addLecturers(lecturers.get(3));
subjects.get(2).addLecturers(lecturers.get(3), lecturers.get(4));
subjectRepository.save(subjects);
Subject s = subjectsBachelorSoftwareAndInformationEngineering
.get("VU Technische Grundlagen der Informatik");
s.addLecturers(lecturers.get(3));
subjectRepository.save(s);
s = subjectsBachelorSoftwareAndInformationEngineering
.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik");
s.addLecturers(lecturers.get(3));
subjectRepository.save(s);
}
private void addTagsToCourses() {
addTagsToBachelorSoftwareAndInformationEngineeringCourses();
courseRepository.save(coursesBachelorSoftwareAndInformationEngineering.values());
}
private void addTagsToBachelorSoftwareAndInformationEngineeringCourses() {
addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester1();
addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester2();
addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester3();
addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester4();
}
private void addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester1() {
coursesBachelorSoftwareAndInformationEngineering.get("VU Programmkonstruktion").addTags(
tags.get("VU"), tags.get("Programmieren"), tags.get("Java"), tags.get("Debug"),
tags.get("Rekursion"), tags.get("Software"), tags.get("Einfach"), tags.get("Grundlagen"),
tags.get("Objektorientiert"), tags.get("Generizität")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik").addTags(
tags.get("VU"), tags.get("Boolsche Algebra"), tags.get("RISC"), tags.get("CISC"), tags.get("Pipelining"),
tags.get("ROM"), tags.get("PROM/EPROM"), tags.get("2 Complement"), tags.get("1 Complement"),
tags.get("Gatterschaltungen"), tags.get("Befehlssatz"), tags.get("Digital"), tags.get("Diffizil"), tags.get("Grundlagen"),
tags.get("Hardware")
);
coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik").addTags(
tags.get("VO"), tags.get("Zahlentheorie"), tags.get("Aussagenlogik"), tags.get("Mengenlehre"),
tags.get("Mathe"), tags.get("Kombinatorik"), tags.get("Differenzengleichungen"),
tags.get("Graphentheorie"), tags.get("Algebraische Strukturen"), tags.get("Lineare Algebra"),
tags.get("Codierungstheorie"), tags.get("Einfach"), tags.get("Funktionen"), tags.get("Grundlagen")
);
coursesBachelorSoftwareAndInformationEngineering.get("UE Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik").addTags(
tags.get("UE"), tags.get("Zahlentheorie"), tags.get("Aussagenlogik"), tags.get("Mengenlehre"),
tags.get("Mathe"), tags.get("Kombinatorik"), tags.get("Differenzengleichungen"),
tags.get("Graphentheorie"), tags.get("Algebraische Strukturen"), tags.get("Lineare Algebra"),
tags.get("Codierungstheorie"), tags.get("Einfach"), tags.get("Funktionen"), tags.get("Grundlagen")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Formale Modellierung").addTags(
tags.get("VU"), tags.get("Automaten"), tags.get("reguläre Ausdrücke"), tags.get("formale Grammatiken"),
tags.get("Aussagenlogik"), tags.get("Petri-Netze"), tags.get("Prädikatenlogik"), tags.get("Einfach"), tags.get("Grundlagen"),
tags.get("Lambda-Kalkuel")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Datenmodellierung").addTags(
tags.get("VU"), tags.get("EER"), tags.get("Relationenmodel"), tags.get("Domänenkalkül"),
tags.get("Datenbanksprachen"), tags.get("Normalformen"), tags.get("Relationale Entwurfstheorie"),
tags.get("Datenintegrität"), tags.get("Einfach"), tags.get("SQL"), tags.get("Grundlagen")
);
}
private void addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester2() {
coursesBachelorSoftwareAndInformationEngineering.get("VU Algorithmen und Datenstrukturen 1").addTags(
tags.get("VU"), tags.get("Datenstrukturen"), tags.get("Algorithmen"), tags.get("Java"),
tags.get("Programmieren"), tags.get("Debug"), tags.get("Rekursion"),
tags.get("Software"), tags.get("Graphentheorie"), tags.get("Einfach")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Algorithmen und Datenstrukturen 2").addTags(
tags.get("VU"), tags.get("Datenstrukturen"), tags.get("Algorithmen"), tags.get("Java"),
tags.get("Programmieren"), tags.get("Debug"), tags.get("Rekursion"),
tags.get("Software"), tags.get("Graphentheorie"), tags.get("Diffizil")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Einführung in Visual Computing").addTags(
tags.get("VU"), tags.get("Visual Computing"), tags.get("MATLAB"), tags.get("Mathe"),
tags.get("Fourier"), tags.get("Analysis"), tags.get("Diffizil"), tags.get("Programmieren"),
tags.get("Grundlagen")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Gesellschaftliche Spannungsfelder der Informatik").addTags(
tags.get("VU"), tags.get("Langweilig"), tags.get("Theorie"), tags.get("Einfach"),
tags.get("Gesellschaft")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Basics of Human Computer Interaction").addTags(
tags.get("VU"), tags.get("Human Computer Interaction"), tags.get("Einfach"), tags.get("Grundlagen")
);
coursesBachelorSoftwareAndInformationEngineering.get("VO Analysis für Informatik und Wirtschaftsinformatik").addTags(
tags.get("VU"), tags.get("Mathe"), tags.get("Analysis"), tags.get("Fourier"),
tags.get("Laplace"), tags.get("Diffizil"), tags.get("Folgen"),
tags.get("Reihen"), tags.get("Stetigkeit"), tags.get("Grenzwerte"),
tags.get("Nullstellen"), tags.get("Differentialrechnung"),
tags.get("Integralrechnung"), tags.get("Funktionen")
);
coursesBachelorSoftwareAndInformationEngineering.get("UE Analysis für Informatik und Wirtschaftsinformatik").addTags(
tags.get("UE"), tags.get("Mathe"), tags.get("Analysis"), tags.get("Fourier"),
tags.get("Laplace"), tags.get("Diffizil"), tags.get("Folgen"),
tags.get("Reihen"), tags.get("Stetigkeit"), tags.get("Grenzwerte"),
tags.get("Nullstellen"), tags.get("Differentialrechnung"),
tags.get("Integralrechnung"), tags.get("Funktionen")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Objektorientierte Modellierung").addTags(
tags.get("VU"), tags.get("Objektorientiert"), tags.get("UML"), tags.get("Grundlagen"),
tags.get("Einfach")
);
}
private void addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester3() {
coursesBachelorSoftwareAndInformationEngineering.get("VU Objektorientierte Programmiertechniken").addTags(
tags.get("VU"), tags.get("Objektorientiert"), tags.get("Programmiersprachen"),
tags.get("Programmieren"), tags.get("Java"),
tags.get("Debug"), tags.get("Software"), tags.get("Teamfaehigkeit"),
tags.get("Gruppenarbeit"), tags.get("Abstraktion"), tags.get("Diffizil"),
tags.get("Generizität"), tags.get("Theorie"), tags.get("Praxis")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Funktionale Programmierung").addTags(
tags.get("VU"), tags.get("Programmiersprachen"), tags.get("Programmieren"),
tags.get("Diffizil"), tags.get("Haskell"), tags.get("Debug"),
tags.get("Software"), tags.get("Teamfaehigkeit"),
tags.get("Gruppenarbeit"), tags.get("Haskell"), tags.get("Diffizil"),
tags.get("Funktional"), tags.get("Theorie"), tags.get("Praxis"),
tags.get("Grundlagen"), tags.get("Rekursion"), tags.get("Funktionen"),
tags.get("Lambda-Kalkuel")
);
coursesBachelorSoftwareAndInformationEngineering.get("VO Betriebssysteme").addTags(
tags.get("V0"), tags.get("Theorie"), tags.get("Thread"), tags.get("Prozess"),
tags.get("Synchronisation"), tags.get("Grundlagen"), tags.get("Betriebssystem"),
tags.get("Scheduling"), tags.get("Multithreading"), tags.get("Deadlock"),
tags.get("Datenstrukturen"), tags.get("Semaphore"), tags.get("Diffizil"),
tags.get("Sequencer"), tags.get("Eventcounts"), tags.get("Producer-Consumer"),
tags.get("Speicherverwaltung"), tags.get("Filesysteme"), tags.get("Netzwerk"),
tags.get("Security"), tags.get("Software"), tags.get("C"), tags.get("Client-Server")
);
coursesBachelorSoftwareAndInformationEngineering.get("UE Betriebssysteme").addTags(
tags.get("UE"), tags.get("Programmieren"), tags.get("Thread"), tags.get("Prozess"),
tags.get("Synchronisation"), tags.get("Grundlagen"), tags.get("Betriebssystem"),
tags.get("Scheduling"), tags.get("Multithreading"), tags.get("Deadlock"),
tags.get("Datenstrukturen"), tags.get("Semaphore"),
tags.get("Sequencer"), tags.get("Eventcounts"), tags.get("Producer-Consumer"),
tags.get("Speicherverwaltung"), tags.get("Filesysteme"), tags.get("Netzwerk"),
tags.get("Security"), tags.get("Software"), tags.get("Diffizil"), tags.get("C"),
tags.get("Client-Server")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Introduction to Security").addTags(
tags.get("VU"), tags.get("Programmieren"), tags.get("Social engineering"), tags.get("Physical Break-Ins"),
tags.get("Dumpster Diving"), tags.get("Grundlagen"), tags.get("Password Cracking"),
tags.get("Session Hijacking"), tags.get("Network"), tags.get("Spoofing"),
tags.get("Viruses"), tags.get("Worms"), tags.get("Trojan Horses"),
tags.get("Phishing"), tags.get("Encryption"), tags.get("Netzwerk"),
tags.get("Security"), tags.get("Software"), tags.get("Diffizil"),
tags.get("Spyware"), tags.get("Adware"), tags.get("Cryptography"),
tags.get("Risk Analysis")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Daten- und Informatikrecht").addTags(
tags.get("VU"), tags.get("Theorie"), tags.get("Recht"), tags.get("Einfach"),
tags.get("Grundlagen"), tags.get("Wirtschaft"), tags.get("Technik")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Datenbanksysteme").addTags(
tags.get("VU"), tags.get("EER"), tags.get("Relationenmodel"), tags.get("Domänenkalkül"),
tags.get("Datenbanksprachen"), tags.get("Normalformen"), tags.get("SQL"),
tags.get("Datenintegrität"), tags.get("Diffizil"), tags.get("JDBC"), tags.get("DBMS")
);
coursesBachelorSoftwareAndInformationEngineering.get("VO Statistik und Wahrscheinlichkeitstheorie").addTags(
tags.get("VO"), tags.get("Mathe"), tags.get("Statistik"), tags.get("Wahrscheinlichkeitstheorie"),
tags.get("Verteilung"), tags.get("Histogramm"), tags.get("Wahrscheinlichkeitsräume"),
tags.get("Stochastik"), tags.get("Grundlagen"), tags.get("Gesetz der großen Zahlen"),
tags.get("Grundlagen der Bayes'schen"), tags.get("Diffizil"), tags.get("Zahlentheorie"),
tags.get("Mengenlehre"), tags.get("Kombinatorik")
);
coursesBachelorSoftwareAndInformationEngineering.get("UE Statistik und Wahrscheinlichkeitstheorie").addTags(
tags.get("UE"), tags.get("Mathe"), tags.get("Statistik"), tags.get("Wahrscheinlichkeitstheorie"),
tags.get("Verteilung"), tags.get("Histogramm"), tags.get("Wahrscheinlichkeitsräume"),
tags.get("Stochastik"), tags.get("Grundlagen"), tags.get("Gesetz der großen Zahlen"),
tags.get("Grundlagen der Bayes'schen"), tags.get("Diffizil"), tags.get("Zahlentheorie"),
tags.get("Mengenlehre"), tags.get("Kombinatorik")
);
}
private void addTagsToBachelorSoftwareAndInformationEngineeringCoursesSemester4() {
coursesBachelorSoftwareAndInformationEngineering.get("VU Einführung in die Künstliche Intelligenz").addTags(
tags.get("VU"), tags.get("Künstliche Intelligenz"), tags.get("Grundlagen"),
tags.get("Programmieren"), tags.get("Theorie"), tags.get("Diffizil")
);
coursesBachelorSoftwareAndInformationEngineering.get("VU Theoretische Informatik und Logik").addTags(
tags.get("VU"), tags.get("Automaten"), tags.get("reguläre Ausdrücke"), tags.get("formale Grammatiken"),
tags.get("Aussagenlogik"), tags.get("Petri-Netze"), tags.get("Prädikatenlogik"), tags.get("Diffizil"),
tags.get("Lambda-Kalkuel"), tags.get("Logik")
);
coursesBachelorSoftwareAndInformationEngineering.get("VO Software Engineering und Projektmanagement").addTags(
tags.get("VO"), tags.get("Theorie"), tags.get("Software"), tags.get("Projektmanagement"),
tags.get("Planning"), tags.get("UML"), tags.get("Objektorientiert"), tags.get("Softwarequalitätssicherung"),
tags.get("Risikomanagement"), tags.get("Qualitätsmanagement"), tags.get("Projektmarketing"),
tags.get("Einfach"), tags.get("Sprint"), tags.get("SCRUM"), tags.get("SQL")
);
coursesBachelorSoftwareAndInformationEngineering.get("PR Software Engineering und Projektmanagement").addTags(
tags.get("PR"), tags.get("Programmieren"), tags.get("Testing"), tags.get("Software"),
tags.get("Projektmanagement"), tags.get("Gruppenarbeit"), tags.get("Teamfaehigkeit"),
tags.get("Debug"), tags.get("Planning"), tags.get("UML"), tags.get("Objektorientiert"),
tags.get("Softwarequalitätssicherung"), tags.get("Risikomanagement"), tags.get("Qualitätsmanagement"),
tags.get("Projektmarketing"), tags.get("Diffizil"), tags.get("Praxis"),
tags.get("Sprint"), tags.get("SCRUM"), tags.get("CRUD"), tags.get("SQL"), tags.get("UML")
);
}
private void addSubjectsToStudyPlans() {
addBachelorSoftwareAndInformationEngineeringSubjectsToStudyPlan();
}
private void addBachelorSoftwareAndInformationEngineeringSubjectsToStudyPlan() {
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester1.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester1.get(subjectName), studyplans.get(0), true, 1)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester2.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester2.get(subjectName), studyplans.get(0), true, 2)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester3.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester3.get(subjectName), studyplans.get(0), true, 3)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester4.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester4.get(subjectName), studyplans.get(0), true, 4)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester5.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester5.get(subjectName), studyplans.get(0), true, 5)
);
}
for (String subjectName : subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester6.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsMandatoryBachelorSoftwareAndInformationEngineeringSemester6.get(subjectName), studyplans.get(0), true, 6)
);
}
for (String subjectName : subjectsOptionalBachelorSoftwareAndInformationEngineering.keySet()) {
subjectForStudyPlanRepository.save(new SubjectForStudyPlan(
subjectsOptionalBachelorSoftwareAndInformationEngineering.get(subjectName), studyplans.get(0), false)
);
}
}
private void registerCoursesToStudents() {
// Joan Watson
register(studentMap.get("Joan Watson"), coursesBachelorSoftwareAndInformationEngineering.get("UE Studieneingangsgespräch"));
register(studentMap.get("Joan Watson"), coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik"));
register(studentMap.get("Joan Watson"), coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik"));
// Emma Dowd
register(studentMap.get("Emma Dowd"), coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik"));
register(studentMap.get("Emma Dowd"), coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik"));
// Caroline Black
register(studentMap.get("Caroline Black"), coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik"));
// John Terry
Student john = studentMap.get("John Terry");
register(john, coursesBachelorSoftwareAndInformationEngineering.get("VU Datenmodellierung"));
register(john, coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik"));
register(john, coursesBachelorSoftwareAndInformationEngineering.get("VU Programmkonstruktion"));
}
private void register(Student student, Course course) {
course.addStudents(student);
studentSubjectPreferenceStore.studentRegisteredCourse(student, course);
}
private void giveGrades() {
Course course = coursesBachelorSoftwareAndInformationEngineering.get("UE Studieneingangsgespräch");
Student student = course.getStudents().get(0);
Lecturer lecturer = course.getSubject().getLecturers().get(0);
Grade grade = new Grade(course, lecturer, student, Mark.EXCELLENT);
gradeRepository.save(grade);
course = coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik");
student = studentMap.get("Emma Dowd");
lecturer = course.getSubject().getLecturers().get(0);
grade = new Grade(course, lecturer, student, Mark.EXCELLENT);
gradeRepository.save(grade);
course = coursesBachelorSoftwareAndInformationEngineering.get("VO Algebra und Diskrete Mathematik für Informatik und Wirtschaftsinformatik");
student = studentMap.get("Emma Dowd");
lecturer = course.getSubject().getLecturers().get(0);
grade = new Grade(course, lecturer, student, Mark.FAILED);
gradeRepository.save(grade);
grade = new Grade(
coursesBachelorSoftwareAndInformationEngineering.get("VU Datenmodellierung"),
lecturer,
studentMap.get("John Terry"),
Mark.EXCELLENT);
gradeRepository.save(grade);
}
private void giveFeedback() {
Course course = coursesBachelorSoftwareAndInformationEngineering.get("VU Datenmodellierung");
Student johnTerry = studentMap.get("John Terry");
Feedback feedback = new Feedback(johnTerry, course);
course = coursesBachelorSoftwareAndInformationEngineering.get("VU Technische Grundlagen der Informatik");
Student joanWatson = studentMap.get("Joan Watson");
Student emmaDowd = studentMap.get("Emma Dowd");
Student carolineBlack = studentMap.get("Caroline Black");
Feedback feedback1 = new Feedback(
joanWatson,
course,
Feedback.Type.LIKE, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec enim ligula. " +
"Sed eget posuere tellus. Aenean fermentum maximus tempor. Ut ultricies dapibus nulla vitae mollis. " +
"Suspendisse a nunc nisi. Sed ut sapien eu odio sodales laoreet eu ac turpis. " +
"In id sapien id ante sollicitudin consectetur at laoreet mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Suspendisse quam sem, ornare eget pellentesque sit amet, tincidunt id metus. Sed scelerisque neque sed laoreet elementum. " +
"Integer eros neque, vulputate a hendrerit at, ullamcorper in orci. Donec sit amet risus hendrerit, hendrerit magna non, dapibus nibh. " +
"Suspendisse sed est feugiat, dapibus ante non, aliquet neque. Cras magna sapien, pharetra ut ante ut, malesuada hendrerit erat. " +
"Mauris fringilla mattis dapibus. Nullam iaculis nunc in tortor gravida, id tempor justo elementum.");
Feedback feedback2 = new Feedback(
emmaDowd,
course,
Feedback.Type.DISLIKE, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec enim ligula. " +
"Sed eget posuere tellus. Aenean fermentum maximus tempor. Ut ultricies dapibus nulla vitae mollis. " +
"Suspendisse a nunc nisi. Sed ut sapien eu odio sodales laoreet eu ac turpis. " +
"In id sapien id ante sollicitudin consectetur at laoreet mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Suspendisse quam sem, ornare eget pellentesque sit amet, tincidunt id metus. Sed scelerisque neque sed laoreet elementum. " +
"Integer eros neque, vulputate a hendrerit at, ullamcorper in orci. Donec sit amet risus hendrerit, hendrerit magna non, dapibus nibh. " +
"Suspendisse sed est feugiat, dapibus ante non, aliquet neque. Cras magna sapien, pharetra ut ante ut, malesuada hendrerit erat. " +
"Mauris fringilla mattis dapibus. Nullam iaculis nunc in tortor gravida, id tempor justo elementum.");
Feedback feedback3 = new Feedback(
carolineBlack,
course,
Feedback.Type.LIKE, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec enim ligula. " +
"Sed eget posuere tellus. Aenean fermentum maximus tempor. Ut ultricies dapibus nulla vitae mollis. " +
"Suspendisse a nunc nisi. Sed ut sapien eu odio sodales laoreet eu ac turpis. " +
"In id sapien id ante sollicitudin consectetur at laoreet mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Suspendisse quam sem, ornare eget pellentesque sit amet, tincidunt id metus. Sed scelerisque neque sed laoreet elementum. " +
"Integer eros neque, vulputate a hendrerit at, ullamcorper in orci. Donec sit amet risus hendrerit, hendrerit magna non, dapibus nibh. " +
"Suspendisse sed est feugiat, dapibus ante non, aliquet neque. Cras magna sapien, pharetra ut ante ut, malesuada hendrerit erat. " +
"Mauris fringilla mattis dapibus. Nullam iaculis nunc in tortor gravida, id tempor justo elementum.");
giveFeedback(feedback, feedback1, feedback2, feedback3);
}
private void giveFeedback(Feedback... feedbacks) {
for (Feedback feedback : feedbacks) {
feedbackRepository.save(feedback);
studentSubjectPreferenceStore.studentGaveCourseFeedback(feedback.getStudent(), feedback);
}
}
}
|
package br.com.janes.ecommerce.web.rest;
import br.com.janes.ecommerce.config.Constants;
import com.codahale.metrics.annotation.Timed;
import br.com.janes.ecommerce.domain.User;
import br.com.janes.ecommerce.repository.UserRepository;
import br.com.janes.ecommerce.security.AuthoritiesConstants;
import br.com.janes.ecommerce.service.MailService;
import br.com.janes.ecommerce.service.UserService;
import br.com.janes.ecommerce.service.dto.UserDTO;
import br.com.janes.ecommerce.web.rest.errors.BadRequestAlertException;
import br.com.janes.ecommerce.web.rest.errors.EmailAlreadyUsedException;
import br.com.janes.ecommerce.web.rest.errors.LoginAlreadyUsedException;
import br.com.janes.ecommerce.web.rest.vm.ManagedUserVM;
import br.com.janes.ecommerce.web.rest.util.HeaderUtil;
import br.com.janes.ecommerce.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
/**
* REST controller for managing users.
* <p>
* This class accesses the User entity, and needs to fetch its collection of authorities.
* <p>
* For a normal use-case, it would be better to have an eager relationship between User and Authority,
* and send everything to the client side: there would be no View Model and DTO, a lot less code, and an outer-join
* which would be good for performance.
* <p>
* We use a View Model and a DTO for 3 reasons:
* <ul>
* <li>We want to keep a lazy association between the user and the authorities, because people will
* quite often do relationships with the user, and we don't want them to get the authorities all
* the time for nothing (for performance reasons). This is the #1 goal: we should not impact our users'
* application because of this use-case.</li>
* <li> Not having an outer join causes n+1 requests to the database. This is not a real issue as
* we have by default a second-level cache. This means on the first HTTP call we do the n+1 requests,
* but then all authorities come from the cache, so in fact it's much better than doing an outer join
* (which will get lots of data from the database, for each HTTP call).</li>
* <li> As this manages users, for security reasons, we'd rather have a DTO layer.</li>
* </ul>
* <p>
* Another option would be to have a specific JPA entity graph to handle this case.
*/
@RestController
@RequestMapping("/api")
public class UserResource {
private final Logger log = LoggerFactory.getLogger(UserResource.class);
private final UserRepository userRepository;
private final UserService userService;
private final MailService mailService;
public UserResource(UserRepository userRepository, UserService userService, MailService mailService) {
this.userRepository = userRepository;
this.userService = userService;
this.mailService = mailService;
}
// /**
// * POST /users : Creates a new user.
// * <p>
// * Creates a new user if the login and email are not already used, and sends an
// * mail with an activation link.
// * The user needs to be activated on creation.
// *
// * @param managedUserVM the user to create
// * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use
// * @throws URISyntaxException if the Location URI syntax is incorrect
// * @throws BadRequestAlertException 400 (Bad Request) if the login or email is already in use
// */
// @PostMapping("/users")
// @Timed
// @Secured(AuthoritiesConstants.ADMIN)
// public ResponseEntity<User> createUser(@Valid @RequestBody ManagedUserVM managedUserVM) throws URISyntaxException {
// log.debug("REST request to save User : {}", managedUserVM);
// if (managedUserVM.getId() != null) {
// throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists");
// // Lowercase the user login before comparing with database
// } else if (userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase()).isPresent()) {
// throw new LoginAlreadyUsedException();
// } else if (userRepository.findOneByEmailIgnoreCase(managedUserVM.getEmail()).isPresent()) {
// throw new EmailAlreadyUsedException();
// } else {
// User newUser = userService.createUser(managedUserVM);
// mailService.sendCreationEmail(newUser);
// return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin()))
// .headers(HeaderUtil.createAlert( "A user is created with identifier " + newUser.getLogin(), newUser.getLogin()))
// .body(newUser);
/**
* PUT /users : Updates an existing User.
*
* @param managedUserVM the user to update
* @return the ResponseEntity with status 200 (OK) and with body the updated user
* @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already in use
* @throws LoginAlreadyUsedException 400 (Bad Request) if the login is already in use
*/
@PutMapping("/users")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody ManagedUserVM managedUserVM) {
log.debug("REST request to update User : {}", managedUserVM);
Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(managedUserVM.getEmail());
if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) {
throw new EmailAlreadyUsedException();
}
existingUser = userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase());
if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) {
throw new LoginAlreadyUsedException();
}
Optional<UserDTO> updatedUser = userService.updateUser(managedUserVM);
return ResponseUtil.wrapOrNotFound(updatedUser,
HeaderUtil.createAlert("A user is updated with identifier " + managedUserVM.getLogin(), managedUserVM.getLogin()));
}
/**
* GET /users : get all users.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and with body all users
*/
@GetMapping("/users")
@Timed
public ResponseEntity<List<UserDTO>> getAllUsers(@ApiParam Pageable pageable) {
final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* @return a string list of the all of the roles
*/
@GetMapping("/users/authorities")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public List<String> getAuthorities() {
return userService.getAuthorities();
}
/**
* GET /users/:login : get the "login" user.
*
* @param login the login of the user to find
* @return the ResponseEntity with status 200 (OK) and with body the "login" user, or with status 404 (Not Found)
*/
@GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@Timed
public ResponseEntity<UserDTO> getUser(@PathVariable String login) {
log.debug("REST request to get User : {}", login);
return ResponseUtil.wrapOrNotFound(
userService.getUserWithAuthoritiesByLogin(login)
.map(UserDTO::new));
}
/**
* DELETE /users/:login : delete the "login" User.
*
* @param login the login of the user to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<Void> deleteUser(@PathVariable String login) {
log.debug("REST request to delete User: {}", login);
userService.deleteUser(login);
return ResponseEntity.ok().headers(HeaderUtil.createAlert( "A user is deleted with identifier " + login, login)).build();
}
}
|
package ch.brinika.sportsplanner5000.business;
import ch.brinika.sportsplanner5000.domain.Team;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author simon
* @author Andreas Briw
*/
@Stateless
@LocalBean
public class TeamEJB {
@PersistenceContext(unitName = "ch.brinika_sportsplanner5000_war_1.0PU")
EntityManager em;
//testkommentar
public Team createTeam(Team team)
{
em.persist(team);
return team;
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}
|
package ch.softappeal.yass.transport.ws;
import ch.softappeal.yass.core.remote.session.Connection;
import ch.softappeal.yass.core.remote.session.Packet;
import ch.softappeal.yass.core.remote.session.Session;
import ch.softappeal.yass.serialize.Reader;
import ch.softappeal.yass.serialize.Serializer;
import ch.softappeal.yass.serialize.Writer;
import ch.softappeal.yass.serialize.Writer.ByteBufferOutputStream;
import ch.softappeal.yass.transport.TransportSetup;
import ch.softappeal.yass.util.Check;
import ch.softappeal.yass.util.Nullable;
import javax.websocket.CloseReason;
import javax.websocket.MessageHandler;
import java.io.IOException;
import java.nio.ByteBuffer;
public abstract class WsConnection implements Connection {
private final Serializer packetSerializer;
public final javax.websocket.Session session;
private Session yassSession;
protected WsConnection(final Serializer packetSerializer, final javax.websocket.Session session) {
this.packetSerializer = Check.notNull(packetSerializer);
this.session = Check.notNull(session);
}
protected final ByteBuffer writeToBuffer(final Packet packet) throws Exception {
final ByteBufferOutputStream buffer = new ByteBufferOutputStream(128);
packetSerializer.write(packet, Writer.create(buffer));
return buffer.toByteBuffer();
}
final void onClose(final CloseReason closeReason) {
if (closeReason.getCloseCode().getCode() == CloseReason.CloseCodes.NORMAL_CLOSURE.getCode()) {
yassSession.close();
} else {
onError(new RuntimeException("WebSocket closed - " + closeReason.toString()));
}
}
static Exception wrap(final @Nullable Throwable throwable) {
if (throwable == null) {
return new Exception("<no-throwable>");
} else if (throwable instanceof Exception) {
return (Exception)throwable;
} else if (throwable instanceof Error) {
throw (Error)throwable;
} else {
throw new Error(throwable);
}
}
protected final void onError(final @Nullable Throwable ignore) {
Session.close(yassSession, wrap(ignore));
}
@Override public final void closed() throws IOException {
session.close();
}
private void created() {
session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() { // $note: this could be replaced with a lambda in WebSocket API 1.1
@Override public void onMessage(final ByteBuffer in) {
try {
Session.received(yassSession, (Packet)packetSerializer.read(Reader.create(in)));
if (in.hasRemaining()) {
throw new RuntimeException("input buffer is not empty");
}
} catch (final Exception ignore) {
Session.close(yassSession, ignore);
}
}
});
}
@FunctionalInterface public interface Factory {
WsConnection create(Serializer packetSerializer, javax.websocket.Session session) throws Exception;
}
public static WsConnection create(final Factory connectionFactory, final TransportSetup setup, final javax.websocket.Session session) throws Exception {
try {
final WsConnection connection = connectionFactory.create(setup.packetSerializer, session);
connection.created();
connection.yassSession = Session.create(setup.sessionFactory, connection);
return connection;
} catch (final Exception e) {
try {
session.close();
} catch (final Exception e2) {
e.addSuppressed(e2);
}
throw e;
}
}
}
|
package ch.sourcepond.maven.release.scm;
import static ch.sourcepond.maven.release.scm.DefaultProposedTag.BUILD_NUMBER;
import static ch.sourcepond.maven.release.scm.DefaultProposedTag.VERSION;
import static java.lang.String.format;
import static org.apache.commons.lang3.Validate.notNull;
import static org.eclipse.jgit.lib.Repository.isValidRefName;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.maven.plugin.logging.Log;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.LsRemoteCommand;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.errors.NoWorkTreeException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTag;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
import org.eclipse.jgit.treewalk.filter.PathFilter;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import ch.sourcepond.maven.release.config.Configuration;
// TODO: Make this class package private when SingleModuleTest is working with a Guice injector
@Named
@Singleton
public final class GitRepository implements SCMRepository {
private static final String REFS_TAGS = "refs/tags/";
static final String SNAPSHOT_COMMIT_MESSAGE = "Incremented SNAPSHOT-version for next development iteration";
static final String INVALID_REF_NAME_MESSAGE = "Sorry, '%s' is not a valid version.";
private final Log log;
private final GitFactory gitFactory;
private final Configuration config;
private Git git;
private SCMException gitInstantiationException;
private Collection<Ref> remoteTags;
@Inject
public GitRepository(final Log pLog, final GitFactory pGitFactory, final Configuration pConfig) {
log = pLog;
gitFactory = pGitFactory;
config = pConfig;
}
private Git getGit() throws SCMException {
if (git == null && gitInstantiationException == null) {
try {
git = gitFactory.newGit();
} catch (final SCMException e) {
gitInstantiationException = e;
}
}
if (git == null) {
throw gitInstantiationException;
}
return git;
}
@Override
public Collection<Long> getRemoteBuildNumbers(final String remoteUrlOrNull, final String artifactId,
final String versionWithoutBuildNumber) throws SCMException {
final Collection<Ref> remoteTagRefs = allRemoteTags(remoteUrlOrNull);
final Collection<Long> remoteBuildNumbers = new ArrayList<Long>();
final String tagWithoutBuildNumber = artifactId + "-" + versionWithoutBuildNumber;
for (final Ref remoteTagRef : remoteTagRefs) {
final String remoteTagName = remoteTagRef.getName();
final Long buildNumber = buildNumberOf(tagWithoutBuildNumber, remoteTagName);
if (buildNumber != null) {
remoteBuildNumbers.add(buildNumber);
}
}
return remoteBuildNumbers;
}
public Collection<Ref> allRemoteTags(final String remoteUrlOrNull) throws SCMException {
if (remoteTags == null) {
final LsRemoteCommand lsRemoteCommand = getGit().lsRemote().setTags(true).setHeads(false);
if (remoteUrlOrNull != null) {
lsRemoteCommand.setRemote(remoteUrlOrNull);
}
try {
remoteTags = lsRemoteCommand.call();
} catch (final GitAPIException e) {
throw new SCMException(e, "Remote tags could not be listed!");
}
}
return remoteTags;
}
@Override
public boolean hasLocalTag(final String tagName) throws SCMException {
try {
return GitHelper.hasLocalTag(getGit(), tagName);
} catch (final GitAPIException e) {
throw new SCMException(e, "Local tag could not be determined!");
}
}
private Status currentStatus() throws SCMException {
Status status;
try {
status = getGit().status().call();
} catch (final GitAPIException e) {
throw new SCMException(e, "Error while checking if the Git repo is clean");
}
return status;
}
@Override
public void errorIfNotClean() throws SCMException {
final Status status = currentStatus();
final boolean isClean = status.isClean();
if (!isClean) {
final SCMException exception = new SCMException(
"Cannot release with uncommitted changes. Please check the following files:");
final Set<String> uncommittedChanges = status.getUncommittedChanges();
if (uncommittedChanges.size() > 0) {
exception.add("Uncommitted:");
for (final String path : uncommittedChanges) {
exception.add(" * %s", path);
}
}
final Set<String> untracked = status.getUntracked();
if (untracked.size() > 0) {
exception.add("Untracked:");
for (final String path : untracked) {
exception.add(" * %s", path);
}
}
throw exception.add("Please commit or revert these changes before releasing.");
}
}
@Override
public void revertChanges(final Collection<File> changedFiles) throws SCMException {
try {
final File workTree = getGit().getRepository().getWorkTree().getCanonicalFile();
final SCMException exception = new SCMException("Reverting changed POMs failed!");
for (final File changedFile : changedFiles) {
try {
final String pathRelativeToWorkingTree = Repository.stripWorkDir(workTree, changedFile);
getGit().checkout().addPath(pathRelativeToWorkingTree).call();
} catch (final Exception e) {
exception.add(
" * Unable to revert changes to %s - you may need to manually revert this file. Error was: %s",
changedFile, e.getMessage());
}
}
if (!exception.getMessages().isEmpty()) {
throw exception;
}
} catch (NoWorkTreeException | IOException e) {
throw new SCMException(e, "Working directory could not be determined!");
}
}
@Override
public List<ProposedTag> tagsForVersion(final String module, final String versionWithoutBuildNumber)
throws SCMException {
final List<ProposedTag> results = new ArrayList<>();
List<Ref> tags;
try {
tags = getGit().tagList().call();
} catch (final GitAPIException e) {
throw new SCMException(e, "Error while getting a list of tags in the local repo");
}
Collections.reverse(tags);
final String tagWithoutBuildNumber = module + "-" + versionWithoutBuildNumber;
for (final Ref tag : tags) {
if (isPotentiallySameVersionIgnoringBuildNumber(tagWithoutBuildNumber, tag.getName())) {
results.add(fromRef(tag));
}
}
return results;
}
static boolean isPotentiallySameVersionIgnoringBuildNumber(final String versionWithoutBuildNumber,
final String refName) {
return buildNumberOf(versionWithoutBuildNumber, refName) != null;
}
public static Long buildNumberOf(final String versionWithoutBuildNumber, final String refName) {
final String tagName = stripRefPrefix(refName);
final String prefix = versionWithoutBuildNumber + ".";
if (tagName.startsWith(prefix)) {
final String end = tagName.substring(prefix.length());
try {
return Long.parseLong(end);
} catch (final NumberFormatException e) {
return null;
}
}
return null;
}
@Override
public ProposedTag fromRef(final Ref gitTag) throws SCMException {
notNull(gitTag, "gitTag");
final RevWalk walk = new RevWalk(getGit().getRepository());
final ObjectId tagId = gitTag.getObjectId();
JSONObject message;
try {
final RevTag tag = walk.parseTag(tagId);
message = (JSONObject) JSONValue.parse(tag.getFullMessage());
} catch (final IOException e) {
throw new SCMException(e, "Error while looking up tag because RevTag could not be parsed! Object-id was %s",
tagId);
} finally {
walk.dispose();
}
if (message == null) {
message = new JSONObject();
message.put(VERSION, "0");
message.put(BUILD_NUMBER, "0");
}
return new DefaultProposedTag(getGit(), log, gitTag, stripRefPrefix(gitTag.getName()), message);
}
static String stripRefPrefix(final String refName) {
return refName.substring(REFS_TAGS.length());
}
@Override
public ProposedTagsBuilder newProposedTagsBuilder(final String remoteUrlOrNull) throws SCMException {
return new DefaultProposedTagsBuilder(log, getGit(), this, remoteUrlOrNull);
}
@Override
public void checkValidRefName(final String releaseVersion) throws SCMException {
if (!isValidRefName(format("%s%s", REFS_TAGS, releaseVersion))) {
throw new SCMException(INVALID_REF_NAME_MESSAGE, releaseVersion)
.add("Version numbers are used in the Git tag, and so can only contain characters that are valid in git tags.")
.add("Please see https:
}
}
@Override
public boolean hasChangedSince(final String modulePath, final List<String> childModules,
final Collection<ProposedTag> tags) throws SCMException {
final RevWalk walk = new RevWalk(getGit().getRepository());
try {
walk.setRetainBody(false);
walk.markStart(walk.parseCommit(getGit().getRepository().findRef("HEAD").getObjectId()));
filterOutOtherModulesChanges(modulePath, childModules, walk);
stopWalkingWhenTheTagsAreHit(tags, walk);
final Iterator<RevCommit> it = walk.iterator();
boolean changed = it.hasNext();
if (config.isIncrementSnapshotVersionAfterRelease() && changed) {
changed = !SNAPSHOT_COMMIT_MESSAGE.equals(it.next().getShortMessage()) || it.hasNext();
}
return changed;
} catch (final IOException e) {
throw new SCMException(e, "Diff detector could not determine whether module %s has been changed!",
modulePath);
} finally {
walk.dispose();
}
}
private static void stopWalkingWhenTheTagsAreHit(final Collection<ProposedTag> tags, final RevWalk walk)
throws IOException {
for (final ProposedTag tag : tags) {
final ObjectId commitId = tag.getObjectId();
final RevCommit revCommit = walk.parseCommit(commitId);
walk.markUninteresting(revCommit);
}
}
private void filterOutOtherModulesChanges(final String modulePath, final List<String> childModules,
final RevWalk walk) {
final boolean isRootModule = ".".equals(modulePath);
final boolean isMultiModuleProject = !isRootModule || !childModules.isEmpty();
final List<TreeFilter> treeFilters = new LinkedList<TreeFilter>();
treeFilters.add(TreeFilter.ANY_DIFF);
if (isMultiModuleProject) {
if (!isRootModule) {
// for sub-modules, look for changes only in the sub-module
// path...
treeFilters.add(PathFilter.create(modulePath));
}
// ... but ignore any sub-modules of the current sub-module, because
// they can change independently of the current module
for (final String childModule : childModules) {
final String path = isRootModule ? childModule : modulePath + "/" + childModule;
treeFilters.add(PathFilter.create(path).negate());
}
}
final TreeFilter treeFilter = treeFilters.size() == 1 ? treeFilters.get(0) : AndTreeFilter.create(treeFilters);
walk.setTreeFilter(treeFilter);
}
@Override
public void pushChanges(final String remoteUrlOrNull, final Collection<File> changedFiles) throws SCMException {
try {
final File workTree = getGit().getRepository().getWorkTree().getCanonicalFile();
for (final File changedFile : changedFiles) {
final String pathRelativeToWorkingTree = Repository.stripWorkDir(workTree, changedFile);
getGit().add().setUpdate(true).addFilepattern(pathRelativeToWorkingTree).call();
}
getGit().commit().setMessage(SNAPSHOT_COMMIT_MESSAGE).call();
if (remoteUrlOrNull != null) {
getGit().push().setRemote(remoteUrlOrNull).call();
}
} catch (final GitAPIException | IOException e) {
throw new SCMException(e, "Changed POM files could not be committed and pushed!");
}
}
}
|
package uk.ac.ebi.atlas.bioentity.properties;
import com.google.common.collect.ImmutableList;
import uk.ac.ebi.atlas.model.OntologyTerm;
import uk.ac.ebi.atlas.solr.BioentityPropertyName;
import uk.ac.ebi.atlas.search.SemanticQuery;
import uk.ac.ebi.atlas.bioentity.go.GoPoTrader;
import uk.ac.ebi.atlas.bioentity.interpro.InterProTrader;
import uk.ac.ebi.atlas.species.Species;
import uk.ac.ebi.atlas.species.SpeciesInferrer;
import uk.ac.ebi.atlas.utils.ReactomeClient;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static org.apache.commons.text.WordUtils.capitalize;
import static uk.ac.ebi.atlas.solr.BioentityPropertyName.GO;
import static uk.ac.ebi.atlas.solr.BioentityPropertyName.PO;
import static uk.ac.ebi.atlas.solr.BioentityPropertyName.SYMBOL;
@Named
public class BioEntityPropertyService {
private SpeciesInferrer speciesInferrer;
private BioEntityPropertyDao bioEntityPropertyDao;
private ReactomeClient reactomeClient;
private GoPoTrader goPoTermTrader;
private InterProTrader interProTermTrader;
@Inject
public BioEntityPropertyService(SpeciesInferrer speciesInferrer,
BioEntityPropertyDao bioEntityPropertyDao,
ReactomeClient reactomeClient,
GoPoTrader goPoTermTrader,
InterProTrader interProTermTrader) {
this.speciesInferrer = speciesInferrer;
this.bioEntityPropertyDao = bioEntityPropertyDao;
this.reactomeClient = reactomeClient;
this.goPoTermTrader = goPoTermTrader;
this.interProTermTrader = interProTermTrader;
}
Map<String, String> mapToLinkText(BioentityPropertyName propertyName,
Collection<String> propertyValues,
boolean isPlantSpecies) {
switch (propertyName) {
case ORTHOLOG:
return propertyValues.stream()
.collect(toMap(identity(), this::fetchSymbolAndSpeciesForOrtholog));
case PATHWAYID:
return isPlantSpecies ?
reactomeClient.getPlantPathwayNames(propertyValues) :
reactomeClient.getPathwayNames(propertyValues);
case GO: case PO:
return propertyValues.stream()
.collect(toMap(identity(),
p -> goPoTermTrader.get(p).map(OntologyTerm::name).orElse(p)));
case INTERPRO:
return propertyValues.stream()
.collect(toMap(identity(),
p -> interProTermTrader.get(p).map(OntologyTerm::name).orElse(p)));
default:
return propertyValues.stream().collect(toMap(identity(), identity()));
}
}
int assessRelevance(BioentityPropertyName bioentityPropertyName, String propertyValue) {
if (ImmutableList.of(GO, PO).contains(bioentityPropertyName)) {
return goPoTermTrader.get(propertyValue).map(OntologyTerm::depth).orElse(0);
} else {
return 0;
}
}
private String fetchSymbolAndSpeciesForOrtholog(String identifier) {
Species species = speciesInferrer.inferSpeciesForGeneQuery(SemanticQuery.create(identifier));
if (species.isUnknown()) {
return identifier;
}
Set<String> identifierSymbols = bioEntityPropertyDao.fetchPropertyValuesForGeneId(identifier, SYMBOL);
String speciesToken = " (" + capitalize(species.getName(), new char[0]) + ")";
if (!identifierSymbols.isEmpty()) {
return identifierSymbols.iterator().next() + speciesToken;
}
return identifier + speciesToken;
}
}
|
package be.iminds.iot.dianne.dashboard;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import be.iminds.iot.dianne.api.nn.module.dto.NeuralNetworkDTO;
import be.iminds.iot.dianne.api.repository.DianneRepository;
import be.iminds.iot.dianne.nn.util.DianneJSONConverter;
import be.iminds.iot.dianne.tensor.Tensor;
@Component(service={javax.servlet.Servlet.class},
property={"alias:String=/dianne/download",
"osgi.http.whiteboard.servlet.pattern=/dianne/download",
"aiolos.proxy=false"},
immediate=true)
public class DianneDownload extends HttpServlet{
private static final long serialVersionUID = 1L;
private BundleContext context;
private DianneRepository repository;
@Activate
void activate(BundleContext c){
this.context = c;
}
@Reference
void setRepository(DianneRepository r){
this.repository = r;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String nnName = req.getParameter("nn");
String tag = req.getParameter("tag");
byte[] zip = zipNN(nnName, (tag == null || tag.isEmpty()) ? null : tag.split(","));
if(zip != null){
ServletOutputStream out = resp.getOutputStream();
resp.setContentType("application/zip");
resp.setHeader("Content-Disposition", "attachment; filename=\""+nnName+".jar\"");
out.write(zip);
out.flush();
}
}
private byte[] zipNN(String nnName, String... tags) {
try(
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(zos))
) {
String version = "1.0.0";
for(String t : tags){
if(isVersion(t)){
version = t;
break;
}
}
// add manifest
Manifest manifest = new Manifest();
Attributes atts = manifest.getMainAttributes();
atts.put(Attributes.Name.MANIFEST_VERSION, "1.0");
atts.putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
atts.putValue(Constants.BUNDLE_NAME, "Dianne NN "+nnName);
atts.putValue(Constants.BUNDLE_SYMBOLICNAME, "be.iminds.iot.dianne.nn."+nnName);
atts.putValue(Constants.BUNDLE_VERSION, version);
atts.putValue("NeuralNetwork", nnName);
// TODO add requirement on a DIANNE runtime capability instead of Import-Package?
atts.putValue("Import-Package", "be.iminds.iot.dianne.api.nn.runtime;version=\""+dianneVersion()+"\"");
zos.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
manifest.write(zos);
zos.closeEntry();
// add nn description
NeuralNetworkDTO nn = repository.loadNeuralNetwork(nnName);
String nnString = DianneJSONConverter.toJsonString(nn, true);
zos.putNextEntry(new ZipEntry("modules.txt"));
zos.write(nnString.getBytes());
zos.closeEntry();
// add nn layout if present
try {
String layout = repository.loadLayout(nnName);
zos.putNextEntry(new ZipEntry("layout.txt"));
zos.write(layout.getBytes());
zos.closeEntry();
} catch(Exception e){}
// add weights in binary files
try {
Map<UUID, Tensor> weights = repository.loadParameters(nnName, tags);
for(Entry<UUID, Tensor> e : weights.entrySet()){
String weightName = e.getKey().toString();
if(tags!=null && tags.length>0){
for(String t : tags){
weightName+="-"+t;
}
}
zos.putNextEntry(new ZipEntry(weightName));
float[] data = e.getValue().get();
dos.writeInt(data.length);
for(int i=0;i<data.length;i++){
dos.writeFloat(data[i]);
}
dos.flush();
zos.closeEntry();
}
}catch(Exception e){
// ignore if no parameters available
}
zos.flush();
zos.finish();
baos.flush();
return baos.toByteArray();
} catch(Exception e){
}
return null;
}
private boolean isVersion(String v){
try {
Version version = Version.parseVersion(v);
return true;
} catch(Exception e){
return false;
}
}
private String dianneVersion() {
Version v = context.getBundle().getVersion();
// omit qualifier
return v.getMajor()+"."+v.getMinor()+"."+v.getMicro();
}
}
|
package org.intermine.bio.dataconversion;
import java.io.File;
import java.io.FileReader;
import java.util.Collections;
import java.util.HashMap;
import org.intermine.bio.dataconversion.IdResolverService;
import org.intermine.dataconversion.ItemsTestCase;
import org.intermine.dataconversion.MockItemWriter;
import org.intermine.metadata.Model;
import org.intermine.model.fulldata.Item;
public class RnaiConverterTest extends ItemsTestCase
{
MockItemWriter itemWriter;
RnaiConverter converter;
public RnaiConverterTest(String arg) {
super(arg);
}
public void setUp() throws Exception {
super.setUp();
itemWriter = new MockItemWriter(new HashMap<String, Item>());
converter = new RnaiConverter(itemWriter, Model.getInstanceByName("genomic"));
converter.rslv = IdResolverService.getMockIdResolver("Gene");
converter.rslv.addResolverEntry("7227", "FBgn0015806", Collections.singleton("FBgn001"));
converter.rslv.addResolverEntry("7227", "FBgn0053207", Collections.singleton("FBgn002"));
}
public void testProcess() throws Exception {
File srcFile = new File(getClass().getClassLoader().getResource("all_screens_genomeRNAi.txt").toURI());
converter.setCurrentFile(srcFile);
converter.process(new FileReader(srcFile));
converter.close();
// uncomment to write out a new target items file
//writeItemsFile(itemWriter.getItems(), "rnai-converter-tgt.xml");
assertEquals(readItemSet("RnaiConverterTest.xml"), itemWriter.getItems());
}
}
|
package com.celements.web.service;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.context.Execution;
import org.xwiki.model.reference.DocumentReference;
import com.celements.model.access.IModelAccessFacade;
import com.celements.model.access.exception.DocumentLoadException;
import com.celements.model.access.exception.DocumentNotExistsException;
import com.celements.model.access.exception.DocumentSaveException;
import com.celements.rendering.RenderCommand;
import com.celements.web.UserCreateException;
import com.celements.web.plugin.cmd.PasswordRecoveryAndEmailValidationCommand;
import com.celements.web.plugin.cmd.PossibleLoginsCommand;
import com.celements.web.plugin.cmd.UserNameForUserDataCommand;
import com.celements.web.token.NewCelementsTokenForUserCommand;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.user.api.XWikiUser;
import com.xpn.xwiki.util.Util;
import com.xpn.xwiki.web.XWikiResponse;
@Component
public class CelementsWebService implements ICelementsWebServiceRole {
private static Logger _LOGGER = LoggerFactory.getLogger(CelementsWebService.class);
private List<String> supportedAdminLangList;
@Requirement
private IWebUtilsService webUtilsService;
@Requirement
IModelAccessFacade modelAccess;
@Requirement
private Execution execution;
private XWikiContext getContext() {
return (XWikiContext) execution.getContext().getProperty("xwikicontext");
}
public String getEmailAdressForUser(String username) {
return getEmailAdressForUser(webUtilsService.resolveDocumentReference(username));
}
@Override
public String getEmailAdressForUser(DocumentReference userDocRef) {
if (getContext().getWiki().exists(userDocRef, getContext())) {
try {
XWikiDocument doc = getContext().getWiki().getDocument(userDocRef, getContext());
BaseObject obj = doc.getXObject(webUtilsService.resolveDocumentReference(
"XWiki.XWikiUsers"));
if (obj != null) {
return obj.getStringValue("email");
}
} catch (XWikiException exp) {
_LOGGER.error("Exception while getting a XWikiDocument. docRef:['" + userDocRef + "]'",
exp);
}
}
return null;
}
@Override
public int createUser(boolean validate) throws XWikiException {
String possibleLogins = new PossibleLoginsCommand().getPossibleLogins();
return createUser(getUniqueNameValueRequestMap(), possibleLogins, validate);
}
@Override
public synchronized int createUser(Map<String, String> userData, String possibleLogins,
boolean validate) throws XWikiException {
try {
if (createNewUser(userData, possibleLogins, validate) != null) {
return 1;
}
} catch (UserCreateException uce) {
if (uce.getCause() instanceof XWikiException) {
throw (XWikiException) uce.getCause();
} else {
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_UNKNOWN, "failed to create user", uce);
}
}
return -1;
}
@Override
public synchronized @NotNull XWikiUser createNewUser(@NotNull Map<String, String> userData,
@NotNull String possibleLogins, boolean validate) throws UserCreateException {
String accountName = "";
String accountFullName = null;
if (userData.containsKey("xwikiname")) {
accountName = userData.get("xwikiname");
userData.remove("xwikiname");
} else {
while (accountName.equals("") || getContext().getWiki().exists(
webUtilsService.resolveDocumentReference(accountFullName), getContext())) {
accountName = getContext().getWiki().generateRandomString(12);
accountFullName = "XWiki." + accountName;
}
}
String validkey = "";
int success = -1;
try {
if (areIdentifiersUnique(userData, possibleLogins, getContext())) {
if (!userData.containsKey("password")) {
String password = getContext().getWiki().generateRandomString(8);
userData.put("password", password);
}
if (!userData.containsKey("validkey")) {
validkey = new NewCelementsTokenForUserCommand().getUniqueValidationKey(getContext());
userData.put("validkey", validkey);
} else {
validkey = userData.get("validkey");
}
if (!userData.containsKey("active")) {
userData.put("active", "0");
}
String content = "#includeForm(\"XWiki.XWikiUserSheet\")";
success = getContext().getWiki().createUser(accountName, userData,
webUtilsService.resolveDocumentReference("XWiki.XWikiUsers"), content, null, "edit",
getContext());
}
} catch (XWikiException excp) {
_LOGGER.error("Exception while creating a new user", excp);
throw new UserCreateException(excp);
}
XWikiUser newUser = null;
if (success == 1) {
setRightsOnUserDoc(accountFullName);
newUser = new XWikiUser(accountFullName);
if (validate) {
_LOGGER.info("send account validation mail with data: accountname='" + accountName
+ "', email='" + userData.get("email") + "', validkey='" + validkey + "'");
try {
new PasswordRecoveryAndEmailValidationCommand().sendValidationMessage(userData.get(
"email"), validkey, webUtilsService.resolveDocumentReference(
"Tools.AccountActivationMail"), webUtilsService.getDefaultAdminLanguage());
} catch (XWikiException e) {
_LOGGER.error("Exception while sending validation mail to '" + userData.get("email")
+ "'", e);
throw new UserCreateException(e);
}
}
}
if (newUser == null) {
throw new UserCreateException("Failed to create a new user");
}
return newUser;
}
void setRightsOnUserDoc(@NotNull String accountFullName) throws UserCreateException {
try {
XWikiDocument doc = modelAccess.getDocument(webUtilsService.resolveDocumentReference(
accountFullName));
List<BaseObject> rightsObjs = doc.getXObjects(webUtilsService.resolveDocumentReference(
"XWiki.XWikiRights"));
for (BaseObject rightObj : rightsObjs) {
if (rightObj.getStringValue("groups").equals("")) {
rightObj.setStringValue("users", webUtilsService.getRefLocalSerializer().serialize(
doc.getDocumentReference()));
rightObj.set("allow", "1", getContext());
rightObj.set("levels", "view,edit,delete", getContext());
rightObj.set("groups", "", getContext());
} else {
rightObj.set("users", "", getContext());
rightObj.set("allow", "1", getContext());
rightObj.set("levels", "view,edit,delete", getContext());
rightObj.set("groups", "XWiki.XWikiAdminGroup", getContext());
}
}
modelAccess.saveDocument(doc, "added rights objects to created user");
} catch (DocumentLoadException | DocumentNotExistsException | DocumentSaveException excp) {
_LOGGER.error("Exception while trying to add rights to newly created user", excp);
throw new UserCreateException(excp);
}
}
@SuppressWarnings("unchecked")
@Override
public Map<String, String> getUniqueNameValueRequestMap() {
Map<String, String[]> params = getContext().getRequest().getParameterMap();
Map<String, String> resultMap = new HashMap<String, String>();
for (String key : params.keySet()) {
if ((params.get(key) != null) && (params.get(key).length > 0)) {
resultMap.put(key, params.get(key)[0]);
} else {
resultMap.put(key, "");
}
}
return resultMap;
}
private boolean areIdentifiersUnique(Map<String, String> userData, String possibleLogins,
XWikiContext context) throws XWikiException {
boolean isUnique = true;
for (String key : userData.keySet()) {
if (!"".equals(key.trim()) && (("," + possibleLogins + ",").indexOf("," + key + ",") >= 0)) {
String user = new UserNameForUserDataCommand().getUsernameForUserData(userData.get(key),
possibleLogins, context);
if ((user == null) || (user.length() > 0)) { // user == "" means there is no such
// user
isUnique = false;
}
}
}
return isUnique;
}
@Override
public List<String> getSupportedAdminLanguages() {
if (supportedAdminLangList == null) {
supportedAdminLangList = Arrays.asList(new String[] { "de", "fr", "en", "it" });
}
return supportedAdminLangList;
}
@Override
public boolean writeUTF8Response(String filename, String renderDocFullName) {
boolean success = false;
if (getContext().getWiki().exists(webUtilsService.resolveDocumentReference(renderDocFullName),
getContext())) {
XWikiDocument renderDoc;
try {
renderDoc = getContext().getWiki().getDocument(webUtilsService.resolveDocumentReference(
renderDocFullName), getContext());
adjustResponseHeader(filename, getContext().getResponse());
setResponseContent(renderDoc, getContext().getResponse());
} catch (XWikiException e) {
_LOGGER.error("", e);
}
getContext().setFinished(true);
}
return success;
}
private void adjustResponseHeader(String filename, XWikiResponse response) {
response.setContentType("text/plain");
String ofilename = Util.encodeURI(filename, getContext()).replaceAll("\\+", " ");
response.addHeader("Content-disposition", "attachment; filename=\"" + ofilename
+ "\"; charset='UTF-8'");
}
private void setResponseContent(XWikiDocument renderDoc, XWikiResponse response)
throws XWikiException {
String renderedContent = new RenderCommand().renderDocument(renderDoc);
byte[] data = {};
try {
data = renderedContent.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
response.setContentLength(data.length + 3);
try {
response.getOutputStream().write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
response.getOutputStream().write(data);
} catch (IOException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION,
"Exception while sending response", e);
}
}
@Override
public void setSupportedAdminLanguages(List<String> supportedAdminLangList) {
this.supportedAdminLangList = supportedAdminLangList;
}
}
|
package org.biojava.bio.structure.io;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.biojava.bio.structure.AminoAcid;
import org.biojava.bio.structure.Atom;
import org.biojava.bio.structure.Chain;
import org.biojava.bio.structure.Group;
import org.biojava.bio.structure.HetatomImpl;
import org.biojava.bio.structure.ResidueNumber;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.io.mmcif.chem.PolymerType;
import org.biojava.bio.structure.io.mmcif.chem.ResidueType;
import org.biojava.bio.structure.io.mmcif.model.ChemComp;
import org.biojava3.alignment.Alignments;
import org.biojava3.alignment.SimpleGapPenalty;
import org.biojava3.alignment.SubstitutionMatrixHelper;
import org.biojava3.alignment.Alignments.PairwiseSequenceAlignerType;
import org.biojava3.alignment.template.GapPenalty;
import org.biojava3.alignment.template.PairwiseSequenceAligner;
import org.biojava3.alignment.template.SequencePair;
import org.biojava3.alignment.template.SubstitutionMatrix;
import org.biojava3.core.sequence.ProteinSequence;
import org.biojava3.core.sequence.compound.AminoAcidCompound;
import org.biojava3.core.sequence.compound.AminoAcidCompoundSet;
import org.biojava3.core.sequence.template.Compound;
/** Aligns the SEQRES residues to the ATOM residues.
* The AminoAcids that can be matched between the two of them will be set in the SEQRES
* chains
*
*
* @author Andreas Prlic
*
*/
public class SeqRes2AtomAligner {
boolean DEBUG = false;
static final List<String> excludeTypes;
String alignmentString;
static {
excludeTypes = new ArrayList<String>();
excludeTypes.add("HOH"); // we don't want to align water against the SEQRES...
excludeTypes.add("DOD"); // deuterated water
//matrix.printMatrix();
}
public SeqRes2AtomAligner(){
alignmentString = "";
}
public String getAlignmentString() {
return alignmentString;
}
public boolean isDEBUG() {
return DEBUG;
}
public void setDEBUG(boolean debug) {
DEBUG = debug;
}
private Chain getMatchingAtomRes(Chain seqRes, List<Chain> atomList)
throws StructureException {
Iterator<Chain> iter = atomList.iterator();
while(iter.hasNext()){
Chain atomChain = iter.next();
if ( atomChain.getChainID().equals(seqRes.getChainID())){
return atomChain;
}
}
throw new StructureException("could not match seqres chainID >" + seqRes.getChainID() + "< to ATOM chains!");
}
public void align(Structure s, List<Chain> seqResList){
//List<Chain> seqResList = s.getSeqRes();
List<Chain> atomList = s.getModel(0);
for (Chain seqRes: seqResList){
try {
Chain atomRes = getMatchingAtomRes(seqRes,atomList);
boolean simpleMatchSuccessful = trySimpleMatch(seqRes, atomRes);
if ( simpleMatchSuccessful) {
// update the new SEQRES list
List<Group> seqResGroups = seqRes.getAtomGroups();
atomRes.setSeqResGroups(seqResGroups);
continue;
}
System.err.println("Could not map SEQRES to ATOM records easily, need to align...");
if ( seqRes.getAtomGroups("amino").size() < 1) {
if (DEBUG){
System.out.println("chain " + seqRes.getChainID() + " does not contain amino acids, ignoring...");
}
continue;
}
if ( atomRes.getAtomGroups("amino").size() < 1) {
if (DEBUG){
System.out.println("chain " + atomRes.getChainID() + " does not contain amino acids, ignoring...");
}
continue;
}
if ( DEBUG )
System.out.println("Alignment for chain "+ atomRes.getChainID() );
List<Group> seqResGroups = seqRes.getAtomGroups();
boolean noMatchFound = align(seqResGroups,atomRes.getAtomGroups());
if ( ! noMatchFound){
atomRes.setSeqResGroups(seqResGroups);
}
//chains.add(mapped);
} catch (StructureException e){
e.printStackTrace();
}
}
//s.setChains(0,chains);
}
/** a simple matching approach that tries to do a 1:1 mapping between SEQRES and ATOM records
* returns true if this simple matching approach worked fine
*
* @param seqRes
* @param atomList
* @return
*/
private boolean trySimpleMatch(Chain seqRes, Chain atomRes) {
List<Group> seqResGroups = seqRes.getAtomGroups();
List<Group> atmResGroups = atomRes.getAtomGroups();
if (DEBUG) {
System.err.println("COMPARING " + atomRes.getChainID() + " " + seqRes.getChainID());
}
// by default first ATOM position is 1
boolean startAt1 = true;
for ( int atomResPos = 0 ; atomResPos < atmResGroups.size() ; atomResPos++){
// let's try to match this case
Group atomResGroup = atmResGroups.get(atomResPos);
// let's ignore waters
String threeLetterCode = atomResGroup.getPDBName();
if ( excludeTypes.contains(threeLetterCode)){
continue;
}
ResidueNumber atomResNum = atomResGroup.getResidueNumber();
int seqResPos = atomResNum.getSeqNum();
if ( seqResPos < 0) {
if ( DEBUG )
System.err.println("ATOM residue number < 0");
return false;
}
if ( seqResPos == 0){
// make sure the first SEQRES is matching.
Group seqResGroup = seqResGroups.get(0);
if ( seqResGroup.getPDBName().equals(atomResGroup.getPDBName())){
// they match! seems in this case the numbering starts with 0...
startAt1 = false;
} else {
if ( DEBUG){
System.err.println("SEQRES position 1 ("+seqResGroup.getPDBName()+
") does not match ATOM PDB res num 0 (" + atomResGroup.getPDBName()+")");
return false;
}
}
}
if ( startAt1 )
seqResPos
// another check that would require the alignment approach
if ( startAt1 && seqResPos >= seqResGroups.size() )
{
// could be a HETATOM...
if ( atomResGroup instanceof AminoAcid) {
if ( DEBUG )
System.err.println(" ATOM residue nr: " + seqResPos + " > seqres! " + seqResGroups.size() + " " + atomResGroup);
return false;
} else {
// we won't map HETATOM groups...
continue;
}
}
if ( seqResPos < 0){
System.err.println("What is going on??? " + atomRes.getChainID() + " " + atomResGroup);
}
Group seqResGroup = seqResGroups.get(seqResPos );
if ( ! seqResGroup.getPDBName().trim().equals(atomResGroup.getPDBName().trim())){
// a mismatch! something is wrong in the mapping and we need to do an alignment
if ( DEBUG )
System.err.println("Mismatch of SEQRES pos " + seqResPos + " and ATOM record: " + atomResGroup + " | " + seqResGroup);
return false;
}
// the two groups are identical and we can merge them
// replace the SEQRES group with the ATOM group...
seqResGroups.set(seqResPos, atomResGroup);
}
// all atom records could get matched correctly!
return true;
}
/** returns the full sequence of the Atom records of a parent
* with X instead of HETATMSs. The advantage of this is
* that it allows us to also align HETATM groups back to the SEQRES.
* @param groups the list of groups in a parent
* @param positionIndex a Map to keep track of which group is at which sequence position
* @return string representations
*/
public String getFullAtomSequence(List<Group> groups, Map<Integer, Integer> positionIndex){
StringBuffer sequence = new StringBuffer() ;
int seqIndex = 0;
for ( int i=0 ; i< groups.size(); i++){
Group g = (Group) groups.get(i);
if ( g instanceof AminoAcid ){
AminoAcid a = (AminoAcid)g;
char oneLetter =a.getAminoType();
if ( oneLetter == '?')
oneLetter = 'X';
positionIndex.put(seqIndex,i);
sequence.append(oneLetter );
seqIndex++;
} else {
// exclude solvents
if ( excludeTypes.contains(g.getPDBName()))
continue;
// exclude metals
if ( g.size() == 1 ) {
try {
Atom a = g.getAtom(0);
if (a.getElement().isMetal())
continue;
continue;
} catch (StructureException e){
e.printStackTrace();
continue;
}
}
ChemComp cc = g.getChemComp();
if (
ResidueType.lPeptideLinking.equals(cc.getResidueType()) ||
PolymerType.PROTEIN_ONLY.contains(cc.getPolymerType()) ||
PolymerType.POLYNUCLEOTIDE_ONLY.contains(cc.getPolymerType())
) {
//System.out.println(cc.getOne_letter_code());
String c = cc.getOne_letter_code();
if ( c.equals("?"))
c = "X";
positionIndex.put(seqIndex,i);
sequence.append(c);
seqIndex++;
} else {
//System.out.println(cc);
continue;
}
//sequence.append("X");
}
}
return sequence.toString();
}
/** aligns two chains of groups, where the first parent is representing the
* list of amino acids as obtained from the SEQRES records, and the second parent
* represents the groups obtained from the ATOM records (and containing the actual ATOM information).
* This does the actual alignment and if a group can be mapped to a position in the SEQRES then the corresponding
* position is repplaced with the group that contains the atoms.
*
* @param seqRes
* @param atomRes
* @return true if no match has bee found
* @throws StructureException
*/
public boolean align(List<Group> seqRes, List<Group> atomRes) throws StructureException{
Map<Integer,Integer> seqresIndexPosition = new HashMap<Integer, Integer>();
Map<Integer,Integer> atomIndexPosition = new HashMap<Integer, Integer>();
String seq1 = getFullAtomSequence(seqRes, seqresIndexPosition);
String seq2 = getFullAtomSequence(atomRes, atomIndexPosition);
if ( DEBUG ) {
System.out.println("align seq1 ("+ seq1.length()+") " + seq1);
System.out.println("align seq2 ("+ seq2.length()+") " + seq2);
}
ProteinSequence s1 = new ProteinSequence(seq1);
ProteinSequence s2 = new ProteinSequence(seq2);
SubstitutionMatrix<AminoAcidCompound> matrix = SubstitutionMatrixHelper.getBlosum65();
GapPenalty penalty = new SimpleGapPenalty();
short gop = 8;
short extend = 1;
penalty.setOpenPenalty(gop);
penalty.setExtensionPenalty(extend);
try {
PairwiseSequenceAligner<ProteinSequence, AminoAcidCompound> smithWaterman =
Alignments.getPairwiseAligner(s1, s2, PairwiseSequenceAlignerType.LOCAL, penalty, matrix);
SequencePair<ProteinSequence, AminoAcidCompound> pair = smithWaterman.getPair();
if ( pair == null)
throw new StructureException("could not align objects!");
if ( DEBUG ) {
System.out.println(pair.toString(60));
}
boolean noMatchFound = mapChains(seqRes,atomRes,pair,seqresIndexPosition, atomIndexPosition );
return noMatchFound;
} catch (Exception e){
System.err.println("Problem while aligning ATOM and SEQRES records for " + atomRes.get(0).getChain().getParent().getPDBCode() + " chain: " +atomRes.get(0).getChain().getChainID());
//e.printStackTrace();
return true;
}
}
private boolean mapChains(List<Group> seqResGroups, List<Group> atomRes,
SequencePair<ProteinSequence, AminoAcidCompound> pair,
Map<Integer,Integer> seqresIndexPosition,
Map<Integer,Integer> atomIndexPosition
) throws StructureException{
// at the present stage the future seqREs are still stored as Atom groups in the seqRes parent...
int aligLength = pair.getLength();
// System.out.println("sequence length seqres:");
// System.out.println(seqresIndexPosition.keySet().size());
// System.out.println("alignment length: " + aligLength);
// System.out.println(gapSymbol.getName());
// make sure we actually find an alignment
boolean noMatchFound = true;
Compound gapSymbol = AminoAcidCompoundSet.getAminoAcidCompoundSet().getCompoundForString("-");
mainLoop:
for (int i = 1; i <= aligLength ; i++) {
Compound s = pair.getCompoundAt(1, i);
Compound a = pair.getCompoundAt(2,i);
// alignment is using internal index start at 1...
int posSeq = pair.getIndexInQueryAt(i) -1;
int posAtom = pair.getIndexInTargetAt(i) -1;
if ( s.equals(gapSymbol) || a.equals(gapSymbol)){
continue;
}
if ( s.equals(a)){
// the atom record can be aligned to the SeqRes record!
// replace the SeqRes group with the Atom group!
Group s1 = seqResGroups.get(seqresIndexPosition.get(posSeq));
Group a1 = atomRes.get(atomIndexPosition.get(posAtom));
if ( s1 == null || a1 == null){
/// can't map this position...
System.err.println("can't map " + i + ":" + s + " " + posSeq +" " + s1 + " atom: " + posAtom + " " + a1 );
continue mainLoop;
}
// need to trim the names to allow matching e.g in
// pdb1b2m
String pdbNameS = s1.getPDBName();
String pdbNameA = a1.getPDBName();
if ( pdbNameS == null || pdbNameA == null ){
System.err.println("null value found at " + posSeq + " when trying to align " + s1 + " and " + a1 + " " + posAtom);
throw new StructureException("null value found at group.getPDBName()");
}
if (! pdbNameA.equals(pdbNameS)){
if ( ! pdbNameA.trim().equals(pdbNameS.trim())) {
System.err.println(s1 + " " + posSeq + " does not align with " + a1+ " " + posAtom + " should be: " + s + " : " + a);
if ( s1.getType().equals(HetatomImpl.type) && a1.getType().equals(HetatomImpl.type)){
System.err.println("they seem to be hetatoms, so ignoring mismatch.");
}
else {
// System.exit(0);// for debug only
//System.out.println(lst1.seqString());
//System.out.println(lst2.seqString());
System.err.println("could not match residues " + s1 + " " + a1);
//throw new StructureException("could not match residues " + s1 + " " + a1);
}
}
}
// do the actual replacing of the SEQRES group with the ATOM group
// if ( s1.getChain().getChainID().equals("A")) {
// System.out.println(" setting " + posSeq +" " + a1);
seqResGroups.set(seqresIndexPosition.get(posSeq),a1);
noMatchFound = false;
}
}
// now we merge the two chains into one
// the Groups that can be aligned are now pointing to the
// groups in the Atom records.
if ( noMatchFound) {
if ( DEBUG )
System.out.println("no alignment found!");
}
return noMatchFound;
}
}
|
package com.codahale.metrics.jenkins;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import javax.annotation.concurrent.GuardedBy;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Stephen Connolly
*/
public class MetricsAccessKey extends AbstractDescribableImpl<MetricsAccessKey> implements Serializable {
private static long serialVersionUID = 1L;
@NonNull
private final String key;
@CheckForNull
private final String description;
private final boolean canPing;
private final boolean canThreadDump;
private final boolean canHealthCheck;
private final boolean canMetrics;
public MetricsAccessKey(String description, String key) {
this(description, key, true, false, false, true);
}
@DataBoundConstructor
public MetricsAccessKey(String description, String key, boolean canPing, boolean canThreadDump,
boolean canHealthCheck, boolean canMetrics) {
this.description = Util.fixEmptyAndTrim(description);
key = Util.fixEmptyAndTrim(key);
this.key = key == null ? DescriptorImpl.generateKey() : key;
this.canPing = canPing;
this.canThreadDump = canThreadDump;
this.canHealthCheck = canHealthCheck;
this.canMetrics = canMetrics;
}
@CheckForNull
public String getDescription() {
return description;
}
@NonNull
public String getKey() {
return key;
}
public boolean isCanPing() {
return canPing;
}
public boolean isCanThreadDump() {
return canThreadDump;
}
public boolean isCanHealthCheck() {
return canHealthCheck;
}
public boolean isCanMetrics() {
return canMetrics;
}
@Extension
public static class DescriptorImpl extends Descriptor<MetricsAccessKey> {
private static final SecureRandom entropy = new SecureRandom();
private static final char[] keyChars =
"ABCEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".toCharArray();
@GuardedBy("this")
private List<MetricsAccessKey> accessKeys;
private transient volatile Set<String> accessKeySet;
public DescriptorImpl() {
super();
load();
}
@NonNull
public static String generateKey() {
StringBuilder b = new StringBuilder(64);
for (int i = 0; i < 64; i++) {
b.append(keyChars[entropy.nextInt(keyChars.length)]);
}
return b.toString();
}
@Override
public synchronized boolean configure(StaplerRequest req, JSONObject json) throws FormException {
accessKeys = req.bindJSONToList(MetricsAccessKey.class, json.get("accessKeys"));
accessKeySet = null;
save();
return true;
}
@NonNull
public synchronized List<MetricsAccessKey> getAccessKeys() {
return Collections.unmodifiableList(new ArrayList<MetricsAccessKey>(
accessKeys == null ? Collections.<MetricsAccessKey>emptyList() : accessKeys
));
}
public void checkAccessKey(@CheckForNull String accessKey) {
Set<String> accessKeySet = this.accessKeySet;
if (accessKeySet == null) {
accessKeySet = new HashSet<String>();
for (Provider p : Jenkins.getInstance().getExtensionList(Provider.class)) {
for (MetricsAccessKey k : p.getAccessKeys()) {
accessKeySet.add(k.getKey());
}
}
synchronized (this) {
for (MetricsAccessKey k : accessKeys) {
accessKeySet.add(k.getKey());
}
this.accessKeySet = accessKeySet; // will be idempotent
}
}
if (!accessKeySet.contains(accessKey)) {
// slow check
for (Provider p : Jenkins.getInstance().getExtensionList(Provider.class)) {
if (p.mayHaveOnDemandKeys && p.getAccessKey(accessKey) != null) {
return;
}
}
throw new AccessDeniedException(Messages.MetricsAccessKey_invalidAccessKey(accessKey));
}
}
public boolean hasAccessKeyPing(@CheckForNull String accessKey) {
checkAccessKey(accessKey);
MetricsAccessKey key = getAccessKey(accessKey);
return key != null && key.isCanPing();
}
public boolean hasAccessKeyThreadDump(@CheckForNull String accessKey) {
checkAccessKey(accessKey);
MetricsAccessKey key = getAccessKey(accessKey);
return key != null && key.isCanThreadDump();
}
public boolean hasAccessKeyHealthCheck(@CheckForNull String accessKey) {
checkAccessKey(accessKey);
MetricsAccessKey key = getAccessKey(accessKey);
return key != null && key.isCanHealthCheck();
}
public boolean hasAccessKeyMetrics(@CheckForNull String accessKey) {
checkAccessKey(accessKey);
MetricsAccessKey key = getAccessKey(accessKey);
return key != null && key.isCanMetrics();
}
public void checkAccessKeyPing(@CheckForNull String accessKey) {
if (!hasAccessKeyPing(accessKey)) {
throw new AccessDeniedException(Messages.MetricsAccessKey_invalidAccessKey(accessKey));
}
}
public void checkAccessKeyThreadDump(@CheckForNull String accessKey) {
if (!hasAccessKeyThreadDump(accessKey)) {
throw new AccessDeniedException(Messages.MetricsAccessKey_invalidAccessKey(accessKey));
}
}
public void checkAccessKeyHealthCheck(@CheckForNull String accessKey) {
if (!hasAccessKeyHealthCheck(accessKey)) {
throw new AccessDeniedException(Messages.MetricsAccessKey_invalidAccessKey(accessKey));
}
}
public void checkAccessKeyMetrics(@CheckForNull String accessKey) {
if (!hasAccessKeyMetrics(accessKey)) {
throw new AccessDeniedException(Messages.MetricsAccessKey_invalidAccessKey(accessKey));
}
}
private MetricsAccessKey getAccessKey(String accessKey) {
for (Provider p : Jenkins.getInstance().getExtensionList(Provider.class)) {
MetricsAccessKey key = p.getAccessKey(accessKey);
if (key != null) {
return key;
}
}
synchronized (this) {
for (MetricsAccessKey k : accessKeys) {
if (StringUtils.equals(accessKey, k.getKey())) {
return k;
}
}
}
return null;
}
@Override
public String getDisplayName() {
return Messages.MetricsAccessKey_displayName();
}
public void reindexAccessKeys() {
Set<String> accessKeySet = new HashSet<String>();
for (Provider p : Jenkins.getInstance().getExtensionList(Provider.class)) {
for (MetricsAccessKey k : p.getAccessKeys()) {
accessKeySet.add(k.getKey());
}
}
synchronized (this) {
if (accessKeys != null) {
for (MetricsAccessKey k : accessKeys) {
accessKeySet.add(k.getKey());
}
}
this.accessKeySet = accessKeySet;
}
}
}
/**
* An extension point that allows for plugins to provide their own set of access keys.
*/
public static abstract class Provider implements ExtensionPoint {
/**
* Tracks if {@link #getAccessKey(String)} has been overridden (which means that there may be keys that are
* not iterable from the {@link #getAccessKeys()} method.
*/
private final boolean mayHaveOnDemandKeys;
protected Provider() {
boolean needsSlow = true;
try {
Method method = getClass().getMethod("getAccessKey", String.class);
needsSlow = !method.getDeclaringClass().equals(Provider.class);
} catch (NoSuchMethodException e) {
needsSlow = true;
}
this.mayHaveOnDemandKeys = needsSlow;
}
public abstract List<MetricsAccessKey> getAccessKeys();
/**
* Returns the definition of the specific access key. Note that all entries in {@link #getAccessKeys()} must
* be returned by this method, but it may also return additional entries.
*
* @param accessKey the access key to retrieve.
* @return the access key.
*/
@CheckForNull
public MetricsAccessKey getAccessKey(String accessKey) {
for (MetricsAccessKey k : getAccessKeys()) {
if (StringUtils.equals(accessKey, k.getKey())) {
return k;
}
}
return null;
}
}
}
|
package org.jasig.cas.authentication.principal;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.util.DefaultUniqueTicketIdGenerator;
import org.jasig.cas.util.UniqueTicketIdGenerator;
import org.springframework.util.StringUtils;
public final class SamlService extends AbstractWebApplicationService {
private static final Log LOG = LogFactory.getLog(SamlService.class);
private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC");
/** Constant representing service. */
private static final String CONST_PARAM_SERVICE = "TARGET";
/** Constant representing artifact. */
private static final String CONST_PARAM_TICKET = "SAMLart";
private static final UniqueTicketIdGenerator GENERATOR = new DefaultUniqueTicketIdGenerator();
private boolean loggedOutAlready = false;
/**
* Unique Id for serialization.
*/
private static final long serialVersionUID = -6867572626767140223L;
public SamlService(final String id) {
super(id, id, null);
}
protected SamlService(final String id, final String originalUrl,
final String artifactId) {
super(id, originalUrl, artifactId);
}
public static WebApplicationService createServiceFrom(
final HttpServletRequest request) {
final String service = request.getParameter(CONST_PARAM_SERVICE);
if (!StringUtils.hasText(service)) {
return null;
}
final String id = cleanupUrl(service);
final String artifactId = request.getParameter(CONST_PARAM_TICKET);
return new SamlService(id, service, artifactId);
}
public String getRedirectUrl(final String ticketId) {
final String service = getOriginalUrl();
final StringBuilder buffer = new StringBuilder(ticketId.length()
+ ticketId.length() + CONST_PARAM_TICKET.length()
+ CONST_PARAM_SERVICE.length() + 4 + service.length());
buffer.append(service);
buffer.append(service.contains("?") ? "&" : "?");
buffer.append(CONST_PARAM_TICKET);
buffer.append("=");
try {
buffer.append(URLEncoder.encode(ticketId, "UTF-8"));
} catch (final UnsupportedEncodingException e) {
buffer.append(ticketId);
}
buffer.append("&");
buffer.append(CONST_PARAM_SERVICE);
buffer.append("=");
try {
buffer.append(URLEncoder.encode(service, "UTF-8"));
} catch (final UnsupportedEncodingException e) {
buffer.append(service);
}
return buffer.toString();
}
public synchronized boolean logOutOfService(final String sessionIdentifier) {
if (this.loggedOutAlready) {
return true;
}
final DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(UTC_TIME_ZONE);
final String date = dateFormat.format(new Date());
LOG.debug("Sending logout request for: " + getId());
final String logoutRequest = "<samlp:LogoutRequest ID=\""
+ GENERATOR.getNewTicketId("LR")
+ "\" Version=\"2.0\" IssueInstant=\"" + date
+ "\"><saml:NameID>NotUsed</saml:NameID><samlp:SessionIndex>"
+ sessionIdentifier + "</samlp:SessionIndex></samlp:LogoutRequest>";
HttpURLConnection connection = null;
try {
final URL logoutUrl = new URL(getOriginalUrl());
final String output = "logoutRequest=" + logoutRequest;
connection = (HttpURLConnection) logoutUrl.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(output.getBytes().length));
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
final DataOutputStream printout = new DataOutputStream(connection
.getOutputStream());
printout.writeBytes(output);
printout.flush();
printout.close();
final BufferedReader in = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
while (in.readLine() != null) {
// nothing to do
}
return true;
} catch (final MalformedURLException e) {
return false;
} catch (final IOException e) {
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
this.loggedOutAlready = true;
}
}
}
|
package edu.kestrel.netbeans.lisp;
import com.franz.jlinker.TranStruct;
import com.franz.jlinker.JavaLinkDist;
import com.franz.jlinker.LispConnector;
//hacky stuff:
import org.openide.nodes.Node;
import org.openide.loaders.DataObject;
import org.openide.filesystems.FileObject;
import edu.kestrel.netbeans.MetaSlangDataObject;
import edu.kestrel.netbeans.actions.ProcessUnitAction;
import edu.kestrel.netbeans.parser.ParseSourceRequest;
import edu.kestrel.netbeans.Util;
import java.util.HashSet;
import java.util.Set;
import org.openide.TopManager;
import org.openide.filesystems.FileSystem;
import org.openide.filesystems.Repository;
import org.openide.text.CloneableEditor;
import org.openide.text.CloneableEditorSupport;
import org.openide.windows.InputOutput;
import org.openide.windows.OutputWriter;
/**
*
* @author weilyn
*/
public class LispProcessManager {
private static Set machines = new HashSet() ;
private static String lispFile = "";
private static String lispHost = "";
private static int lispPort = 4321;
private static int pollInterval = 1000;
private static int pollCount = 300;
private static int javaTimeout = -1;
private static String javaFile = "";
private static String javaHost = "";
private static int javaPort = 0;
static private ExternalLispProcess lispServer = null;
static private Process lispProcess = null;
/** Creates a new instance of LispProcessManager */
public LispProcessManager() {
}
public static boolean connectToLisp() {
if (JavaLinkDist.query(true)) {
// writeToOutput("LispProcessManager.connectToLisp --> Already Connected");
return true;
} else if (JavaLinkDist.connect(lispHost, lispPort, javaHost, javaPort, pollInterval, javaTimeout)) {
// writeToOutput("LispProcessManager.connectToLisp --> New Connection Established");
return true;
} else {
// writeToOutput("LispProcessManager.connectToLisp --> Failed to Connect to LISP " + JavaLinkDist.query());
// writeToOutput("LispServer = "+ lispServer + "\n Lisp Process "+lispProcess + "\n");
if (lispServer == null){
lispServer = new ExternalLispProcess();
try {
lispProcess = lispServer.createProcess();
Thread.sleep(5000);
} catch (Exception e) {
writeToOutput("LispProcessManager.connectToLisp.Exception "+e+" starting Lisp");
}
// writeToOutput("LispProcessManager.connectToLisp --> Calling Connect to Lisp again");
if (lispProcess != null) {
return connectToLisp();
}
}
return false;
}
}
public static void destroyLispProcess() {
if (lispProcess != null) {
// writeToOutput("\n Destroying Lisp Process "+lispProcess);
lispProcess.destroy();
lispProcess = null;
lispServer = null;
}
}
public static void processUnit(String pathName, String fileName) {
if (connectToLisp()) {
TranStruct [] ARGS = new TranStruct[2];
TranStruct [] RES;
ARGS[0] = JavaLinkDist.newDistOb(pathName);
ARGS[1] = JavaLinkDist.newDistOb(fileName);
com.franz.jlinker.LispConnector.go(false, null);
//Set focus to Specware Status tab
writeToSpecwareStatus("");
try {
RES = JavaLinkDist.invokeInLispEx(3, JavaLinkDist.newDistOb("USER::PROCESS-UNIT"), ARGS);
// Util.log("Done.");
if (com.franz.jlinker.JavaLinkDist.stringP(RES[0])) {
Util.log("Error while generating code for: \n"+ RES[0]);
} else {
// Util.log("Call succeeded");
}
} catch (JavaLinkDist.JLinkerException ex) {
Util.log("Exception in generateCode "+ ex);
}
} else {
// writeToOutput("LispProcessManager.generateCode ==> No Connection to Lisp");
}
}
// This is called from specware
public static void setProcessUnitResults(String results) {
writeToSpecwareStatus(results);
FileObject fileObj = Repository.getDefault().find("Demo_Examples", null, null);
if (fileObj != null)
fileObj.refresh();
}
public static void setProcessUnitResults(String pathName, String fileName, int lineNum, int colNum, String errorMsg) {
FileObject fileObj = Repository.getDefault().find(pathName, fileName, "sw");
if (fileObj != null) {
// SLIGHT HACK: ParseSourceRequest is the same class used for the netbeans parsing stuff...
// should probably create different class for the Specware processing stuff
ParseSourceRequest.pushProcessUnitError(fileObj, lineNum, colNum, errorMsg, "");
}
}
public static void generateLispCode(String pathName, String fileName) {
if (connectToLisp()) {
TranStruct [] ARGS = new TranStruct[2];
TranStruct [] RES;
ARGS[0] = JavaLinkDist.newDistOb(pathName);
ARGS[1] = JavaLinkDist.newDistOb(fileName);
com.franz.jlinker.LispConnector.go(false, null);
//Set focus to Specware Status tab
writeToSpecwareStatus("");
try {
RES = JavaLinkDist.invokeInLispEx(3, JavaLinkDist.newDistOb("USER::GENERATE-LISP"), ARGS);
// Util.log("Done.");
if (com.franz.jlinker.JavaLinkDist.stringP(RES[0])) {
Util.log("Error while generating code for: \n"+ RES[0]);
} else {
// Util.log("Call succeeded");
}
} catch (JavaLinkDist.JLinkerException ex) {
Util.log("Exception in generateCode "+ ex);
}
} else {
// writeToOutput("LispProcessManager.generateCode ==> No Connection to Lisp");
}
}
public static void setGenerateLispResults(String pathName, String fileName, String results) {
writeToSpecwareStatus(results);
// TOTAL HACK: 14 is the length of "Demo_Examples/", which is the path to fileName in Weilyn's setup from the
// mounted local directory C:\Program Files\Specware4\Gui\src
String nonQualifiedFileName = fileName.substring(14);
// Do a refresh of Demo_Examples folder to show the possibly newly created "lisp" folder
FileObject fileObj = Repository.getDefault().find("Demo_Examples", null, null);
if (fileObj != null) fileObj.refresh();
// Do a refresh of lisp folder to show the newly generated file
fileObj = Repository.getDefault().find("Demo_Examples.lisp", null, null);
if (fileObj != null) fileObj.refresh();
// TODO: Open the new lisp file in the editor as a text file
fileObj = Repository.getDefault().find("Demo_Examples.lisp", nonQualifiedFileName, "lisp");
if (fileObj != null) {
// CloneableEditorSupport editSupp = new CloneableEditorSupport(new CloneableEditorSupport.Env(fileObj));
// CloneableEditor editor = new CloneableEditor(editSupp);
}
}
public static void generateJavaCode(String pathName, String fileName) {
if (connectToLisp()) {
TranStruct [] ARGS = new TranStruct[2];
TranStruct [] RES;
ARGS[0] = JavaLinkDist.newDistOb(pathName);
ARGS[1] = JavaLinkDist.newDistOb(fileName);
com.franz.jlinker.LispConnector.go(false, null);
//Set focus to Specware Status tab
writeToSpecwareStatus("");
try {
RES = JavaLinkDist.invokeInLispEx(3, JavaLinkDist.newDistOb("USER::GENERATE-JAVA"), ARGS);
// Util.log("Done.");
if (com.franz.jlinker.JavaLinkDist.stringP(RES[0])) {
Util.log("Error while generating code for: \n"+ RES[0]);
} else {
// Util.log("Call succeeded");
}
} catch (JavaLinkDist.JLinkerException ex) {
Util.log("Exception in generateCode "+ ex);
}
} else {
// writeToOutput("LispProcessManager.generateCode ==> No Connection to Lisp");
}
}
public static void setGenerateJavaResults(String pathName, String fileName, String results) {
writeToSpecwareStatus(results);
// TOTAL HACK: 14 is the length of "Demo_Examples/", which is the path to fileName in Weilyn's setup from the
// mounted local directory C:\Program Files\Specware4\Gui\src
String nonQualifiedFileName = fileName.substring(14);
// Do a refresh of Demo_Examples folder to show the possibly newly created "java" folder
FileObject fileObj = Repository.getDefault().find("Demo_Examples", null, null);
if (fileObj != null) fileObj.refresh();
// Do a refresh of java folder to show the newly generated file
fileObj = Repository.getDefault().find("Demo_Examples.java", null, null);
if (fileObj != null) fileObj.refresh();
// TODO: Open the new java file in the editor
fileObj = Repository.getDefault().find("Demo_Examples.java", nonQualifiedFileName, "java");
if (fileObj != null) {
// CloneableEditorSupport editSupp = new CloneableEditorSupport(new CloneableEditorSupport.Env(fileObj));
// CloneableEditor editor = new CloneableEditor(editSupp);
}
}
public static void writeToOutput(String s) {
InputOutput outputStream = TopManager.getDefault().getIO("Debug: LispProcessManager", false);
OutputWriter writer = outputStream.getOut();
writer.println(s);
}
public static void writeToSpecwareStatus(String s) {
InputOutput outputStream = TopManager.getDefault().getIO("Specware Output", false);
outputStream.select();
OutputWriter writer = outputStream.getOut();
writer.println(s);
}
}
|
package com.authlete.common.dto;
import java.io.Serializable;
/**
* Request to Authlete's /auth/requestobject API.
*
* @author jricher
*
*/
public class RequestObjectRequest implements Serializable
{
private static final long serialVersionUID = 1L;
/**
* FAPI Request object endpoint request body (in JWS format).
*/
private String body;
/**
* Get the value of the HTTP message body sent to the
* request object endpoint. This consists entirely of a
* JSON Web Token (JWT) signed with Json Web Signatures
* (JWS) representing the client's request object.
*
* @return
* The body string.
*
* @since 2.XX
*/
public String getBody()
{
return body;
}
/**
* Get the value of the HTTP message body sent to the
* request object endpoint. This consists entirely of a
* JSON Web Token (JWT) signed with Json Web Signatures
* (JWS) representing the client's request object.
*
* @param body
* The body string.
*
* @return
* this object
*
* @since 2.XX
*/
public RequestObjectRequest setBody(String body)
{
this.body = body;
return this;
}
}
|
package com.conveyal.analysis;
import com.conveyal.r5.util.ExceptionUtils;
import graphql.GraphQLError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class AnalysisServerException extends RuntimeException {
private static final Logger LOG = LoggerFactory.getLogger(AnalysisServerException.class);
public int httpCode;
public TYPE type;
public String message;
public enum TYPE {
BAD_REQUEST,
BROKER,
FILE_UPLOAD,
FORBIDDEN,
GRAPHQL,
JSON_PARSING,
NONCE,
NOT_FOUND,
UNAUTHORIZED,
UNKNOWN;
}
public static AnalysisServerException badRequest(String message) {
return new AnalysisServerException(TYPE.BAD_REQUEST, message, 400);
}
public static AnalysisServerException fileUpload(String message) {
return new AnalysisServerException(TYPE.FILE_UPLOAD, message, 400);
}
public static AnalysisServerException forbidden(String message) {
return new AnalysisServerException(TYPE.FORBIDDEN, message, 403);
}
public static AnalysisServerException graphQL(List<GraphQLError> errors) {
return new AnalysisServerException(
TYPE.GRAPHQL,
errors
.stream()
.map(e -> e.getMessage())
.reduce("", (a, b) -> a + " " + b),
400
);
}
public static AnalysisServerException nonce() {
return new AnalysisServerException(TYPE.NONCE, "The data you attempted to change is out of date and could not be " +
"updated. This project may be open by another user or in another browser tab.", 400);
}
public static AnalysisServerException notFound(String message) {
return new AnalysisServerException(TYPE.NOT_FOUND, message, 404);
}
public static AnalysisServerException unauthorized(String message) {
return new AnalysisServerException(TYPE.UNAUTHORIZED, message, 401);
}
public static AnalysisServerException unknown(Exception e) {
return new AnalysisServerException(TYPE.UNKNOWN, ExceptionUtils.asString(e), 400);
}
public static AnalysisServerException unknown(String message) {
return new AnalysisServerException(TYPE.UNKNOWN, message, 400);
}
public AnalysisServerException(Exception e, String message) {
this(message);
LOG.error(ExceptionUtils.asString(e));
}
public AnalysisServerException(String message) {
this(TYPE.UNKNOWN, message, 400);
}
public AnalysisServerException(AnalysisServerException.TYPE t, String m, int c) {
httpCode = c;
type = t;
message = m;
}
@Override
public String getMessage() {
return message;
}
}
|
package com.dmdirc.ui.core.newserver;
import com.dmdirc.DMDircMBassador;
import com.dmdirc.config.profiles.Profile;
import com.dmdirc.config.profiles.ProfileManager;
import com.dmdirc.events.ProfileAddedEvent;
import com.dmdirc.events.ProfileDeletedEvent;
import com.dmdirc.interfaces.ConnectionManager;
import com.dmdirc.interfaces.config.AggregateConfigProvider;
import com.dmdirc.interfaces.config.ConfigProvider;
import com.dmdirc.interfaces.ui.NewServerDialogModelListener;
import com.google.common.collect.Lists;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CoreNewServerDialogModelTest {
@Mock private AggregateConfigProvider globalConfig;
@Mock private ConfigProvider userConfig;
@Mock private ProfileManager profileManager;
@Mock private ConnectionManager connectionManager;
@Mock private DMDircMBassador eventBus;
@Mock private Profile profile1;
@Mock private Profile profile2;
@Mock private NewServerDialogModelListener listener;
private CoreNewServerDialogModel instance;
@Before
public void setupMocks() {
when(profileManager.getProfiles()).thenReturn(
Lists.newArrayList(profile1, profile2));
when(globalConfig.getOption("newserver", "hostname")).thenReturn("hostname");
when(globalConfig.getOptionInt("newserver", "port")).thenReturn(1111);
when(globalConfig.getOption("newserver", "password")).thenReturn("password");
when(globalConfig.getOptionBool("newserver", "ssl")).thenReturn(true);
instance = new CoreNewServerDialogModel(globalConfig, userConfig, profileManager,
connectionManager, eventBus);
}
@Test
public void testGetProfiles() {
instance.loadModel();
assertEquals("loadModel: ", Lists.newArrayList(profile1, profile2), instance.
getProfileList());
}
@Test
public void testSelectedProfile() {
instance.loadModel();
assertEquals("testSelectedProfile: ",
Optional.<Profile>empty(), instance.getSelectedProfile());
instance.setSelectedProfile(Optional.ofNullable(profile1));
assertEquals("testSelectedProfile", Optional.ofNullable(profile1),
instance.getSelectedProfile());
}
@Test
public void testProfileValidatorEmpty() {
when(profileManager.getProfiles()).thenReturn(Lists.<Profile>newArrayList());
instance.loadModel();
assertFalse("testProfileValidatorEmpty: ", instance.isProfileListValid());
}
@Test
public void testProfileValidatorNotEmpty() {
when(profileManager.getProfiles()).thenReturn(Lists.newArrayList(profile1, profile2));
instance.loadModel();
assertTrue("testProfileValidatorNotEmpty: ", instance.isProfileListValid());
}
@Test
public void testHostname() {
instance.loadModel();
assertEquals("testHostname: ", Optional.ofNullable("hostname"), instance.getHostname());
instance.setHostname(Optional.ofNullable("test"));
assertEquals("testHostname: ", Optional.ofNullable("test"), instance.getHostname());
}
@Test
public void testHostnameValidatorValid() {
when(globalConfig.getOption("newserver", "hostname")).thenReturn("hostname");
instance.loadModel();
assertTrue("testHostnameValidatorValid: ", instance.isHostnameValid());
}
@Test
public void testHostnameValidatorInvalid() {
when(globalConfig.getOption("newserver", "hostname")).thenReturn("~!£$^£$%^&");
instance.loadModel();
assertFalse("testHostnameValidatorInvalid: ", instance.isHostnameValid());
}
@Test
public void testPort() {
instance.loadModel();
assertEquals("testPort: ", Optional.ofNullable(1111), instance.getPort());
instance.setPort(Optional.ofNullable(5678));
assertEquals("testPort: ", Optional.ofNullable(5678), instance.getPort());
}
@Test
public void testPortValidatorValid() {
when(globalConfig.getOptionInt("newserver", "port")).thenReturn(1111);
instance.loadModel();
assertTrue("testPortValidatorValid: ", instance.isPortValid());
}
@Test
public void testPortValidatorTooLow() {
when(globalConfig.getOptionInt("newserver", "port")).thenReturn(-1);
instance.loadModel();
assertFalse("testPortValidatorTooLow: ", instance.isPortValid());
}
@Test
public void testPortValidatorTooHigh() {
when(globalConfig.getOptionInt("newserver", "port")).thenReturn(65536);
instance.loadModel();
assertFalse("testPortValidatorTooHigh: ", instance.isPortValid());
}
@Test
public void testPassword() {
instance.loadModel();
assertEquals("testPassword: ", Optional.ofNullable("password"), instance.getPassword());
instance.setPassword(Optional.ofNullable("test"));
assertEquals("testPassword: ", Optional.ofNullable("test"), instance.getPassword());
}
@Test
public void testPasswordValidatorValid() {
when(globalConfig.getOption("newserver", "password")).thenReturn("password");
instance.loadModel();
assertTrue("testPasswordValidatorValid: ", instance.isPortValid());
}
@Test
public void testSSL() {
instance.loadModel();
assertTrue("testSSL: ", instance.getSSL());
instance.setSSL(false);
assertFalse("testSSL: ", instance.getSSL());
}
@Test
public void testSaveAsDefault() {
instance.loadModel();
assertFalse("testSaveAsDefault:", instance.getSaveAsDefault());
instance.setSaveAsDefault(true);
assertTrue("testSaveAsDefault:", instance.getSaveAsDefault());
}
@Test
public void testIsSaveAllowedValid() {
when(globalConfig.getOption("newserver", "hostname")).thenReturn("hostname");
instance.loadModel();
assertTrue("testIsSaveAllowedValid: ", instance.isSaveAllowed());
}
@Test
public void testIsSaveAllowedInvalidHostname() {
when(globalConfig.getOption("newserver", "hostname")).thenReturn("~!£$^£$%^&");
instance.loadModel();
assertFalse("testIsSaveAllowedInvalidHostname: ", instance.isSaveAllowed());
}
@Test
public void testIsSaveAllowedInvalidPort() {
when(globalConfig.getOption("newserver", "hostname")).thenReturn("-1");
instance.loadModel();
assertFalse("testIsSaveAllowedInvalidPort: ", instance.isSaveAllowed());
}
@Test
public void testSaveSaveDefaults() {
instance.loadModel();
instance.setSaveAsDefault(true);
instance.save();
verify(userConfig).setOption("newserver", "hostname", "hostname");
verify(userConfig).setOption("newserver", "port", 1111);
verify(userConfig).setOption("newserver", "password", "password");
verify(userConfig).setOption("newserver", "ssl", true);
}
@Test
public void testSaveNotDefaults() {
instance.loadModel();
instance.setSaveAsDefault(false);
instance.save();
verify(userConfig, never()).setOption("newserver", "hostname", "hostname");
verify(userConfig, never()).setOption("newserver", "port", 1111);
verify(userConfig, never()).setOption("newserver", "password", "password");
verify(userConfig, never()).setOption("newserver", "ssl", true);
}
@Test
public void testSaveConnectWithoutProfile() throws URISyntaxException {
instance.loadModel();
instance.save();
verify(connectionManager).connectToAddress(new URI("ircs://password@hostname:1111"));
verify(connectionManager, never()).connectToAddress(any(URI.class), any(Profile.class));
}
@Test
public void testSaveConnectWithProfile() throws URISyntaxException {
instance.loadModel();
instance.setSelectedProfile(Optional.ofNullable(profile1));
instance.save();
verify(connectionManager, never()).connectToAddress(any(URI.class));
verify(connectionManager).connectToAddress(new URI("ircs://password@hostname:1111"),
profile1);
}
@Test
public void testAddConfigProvider() {
when(profileManager.getProfiles()).thenReturn(Lists.newArrayList(profile1));
instance.loadModel();
assertEquals("testAddConfigProvider:", Lists.newArrayList(profile1),
instance.getProfileList());
instance.profileAdded(new ProfileAddedEvent(profile2));
assertEquals("testAddConfigProvider:", Lists.newArrayList(profile1, profile2),
instance.getProfileList());
}
@Test
public void testRemoveConfigProvider() {
when(profileManager.getProfiles()).thenReturn(Lists.newArrayList(profile1, profile2));
instance.loadModel();
assertEquals("testRemoveConfigProvider:", Lists.newArrayList(profile1, profile2),
instance.getProfileList());
instance.profileDeleted(new ProfileDeletedEvent(profile2));
assertEquals("testRemoveConfigProvider:", Lists.newArrayList(profile1),
instance.getProfileList());
}
@Test
public void testRemoveConfigProviderSelectedProfile() {
when(profileManager.getProfiles()).thenReturn(Lists.newArrayList(profile1, profile2));
instance.loadModel();
instance.setSelectedProfile(Optional.ofNullable(profile2));
assertEquals("testRemoveConfigProviderSelectedProfile:",
Lists.newArrayList(profile1, profile2),
instance.getProfileList());
assertEquals("testRemoveConfigProviderSelectedProfile:", Optional.ofNullable(profile2),
instance.getSelectedProfile());
instance.profileDeleted(new ProfileDeletedEvent(profile2));
assertEquals("testRemoveConfigProviderSelectedProfile:", Lists.newArrayList(profile1),
instance.getProfileList());
assertEquals("testRemoveConfigProviderSelectedProfile:", Optional.<Profile>empty(),
instance.getSelectedProfile());
}
@Test
public void testListenerSelectedProfileChanged() {
instance.loadModel();
assertEquals("testListenerSelectedProfileChanged: ", Optional.<Profile>empty(),
instance.getSelectedProfile());
instance.addListener(listener);
instance.setSelectedProfile(Optional.ofNullable(profile1));
assertEquals("testListenerSelectedProfileChanged: ", Optional.ofNullable(profile1),
instance.getSelectedProfile());
verify(listener).selectedProfileChanged(Optional.<Profile>empty(),
Optional.ofNullable(profile1));
}
@Test
public void testListenerProfileListChangedRemoved() {
instance.loadModel();
instance.addListener(listener);
assertEquals("testListenerProfileListChangedRemoved: ",
Lists.newArrayList(profile1, profile2), instance.getProfileList());
instance.profileDeleted(new ProfileDeletedEvent(profile2));
assertEquals("testListenerProfileListChangedRemoved:", Lists.newArrayList(profile1),
instance.getProfileList());
verify(listener).profileListChanged(Lists.newArrayList(profile1));
}
@Test
public void testListenerProfileListChangedAdded() {
when(profileManager.getProfiles()).thenReturn(Lists.newArrayList(profile1));
instance.loadModel();
instance.addListener(listener);
assertEquals("testListenerProfileListChangedAdded: ", Lists.newArrayList(profile1),
instance.getProfileList());
instance.profileAdded(new ProfileAddedEvent(profile2));
assertEquals("testListenerProfileListChangedAdded:", Lists.newArrayList(profile1, profile2),
instance.getProfileList());
verify(listener).profileListChanged(Lists.newArrayList(profile1, profile2));
}
@Test
public void testListenerServerDetailsChangedPort() {
instance.loadModel();
instance.addListener(listener);
instance.setPort(Optional.ofNullable(9999));
verify(listener).serverDetailsChanged(Optional.ofNullable("hostname"),
Optional.ofNullable(9999), Optional.ofNullable("password"), true, false);
}
@Test
public void testListenerServerDetailsChangedPassword() {
instance.loadModel();
instance.addListener(listener);
instance.setPassword(Optional.ofNullable("password-test"));
verify(listener).serverDetailsChanged(Optional.ofNullable("hostname"),
Optional.ofNullable(1111), Optional.ofNullable("password-test"), true, false);
}
@Test
public void testListenerServerDetailsChangedSSL() {
instance.loadModel();
instance.addListener(listener);
instance.setSSL(false);
verify(listener).serverDetailsChanged(Optional.ofNullable("hostname"),
Optional.ofNullable(1111), Optional.ofNullable("password"), false, false);
}
@Test
public void testListenerServerDetailsChangedSaveAsDefault() {
instance.loadModel();
instance.addListener(listener);
instance.setSaveAsDefault(true);
verify(listener).serverDetailsChanged(Optional.ofNullable("hostname"),
Optional.ofNullable(1111), Optional.ofNullable("password"), true, true);
}
@Test
public void testRemoveListener() {
instance.loadModel();
instance.addListener(listener);
instance.setSaveAsDefault(true);
verify(listener).serverDetailsChanged(Optional.ofNullable("hostname"),
Optional.ofNullable(1111), Optional.ofNullable("password"), true, true);
instance.removeListener(listener);
instance.setHostname(Optional.ofNullable("test"));
verify(listener, never()).serverDetailsChanged(Optional.ofNullable("test"),
Optional.ofNullable(1111), Optional.ofNullable("password"), true, false);
}
@Test
public void testSaveDefaults() throws URISyntaxException {
instance.loadModel();
instance.setSelectedProfile(Optional.ofNullable(profile1));
instance.setSaveAsDefault(true);
instance.save();
verify(userConfig).setOption("newserver", "hostname", "hostname");
verify(userConfig).setOption("newserver", "port", 1111);
verify(userConfig).setOption("newserver", "password", "password");
verify(userConfig).setOption("newserver", "ssl", true);
}
@Test
public void testNoSaveDefaults() throws URISyntaxException {
instance.loadModel();
instance.setSelectedProfile(Optional.ofNullable(profile1));
instance.setSaveAsDefault(false);
instance.save();
verify(userConfig, never()).setOption("newserver", "hostname", "hostname");
verify(userConfig, never()).setOption("newserver", "port", 1111);
verify(userConfig, never()).setOption("newserver", "password", "password");
verify(userConfig, never()).setOption("newserver", "ssl", true);
}
}
|
package com.creativemd.creativecore.core;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.MinecraftForge;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.creativemd.creativecore.api.nei.NEIRecipeInfoHandler;
import com.creativemd.creativecore.common.entity.EntitySit;
import com.creativemd.creativecore.common.event.TickHandler;
import com.creativemd.creativecore.common.gui.GuiHandler;
import com.creativemd.creativecore.common.packet.ContainerControlUpdatePacket;
import com.creativemd.creativecore.common.packet.CreativeCorePacket;
import com.creativemd.creativecore.common.packet.CreativeMessageHandler;
import com.creativemd.creativecore.common.packet.GuiControlPacket;
import com.creativemd.creativecore.common.packet.GuiLayerPacket;
import com.creativemd.creativecore.common.packet.GuiUpdatePacket;
import com.creativemd.creativecore.common.packet.OpenGuiPacket;
import com.creativemd.creativecore.common.packet.PacketReciever;
import com.creativemd.creativecore.common.packet.TEContainerPacket;
import com.creativemd.creativecore.common.utils.stack.StackInfo;
import com.creativemd.creativecore.common.utils.string.StringUtils;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.relauncher.Side;
@Mod(modid = CreativeCore.modid, version = CreativeCore.version, name = "CreativeCore")
public class CreativeCore {
@Instance(CreativeCore.modid)
public static CreativeCore instance = new CreativeCore();
public static final String modid = "creativecore";
public static final String version = "1.3.14";
public static final Logger logger = LogManager.getLogger(modid);
public static SimpleNetworkWrapper network;
public static TickHandler tickHandler = new TickHandler();
@EventHandler
public void Init(FMLInitializationEvent event)
{
network = NetworkRegistry.INSTANCE.newSimpleChannel("CreativeMDPacket");
network.registerMessage(PacketReciever.class, CreativeMessageHandler.class, 0, Side.CLIENT);
network.registerMessage(PacketReciever.class, CreativeMessageHandler.class, 0, Side.SERVER);
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
EntityRegistry.registerModEntity(EntitySit.class, "Sit", 0, this, 250, 250, true);
//Init Packets
CreativeCorePacket.registerPacket(GuiUpdatePacket.class, "guiupdatepacket");
CreativeCorePacket.registerPacket(GuiControlPacket.class, "guicontrolpacket");
CreativeCorePacket.registerPacket(ContainerControlUpdatePacket.class, "containercontrolpacket");
CreativeCorePacket.registerPacket(TEContainerPacket.class, "TEContainer");
CreativeCorePacket.registerPacket(GuiLayerPacket.class, "guilayerpacket");
CreativeCorePacket.registerPacket(OpenGuiPacket.class, "opengui");
FMLCommonHandler.instance().bus().register(tickHandler);
StackInfo.registerDefaultLoaders();
if(Loader.isModLoaded("NotEnoughItems") && FMLCommonHandler.instance().getEffectiveSide().isClient())
NEIRecipeInfoHandler.load();
}
}
|
package io.advantageous.qbit.service;
import io.advantageous.boon.core.Str;
import io.advantageous.qbit.queue.QueueCallBackHandler;
import io.advantageous.qbit.reactive.Reactor;
import io.advantageous.qbit.service.stats.StatsCollector;
import io.advantageous.qbit.util.Timer;
import java.util.HashMap;
public abstract class BaseService implements QueueCallBackHandler{
protected final StatsCollector statsCollector;
protected final Reactor reactor;
protected final Timer timer;
private final String statKeyPrefix;
protected long time;
private final HashMap<String, String> statNameMap;
public BaseService(Reactor reactor, Timer timer, final StatsCollector statsCollector) {
this.statsCollector = statsCollector;
this.reactor = reactor;
this.timer = timer;
statKeyPrefix = Str.underBarCase(this.getClass().getSimpleName()).replace('_', '.') + ".";
statNameMap = new HashMap<>();
}
public BaseService(String statKeyPrefix, Reactor reactor, Timer timer, final StatsCollector statsCollector) {
this.statsCollector = statsCollector;
this.reactor = reactor;
this.timer = timer;
this.statKeyPrefix = statKeyPrefix;
statNameMap = new HashMap<>();
}
/** Prefixes the stats key with the stat key prefix, and then calls statsCollector.recordLevel.
*
* @param statKey statKey
* @param level level
*/
protected void recordLevel(final String statKey, final long level) {
final String longKey = getActualStatKey(statKey);
statsCollector.recordLevel(longKey, level);
}
/** Prefixes the stats key with the stat key prefix, and then calls statsCollector.recordCount.
*
* @param statKey statKey
* @param count count
*/
protected void recordCount(final String statKey, final long count) {
final String longKey = getActualStatKey(statKey);
statsCollector.recordCount(longKey, count);
}
/** Prefixes the stats key with the stat key prefix, and then calls statsCollector.recordTiming.
*
* @param statKey statKey
* @param timeSpan timeSpan
*/
protected void recordTime(String statKey, long timeSpan) {
final String longKey = getActualStatKey(statKey);
statsCollector.recordTiming(longKey, timeSpan);
}
private String getActualStatKey(String statKey) {
String longKey = statNameMap.get(statKey);
if (longKey == null) {
longKey = this.statKeyPrefix + statKey;
}
return longKey;
}
@Override
public void queueLimit() {
doProcess();
}
@Override
public void queueEmpty() {
doProcess();
}
@Override
public void queueIdle() {
doProcess();
}
private void doProcess() {
time = timer.time();
reactor.process();
process();
}
protected void process() {
}
}
|
package com.bio4j.angulillos.titan;
import java.util.stream.Stream;
import java.util.Iterator;
import java.util.Optional;
import com.bio4j.angulillos.*;
import static com.bio4j.angulillos.conversions.*;
import com.thinkaurelius.titan.core.TitanVertex;
import com.thinkaurelius.titan.core.TitanEdge;
import com.thinkaurelius.titan.core.EdgeLabel;
import com.thinkaurelius.titan.core.TitanGraph;
import com.thinkaurelius.titan.core.*;
import com.thinkaurelius.titan.core.schema.EdgeLabelMaker;
import com.thinkaurelius.titan.core.schema.VertexLabelMaker;
public interface TitanUntypedGraph extends UntypedGraph<TitanVertex,VertexLabel,TitanEdge,EdgeLabel> {
TitanGraph titanGraph();
default void commit() { titanGraph().commit(); }
default void shutdown() { titanGraph().shutdown(); }
@Override
default TitanEdge addEdge(TitanVertex from, EdgeLabel edgeType, TitanVertex to) {
return from.addEdge( edgeType, to );
}
@Override
default TitanVertex addVertex(VertexLabel type) {
return (TitanVertex) titanGraph().addVertexWithLabel(type);
}
@Override
default <V> V getPropertyV(TitanVertex vertex, String property) {
return vertex.<V>getProperty(property);
}
@Override
default <V> void setPropertyV(TitanVertex vertex, String property, V value) {
vertex.setProperty(property, value);
}
@Override
default <V> V getPropertyE(TitanEdge edge, String property) {
return edge.<V>getProperty(property);
}
@Override
default <V> void setPropertyE(TitanEdge edge, String property, V value) {
edge.setProperty(property, value);
}
@Override
default TitanVertex source(TitanEdge edge) {
return edge.getVertex(com.tinkerpop.blueprints.Direction.OUT);
}
@Override
default TitanVertex target(TitanEdge edge) {
return edge.getVertex(com.tinkerpop.blueprints.Direction.IN);
}
@Override
default Optional<Stream<TitanEdge>> out(TitanVertex vertex, EdgeLabel edgeType) {
Iterable<TitanEdge> itb = vertex.getTitanEdges(com.tinkerpop.blueprints.Direction.OUT, edgeType);
if ( itb.iterator().hasNext() ) {
return Optional.of( stream( itb ) );
} else {
return Optional.empty();
}
}
@Override
default Optional<Stream<TitanVertex>> outV(TitanVertex vertex, EdgeLabel edgeType) {
Iterable<TitanEdge> itb = vertex.getTitanEdges(com.tinkerpop.blueprints.Direction.OUT, edgeType);
if ( itb.iterator().hasNext() ) {
return Optional.of( stream( itb ).map( e -> e.getVertex(com.tinkerpop.blueprints.Direction.IN) ) );
} else {
return Optional.empty();
}
}
@Override
default Optional<Stream<TitanEdge>> in(TitanVertex vertex, EdgeLabel edgeType) {
Iterable<TitanEdge> itb = vertex.getTitanEdges(com.tinkerpop.blueprints.Direction.IN, edgeType);
if ( itb.iterator().hasNext() ) {
return Optional.of( stream( itb ) );
} else {
return Optional.empty();
}
}
@Override
default Optional<Stream<TitanVertex>> inV(TitanVertex vertex, EdgeLabel edgeType) {
Iterable<TitanEdge> itb = vertex.getTitanEdges(com.tinkerpop.blueprints.Direction.IN, edgeType);
if ( itb.iterator().hasNext() ) {
return Optional.of( stream( itb ).map( e -> e.getVertex(com.tinkerpop.blueprints.Direction.OUT) ) );
} else {
return Optional.empty();
}
}
// create types
/*
creates a key in the graph using the provided `KeyMaker` and `name` if there is no such `TitanKey` with that `name`; otherwise it returns the existing `TitanKey` with the provided `name`.
*/
default VertexLabel createOrGet(VertexLabelMaker labelMaker, String name) {
VertexLabel vertexLabel = titanGraph().getVertexLabel(labelMaker.getName());
return vertexLabel;
}
/*
creates a label in the graph using the provided `LabelMaker` and `name` if there is no such `EdgeLabel` with that `name`; otherwise it returns the existing `EdgeLabel` with the provided `name`.
*/
public default EdgeLabel createOrGet(EdgeLabelMaker labelMaker, String name) {
Boolean isNotDefined = true;
EdgeLabel label = null;
// first see if there's such a thing there
Iterator<EdgeLabel> definedLabels = titanGraph().getTypes(EdgeLabel.class).iterator();
while( definedLabels.hasNext() ) {
EdgeLabel someLabel = definedLabels.next();
if ( someLabel.getName().equals(name) ) {
isNotDefined = false;
label = someLabel;
}
}
if( isNotDefined ) {
label = labelMaker.make();
}
return label;
}
/*
Get a `KeyMaker` already configured for creating the key corresponding to a node type. You can use this for defining the corresponding `...`.
*/
default <
N extends TypedVertex<N,NT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
NT extends TypedVertex.Type<N,NT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
P extends Property<N,NT,P,V,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>, V,
G extends TypedGraph<G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
I extends TitanUntypedGraph
>
KeyMaker titanKeyMakerForVertexType(P property) {
// note how here we take the full name so that this is scoped by the node type; see `Property`.
KeyMaker keyMaker = titanGraph().makeKey(property.name())
.dataType(property.valueClass())
.indexed(com.tinkerpop.blueprints.Vertex.class)
.unique()
.single();
return keyMaker;
}
/*
create a `TitanKey` for a node type, using the default configuration. If a type with the same name is present it will be returned instead.
*/
default <
N extends TypedVertex<N,NT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
NT extends TypedVertex.Type<N,NT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
P extends Property<N,NT,P,V,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>, V,
G extends TypedGraph<G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
I extends TitanUntypedGraph
>
TitanKey titanKeyForVertexType(P property) {
return createOrGet(titanKeyMakerForVertexType(property), property.name());
}
/*
Create a LabelMaker with the minimum default for a relationship type; you should use this for defining the corresponding `TitanTitanTypedEdge.Type`. This is a `LabelMaker` so that you can define any custom signature, indexing etc.
*/
default <
// src
S extends TypedVertex<S,ST,SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
ST extends TypedVertex.Type<S,ST,SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
SG extends TypedGraph<SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
// edge
R extends TypedEdge<S,ST,SG,R,RT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel,T,TT,TG>,
RT extends TypedEdge.Type<S,ST,SG,R,RT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel,T,TT,TG>,
G extends TypedGraph<G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
I extends TitanUntypedGraph,
//tgt
T extends TypedVertex<T,TT,TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
TT extends TypedVertex.Type<T,TT,TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
TG extends TypedGraph<TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>
>
LabelMaker titanLabelMakerForEdgeType(RT relationshipType) {
LabelMaker labelMaker = titanGraph().makeLabel(relationshipType.name())
.directed();
// define the arity
switch (relationshipType.arity()) {
case oneToOne: labelMaker.oneToOne();
case oneToMany: labelMaker.oneToMany();
case manyToOne: labelMaker.manyToOne();
case manyToMany: labelMaker.manyToMany();
}
return labelMaker;
}
/*
create a `EdgeLabel` for a relationship type, using the default configuration. If a type with the same name is present it will be returned instead.
*/
default <
// src
S extends TypedVertex<S,ST,SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
ST extends TypedVertex.Type<S,ST,SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
SG extends TypedGraph<SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
// edge
R extends TypedEdge<S,ST,SG,R,RT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel,T,TT,TG>,
RT extends TypedEdge.Type<S,ST,SG,R,RT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel,T,TT,TG>,
G extends TypedGraph<G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
I extends TitanUntypedGraph,
//tgt
T extends TypedVertex<T,TT,TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
TT extends TypedVertex.Type<T,TT,TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
TG extends TypedGraph<TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>
>
EdgeLabel titanLabelForEdgeType(RT relationshipType) {
return createOrGet(titanLabelMakerForEdgeType(relationshipType), relationshipType.name());
}
default <
N extends TypedVertex<N,NT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
NT extends TypedVertex.Type<N,NT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
P extends Property<N,NT,P,V,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>, V,
G extends TypedGraph<G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
I extends TitanUntypedGraph
>
KeyMaker titanKeyMakerForVertexProperty(P property) {
return titanGraph().makeKey(property.name())
// .indexed(com.tinkerpop.blueprints.Edge.class)
.dataType(property.valueClass());
}
default <
// src
S extends TypedVertex<S,ST,SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
ST extends TypedVertex.Type<S,ST,SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
SG extends TypedGraph<SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
// edge
R extends TypedEdge<S,ST,SG,R,RT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel,T,TT,TG>,
RT extends TypedEdge.Type<S,ST,SG,R,RT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel,T,TT,TG>,
// property
P extends Property<R,RT,P,V,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>, V,
// graph
G extends TypedGraph<G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>, I extends TitanUntypedGraph,
//tgt
T extends TypedVertex<T,TT,TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
TT extends TypedVertex.Type<T,TT,TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
TG extends TypedGraph<TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>
>
KeyMaker titanKeyMakerForEdgeProperty(P property) {
return titanGraph().makeKey(property.name())
// .indexed(com.tinkerpop.blueprints.Edge.class)
.dataType(property.valueClass());
}
default <
// src
S extends TypedVertex<S,ST,SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
ST extends TypedVertex.Type<S,ST,SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
SG extends TypedGraph<SG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
// edge
R extends TypedEdge<S,ST,SG,R,RT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel,T,TT,TG>,
RT extends TypedEdge.Type<S,ST,SG,R,RT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel,T,TT,TG>,
// property
P extends Property<R,RT,P,V,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>, V,
// graph
G extends TypedGraph<G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>, I extends TitanUntypedGraph,
//tgt
T extends TypedVertex<T,TT,TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
TT extends TypedVertex.Type<T,TT,TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
TG extends TypedGraph<TG,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>
>
TitanKey titanKeyForEdgePropertySingle(P property) {
return createOrGet(titanKeyMakerForEdgeProperty(property).single(), property.name());
}
/*
create a `TitanKey` for a single vertex property, using the default configuration. If a property with the same name is present it will be returned instead.
*/
default <
N extends TypedVertex<N,NT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
NT extends TypedVertex.Type<N,NT,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
P extends Property<N,NT,P,V,G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>, V,
G extends TypedGraph<G,I,TitanVertex,TitanKey,TitanEdge,EdgeLabel>,
I extends TitanUntypedGraph
>
TitanKey titanKeyForVertexPropertySingle(P property) {
return createOrGet(titanKeyMakerForVertexProperty(property).single(), property.name());
}
}
|
package com.dailystudio.app.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import com.dailystudio.R;
import com.dailystudio.development.Logger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public abstract class SettingsFragment extends BaseIntentFragment {
public interface LayoutHolder {
View getView();
View createView(Context context, Setting setting);
void invalidate(Context context, Setting setting);
}
public final static String ACTION_SETTINGS_CHANGED =
"devbricks.intent.ACTION_SETTINGS_CHANGED";
public final static String EXTRA_SETTING_NAME =
"devbricks.intent.EXTRA_SETTING_NAME";
public static class Setting {
private Context mContext;
private String mName;
private Drawable mIcon;
private CharSequence mLabel;
private LayoutHolder mHolder;
private boolean mEnabled = true;
public Setting(Context context, String name, int iconResId, int labelResId, LayoutHolder holder) {
mContext = context.getApplicationContext();
mHolder = holder;
mName = name;
setIcon(iconResId);
setLabel(labelResId);
}
public String getName() {
return mName;
}
public void setIcon(Drawable d) {
mIcon = d;
}
public void setIcon(int iconResId) {
if (mContext == null) {
return;
}
final Resources res = mContext.getResources();
if (res == null) {
return;
}
setIcon(res.getDrawable(iconResId));
}
public void setLabel(CharSequence label) {
mLabel = label;
}
public void setLabel(int labelResId) {
if (mContext == null) {
return;
}
final Resources res = mContext.getResources();
if (res == null) {
return;
}
setLabel(res.getString(labelResId));
}
public Drawable getIcon() {
return mIcon;
}
public CharSequence getLabel() {
return mLabel;
}
public Context getContext() {
return mContext;
}
public LayoutHolder getLayoutHolder() {
return mHolder;
}
public void notifyDataChanges() {
mHandler.removeCallbacks(mNotifyDataChangesRunnable);
mHandler.postDelayed(mNotifyDataChangesRunnable, 300);
}
public void setEnabled(boolean enabled) {
mEnabled = enabled;
syncEnabled();
}
public boolean isEnabled() {
return mEnabled;
}
private void syncEnabled() {
if (mHolder != null) {
View view = mHolder.getView();
if (view != null) {
view.setVisibility(isEnabled() ?
View.VISIBLE : View.GONE);
}
}
}
@Override
public String toString() {
return String.format("%s(0x%08x, enabled = %s): label = %s, icon = %s, holder = %s",
getClass().getSimpleName(),
hashCode(),
isEnabled(),
getLabel(),
getIcon(),
getLayoutHolder());
}
protected void notifySettingsChanged() {
SettingsFragment.notifySettingChange(getContext(), getName());
}
private Runnable mNotifyDataChangesRunnable = new Runnable() {
@Override
public void run() {
if (mHolder != null) {
mHolder.invalidate(getContext(), Setting.this);
}
}
};
private Handler mHandler = new Handler();
}
public static class TextSetting extends Setting {
private CharSequence mDesc;
public TextSetting(Context context,
String name,
int iconResId,
int labelResId,
TextSettingsLayoutHolder holder) {
this(context, name, iconResId, labelResId, -1, holder);
}
public TextSetting(Context context,
String name,
int iconResId,
int labelResId,
int descResId,
TextSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
setDesc(descResId);
}
public void setDesc(CharSequence desc) {
mDesc = desc;
}
public void setDesc(int descResId) {
final Context context = getContext();
if (context == null) {
return;
}
final Resources res = context.getResources();
if (res == null) {
return;
}
if (descResId <= 0) {
setDesc(null);
return;
}
setDesc(res.getString(descResId));
}
public CharSequence getDesc() {
return mDesc;
}
}
public abstract static class EditSetting extends Setting {
public EditSetting(Context context,
String name,
int iconResId,
int labelResId,
EditSettingLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
}
public CharSequence getEditHint(Context context) {
return null;
}
public Drawable getEditButtonDrawable(Context context) {
return null;
}
public abstract CharSequence getEditText(Context context);
public abstract void setEditText(Context context, CharSequence text);
public abstract void onEditButtonClicked(Context context);
}
public class EditSettingLayoutHolder extends BaseSettingLayoutHolder {
private EditText mEditText;
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_edit, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
if (context == null) {
return;
}
final EditSetting editSetting = (EditSetting) setting;
if (mEditText != null) {
mEditText.setText(editSetting.getEditText(context));
}
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof EditSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final EditSetting editSetting = (EditSetting) setting;
final ImageView editButton = (ImageView) settingView.findViewById(
R.id.setting_edit_image_button);
if (editButton != null) {
final Drawable drawable =
((EditSetting) setting).getEditButtonDrawable(context);
if (drawable == null) {
editButton.setVisibility(View.GONE);
editButton.setOnClickListener(null);
} else {
editButton.setVisibility(View.VISIBLE);
editButton.setImageDrawable(drawable);
editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editSetting.onEditButtonClicked(context);
}
});
}
}
mEditText = (EditText) settingView.findViewById(
R.id.setting_edit);
if (mEditText != null) {
mEditText.setText(editSetting.getEditText(context));
mEditText.setHint(editSetting.getEditHint(context));
mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus == false) {
Editable editable = mEditText.getText();
if (editable != null) {
performEditTextChange(editSetting,
editable);
}
}
}
});
}
}
protected void performEditTextChange(EditSetting editSetting, CharSequence s) {
if (editSetting == null) {
return;
}
mHandler.removeMessages(MSG_TEXT_CHANGED);
TextChangeData tcd = new TextChangeData();
tcd.editSetting = editSetting;
tcd.text = s;
Message msg = Message.obtain(mHandler, MSG_TEXT_CHANGED, tcd);
mHandler.sendMessageDelayed(msg, DELAY);
}
private final static int MSG_TEXT_CHANGED = 0x1;
private final static long DELAY = 500;
private class TextChangeData {
private EditSetting editSetting;
private CharSequence text;
}
private Handler mHandler = new Handler() {
@Override
public void dispatchMessage(Message msg) {
if (msg.what == MSG_TEXT_CHANGED
&& msg.obj instanceof TextChangeData) {
TextChangeData tcd = (TextChangeData)msg.obj;
if (tcd.editSetting != null) {
tcd.editSetting.setEditText(getContext(), tcd.text);
tcd.editSetting.notifySettingsChanged();
}
return;
}
super.dispatchMessage(msg);
}
};
}
public static abstract class SwitchSetting extends TextSetting {
public SwitchSetting(Context context,
String name,
int iconResId,
int labelResId,
SwitchSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
}
public SwitchSetting(Context context,
String name,
int iconResId,
int labelResId,
int descResId,
SwitchSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, descResId, holder);
}
public abstract boolean isSwitchOn(Context context);
public abstract void setSwitchOn(Context context, boolean on);
}
public static abstract class SeekBarSetting extends Setting {
public SeekBarSetting(Context context,
String name,
int iconResId,
int labelResId,
SeekBarSettingsLayoutHolder holder) {
super(context, name, iconResId, labelResId, holder);
}
public abstract float getProgress(Context context);
public abstract void setProgress(Context context, float progress);
public abstract float getMinValue(Context context);
public abstract float getMaxValue(Context context);
public abstract float getStep(Context context);
}
public interface RadioSettingItem {
public CharSequence getLabel();
public String getId();
}
public class SimpleRadioSettingItem implements RadioSettingItem {
private Context mContext;
private int mLabelResId;
private String mItemId;
public SimpleRadioSettingItem(@NonNull Context context,
int labelResId,
@NonNull String itemId) {
mContext = context.getApplicationContext();
mLabelResId = labelResId;
mItemId = itemId;
}
@Override
public CharSequence getLabel() {
return mContext.getString(mLabelResId);
}
@Override
public String getId() {
return mItemId;
}
}
public abstract static class RadioSetting<T extends RadioSettingItem> extends Setting {
private List<T> mRadioItems = new ArrayList<>();
private Object mLock = new Object();
public RadioSetting(Context context,
String name,
int iconResId,
int labelResId,
RadioSettingsLayoutHolder holder,
T[] items) {
super(context, name, iconResId, labelResId, holder);
addItems(items);
}
public void addItem(T item) {
synchronized (mLock) {
mRadioItems.add(item);
}
notifyDataChanges();
}
public void addItems(T[] items) {
if (items == null
|| items.length <= 0) {
return;
}
synchronized (mLock) {
for (T item : items) {
mRadioItems.add(item);
}
}
notifyDataChanges();
}
public void clear() {
synchronized (mLock) {
mRadioItems.clear();
}
notifyDataChanges();
}
public T getItem(int position) {
return mRadioItems.get(position);
}
public int getItemCount() {
return mRadioItems.size();
}
public T findItemById(String itemId) {
if (TextUtils.isEmpty(itemId)) {
return null;
}
for (T item: mRadioItems) {
if (itemId.equals(item.getId())) {
return item;
}
}
return null;
}
protected abstract String getSelectedId();
protected abstract void setSelected(String selectedId);
}
public class RadioSettingsLayoutHolder<T extends RadioSettingItem> extends BaseSettingLayoutHolder {
private RadioGroup mRadioGroup;
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_radio, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
if (mRadioGroup == null) {
return;
}
mRadioGroup.removeAllViews();
if (setting instanceof RadioSetting) {
bindRadios(getContext(), mRadioGroup,
(RadioSetting)setting);
}
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof RadioSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final RadioSetting radioSetting = (RadioSetting) setting;
mRadioGroup = (RadioGroup) settingView.findViewById(
R.id.selection_group);
if (mRadioGroup != null) {
}
}
private void bindRadios(Context context,
RadioGroup radioGroup,
final RadioSetting<T> radioSetting) {
if (context == null
|| radioGroup == null
|| radioSetting == null) {
return;
}
final int N = radioSetting.getItemCount();
if (N <= 0) {
return;
}
final String selectedId = radioSetting.getSelectedId();
RadioSettingItem item;
RadioButton rb;
RadioButton[] rbs = new RadioButton[N];
for (int i = 0; i < N; i++) {
item = radioSetting.getItem(i);
rb = new RadioButton(context);
rb.setText(item.getLabel());
rb.setTextAppearance(context, R.style.SettingsText);
rb.setTag(item);
if (!TextUtils.isEmpty(selectedId)
&& selectedId.equals(item.getId())) {
rb.setChecked(true);
} else {
rb.setChecked(false);
}
rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked && compoundButton != null) {
Object o = compoundButton.getTag();
if (o instanceof RadioSettingItem) {
RadioSettingItem i = (RadioSettingItem)o;
radioSetting.setSelected(i.getId());
radioSetting.notifyDataChanges();
}
radioSetting.notifySettingsChanged();
}
}
});
mRadioGroup.addView(rb);
rbs[i] = rb;
}
}
}
public class SwitchSettingsLayoutHolder extends TextSettingsLayoutHolder {
private Switch mSwitch;
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_switch, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
if (mSwitch != null
&& setting instanceof SwitchSetting) {
final boolean switchOn =
((SwitchSetting)setting).isSwitchOn(context);
mSwitch.setChecked(switchOn);
}
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof SwitchSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final SwitchSetting switchSetting = (SwitchSetting) setting;
mSwitch = settingView.findViewById(
R.id.setting_switch);
if (mSwitch != null) {
final boolean switchOn =
switchSetting.isSwitchOn(context);
mSwitch.setChecked(switchOn);
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switchSetting.setSwitchOn(context, isChecked);
switchSetting.notifySettingsChanged();
}
});
}
}
}
public class TextSettingsLayoutHolder extends BaseSettingLayoutHolder {
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_text, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof TextSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final TextSetting textSetting = (TextSetting) setting;
TextView descView = settingView.findViewById(R.id.setting_desc);
if (descView != null) {
final CharSequence desc = textSetting.getDesc();
descView.setText(desc);
if (TextUtils.isEmpty(desc)) {
descView.setVisibility(View.GONE);
} else {
descView.setVisibility(View.VISIBLE);
}
}
View rootView = settingView.findViewById(
R.id.setting_root);
if (rootView != null) {
rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Logger.debug("clicked on text settings");
textSetting.notifySettingsChanged();
}
});
}
}
}
public class SeekBarSettingsLayoutHolder extends BaseSettingLayoutHolder {
@Override
public View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting) {
View view = layoutInflater.inflate(
R.layout.layout_setting_seek_bar, null);
bingSetting(view, setting);
return view;
}
@Override
public void invalidate(Context context, Setting setting) {
View view = getView();
if (view == null) {
return;
}
if (setting instanceof SeekBarSetting == false) {
return;
}
SeekBarSetting seekBarSetting = (SeekBarSetting)setting;
SeekBar seekBarView = (SeekBar) view.findViewById(
R.id.setting_seek_bar);
syncProgressWithSetting(getContext(), seekBarView, seekBarSetting);
}
private void syncProgressWithSetting(Context context,
SeekBar seekBar,
SeekBarSetting seekBarSetting) {
if (context == null
|| seekBar == null
|| seekBarSetting == null) {
return;
}
final float progress = seekBarSetting.getProgress(context);
final float step = seekBarSetting.getStep(context);
final float min = seekBarSetting.getMinValue(context);
final float max = seekBarSetting.getMaxValue(context);
final float prg = progress;
Logger.debug("prg = %f, [min: %f, max: %f, step: %f",
prg, min, max, step);
seekBar.setProgress(Math.round((prg - min) / step));
seekBar.setMax(Math.round((max - min) / step));
}
@Override
protected void bingSetting(View settingView, Setting setting) {
super.bingSetting(settingView, setting);
if (settingView == null
|| setting instanceof SeekBarSetting == false) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
final SeekBarSetting seekBarSetting = (SeekBarSetting) setting;
final TextView seekValView = (TextView) settingView.findViewById(
R.id.setting_seek_value);
if (seekValView != null) {
final float prg = seekBarSetting.getProgress(context);
final String prgStr = NumberFormat.getInstance().format(prg);
seekValView.setText(prgStr);
}
SeekBar seekBarView = (SeekBar) settingView.findViewById(
R.id.setting_seek_bar);
if (seekBarView != null) {
syncProgressWithSetting(getContext(), seekBarView, seekBarSetting);
seekBarView.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float prg = seekBarSetting.getMinValue(context)
+ (progress * seekBarSetting.getStep(context));
if (seekValView != null) {
seekValView.setText(NumberFormat.getInstance().format(prg));
}
seekBarSetting.setProgress(context, prg);
seekBarSetting.notifySettingsChanged();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
}
public abstract class BaseSettingLayoutHolder implements LayoutHolder {
private View mView;
@Override
final public View createView(Context context, Setting setting) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
mView = onCreateView(context, layoutInflater, setting);
bingSetting(mView, setting);
return mView;
}
@Override
public View getView() {
return mView;
}
protected void bingSetting(View settingView, Setting setting) {
if (settingView == null
|| setting == null) {
return;
}
ImageView iconView = (ImageView) settingView.findViewById(
R.id.setting_icon);
if (iconView != null) {
iconView.setImageDrawable(setting.getIcon());
}
TextView labelView = (TextView) settingView.findViewById(
R.id.setting_label);
if (labelView != null) {
labelView.setText(setting.getLabel());
}
}
protected abstract View onCreateView(Context context,
LayoutInflater layoutInflater,
Setting setting);
}
private ViewGroup mSettingsContainer;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, null);
setupViews(view);
return view;
}
private void setupViews(View fragmentView) {
if (fragmentView == null) {
return;
}
mSettingsContainer = (ViewGroup) fragmentView.findViewById(R.id.settings_container);
reloadSettings();
}
protected void reloadSettings() {
mSettingsContainer.removeAllViews();
Setting[] settings = createSettings(getContext());
if (settings != null) {
for (Setting s: settings) {
addSetting(s);
s.syncEnabled();
}
}
}
protected abstract Setting[] createSettings(Context context);
public void addSetting(Setting setting) {
Logger.debug("add setting: %s", setting);
if (setting == null) {
return;
}
Logger.debug("mSettingsContainer = %s", mSettingsContainer);
if (mSettingsContainer == null) {
return;
}
LayoutHolder lh = setting.getLayoutHolder();
if (lh == null) {
return;
}
View view = lh.createView(getContext(), setting);
if (view == null) {
return;
}
LinearLayout.LayoutParams llp =
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
Logger.debug("add settings view: %s", view);
mSettingsContainer.addView(view, llp);
}
public static void registerSettingChangesReceiver(Context context, BroadcastReceiver receiver) {
if (context == null || receiver == null) {
return;
}
IntentFilter filter = new IntentFilter(ACTION_SETTINGS_CHANGED);
try {
LocalBroadcastManager.getInstance(context)
.registerReceiver(receiver, filter);
} catch (Exception e) {
Logger.warn("could not register receiver [%s] on %s: %s",
receiver, ACTION_SETTINGS_CHANGED, e.toString());
}
}
public static void unregisterSettingChangesReceiver(Context context, BroadcastReceiver receiver) {
if (context == null || receiver == null) {
return;
}
try {
LocalBroadcastManager.getInstance(context)
.unregisterReceiver(receiver);
} catch (Exception e) {
Logger.warn("could not unregister receiver [%s] from %s: %s",
receiver, ACTION_SETTINGS_CHANGED, e.toString());
}
}
public static void notifySettingChange(Context context, String settingId) {
Intent i = new Intent(ACTION_SETTINGS_CHANGED);
i.putExtra(EXTRA_SETTING_NAME, settingId);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
}
}
|
package com.mysema.query.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.ClassUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mysema.query.Projectable;
import com.mysema.query.QueryBase;
import com.mysema.query.grammar.OrderSpecifier;
import com.mysema.query.grammar.SqlJoinMeta;
import com.mysema.query.grammar.SqlOps;
import com.mysema.query.grammar.SqlSerializer;
import com.mysema.query.grammar.types.Expr;
import com.mysema.query.grammar.types.SubQuery;
/**
* AbstractSqlQuery is the base type for SQL query implementations
*
* @author tiwe
* @version $Id$
*/
public class AbstractSqlQuery<SubType extends AbstractSqlQuery<SubType>> extends QueryBase<SqlJoinMeta,SubType> implements Projectable{
private static final Logger logger = LoggerFactory.getLogger(AbstractSqlQuery.class);
private String queryString;
private int limit, offset;
private List<Object> constants;
private final Connection conn;
protected final SqlOps ops;
private boolean forCountRow = false;
private SubQuery<SqlJoinMeta, ?>[] sq;
@SuppressWarnings("unchecked")
private SubType _this = (SubType)this;
public AbstractSqlQuery(Connection conn, SqlOps ops){
this.conn = conn;
this.ops = ops;
}
public List<Object[]> list(Expr<?> expr1, Expr<?> expr2, Expr<?>...rest){
select(expr1, expr2);
select(rest);
try {
return listMultiple();
} catch (SQLException e) {
String error = "Caught " + e.getClass().getName();
logger.error(error, e);
throw new RuntimeException(error, e);
}
}
private List<Object[]> listMultiple() throws SQLException{
String queryString = toString();
logger.debug("query : {}", queryString);
PreparedStatement stmt = conn.prepareStatement(queryString);
int counter = 1;
for (Object o : constants){
try {
set(stmt, counter++, o);
} catch (Exception e) {
String error = "Caught " + e.getClass().getName();
logger.error(error, e);
throw new RuntimeException(error, e);
}
}
ResultSet rs = stmt.executeQuery();
try{
List<Object[]> rv = new ArrayList<Object[]>();
while(rs.next()){
// TODO : take constructors into account
Object[] objects = new Object[rs.getMetaData().getColumnCount()];
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++){
objects[i] = rs.getObject(i+1);
}
rv.add(objects);
}
return rv;
}finally{
try{
rs.close();
}finally{
stmt.close();
}
}
}
public <RT> List<RT> list(Expr<RT> expr){
select(expr);
try {
return listSingle(expr);
} catch (SQLException e) {
String error = "Caught " + e.getClass().getName();
logger.error(error, e);
throw new RuntimeException(error, e);
}
}
private <RT> List<RT> listSingle(Expr<RT> expr) throws SQLException{
String queryString = toString();
logger.debug("query : {}", queryString);
PreparedStatement stmt = conn.prepareStatement(queryString);
int counter = 1;
for (Object o : constants){
try {
set(stmt, counter++,o);
} catch (Exception e) {
String error = "Caught " + e.getClass().getName();
logger.error(error, e);
throw new RuntimeException(error, e);
}
}
ResultSet rs = stmt.executeQuery();
try{
List<RT> rv = new ArrayList<RT>();
if (expr instanceof Expr.EConstructor){
Expr.EConstructor<RT> c = (Expr.EConstructor<RT>)expr;
java.lang.reflect.Constructor<RT> cc = c.getJavaConstructor();
while (rs.next()){
try {
List<Object> args = new ArrayList<Object>();
for (int i=0; i < c.getArgs().length; i++){
args.add(get(rs,i+1,c.getArgs()[i].getType()));
}
rv.add(cc.newInstance(args.toArray()));
} catch (Exception e) {
String error = "Caught " + e.getClass().getName();
logger.error(error, e);
throw new RuntimeException(error, e);
}
}
}else{
while(rs.next()){
rv.add((RT)rs.getObject(1));
}
}
return rv;
}finally{
try{
rs.close();
}finally{
stmt.close();
}
}
}
@SuppressWarnings("unchecked")
private <T> T get(ResultSet rs, int i, Class<T> type) throws Exception {
String methodName = "get"+type.getSimpleName();
if (methodName.equals("getInteger")){
methodName = "getInt";
}
// TODO : cache methods
return (T)ResultSet.class.getMethod(methodName, int.class).invoke(rs, i);
}
private void set(PreparedStatement stmt, int i, Object o) throws Exception {
Class<?> type = o.getClass();
String methodName = "set"+type.getSimpleName();
if (methodName.equals("setInteger")){
methodName = "setInt";
}
type = ClassUtils.wrapperToPrimitive(type) != null ? ClassUtils.wrapperToPrimitive(type) : type;
if (methodName.equals("setDate") && type.equals(java.util.Date.class)){
type = java.sql.Date.class;
o = new java.sql.Date(((java.util.Date)o).getTime());
}
// TODO : cache methods
PreparedStatement.class.getMethod(methodName, int.class, type).invoke(stmt, i, o);
}
@Override
public String toString(){
if (queryString == null){
queryString = buildQueryString();
}
return queryString;
}
@SuppressWarnings("unchecked")
public <RT> UnionBuilder<RT> union(SubQuery<SqlJoinMeta,RT>... sq){
if (!joins.isEmpty()) throw new IllegalArgumentException("Don't mix union and from");
this.sq = sq;
return new UnionBuilder();
}
protected SqlSerializer createSerializer(){
return new SqlSerializer(ops);
}
protected String buildQueryString() {
SqlSerializer serializer = createSerializer();
if (sq != null){
serializer.serializeUnion(select, sq, where.create(), orderBy);
}else{
serializer.serialize(select, joins, where.create(), groupBy, having.create(), orderBy, limit, offset, forCountRow);
}
constants = serializer.getConstants();
return serializer.toString();
}
private long getCount() throws SQLException{
forCountRow = true;
String queryString = toString();
logger.debug("query : {}", queryString);
System.out.println(queryString);
PreparedStatement stmt = conn.prepareStatement(queryString);
ResultSet rs = null;
try{
int counter = 1;
for (Object o : constants){
try {
set(stmt, counter++, o);
} catch (Exception e) {
String error = "Caught " + e.getClass().getName();
logger.error(error, e);
throw new RuntimeException(error, e);
}
}
rs = stmt.executeQuery();
rs.next();
long rv = rs.getLong(1);
return rv;
}finally{
try{
if (rs != null) rs.close();
}finally{
stmt.close();
}
}
}
public long count(){
try {
return getCount();
} catch (SQLException e) {
String error = "Caught " + e.getClass().getName();
logger.error(error, e);
throw new RuntimeException(error, e);
}
}
public SubType limit(int i) {
this.limit = i;
return _this;
}
public SubType offset(int o) {
this.offset = o;
return _this;
}
public class UnionBuilder<RT>{
public UnionBuilder<RT> orderBy(OrderSpecifier<?>... o) {
AbstractSqlQuery.this.orderBy(o);
return this;
}
public List<RT> list() throws SQLException {
if (sq[0].getQuery().getMetadata().getSelect().size() == 1){
return AbstractSqlQuery.this.listSingle(null);
}else{
return (List<RT>) AbstractSqlQuery.this.listMultiple();
}
}
}
public Iterator<Object[]> iterate(Expr<?> e1, Expr<?> e2, Expr<?>... rest) {
// TODO : optimize
return list(e1, e2, rest).iterator();
}
public <RT> Iterator<RT> iterate(Expr<RT> projection) {
// TODO : optimize
return list(projection).iterator();
}
public <RT> RT uniqueResult(Expr<RT> expr) {
List<RT> list = list(expr);
return !list.isEmpty() ? list.get(0) : null;
}
}
|
package com.bio4j.model.uniref.programs;
import com.bio4j.model.uniref.UniRefGraph;
import com.bio4j.model.uniref.vertices.UniRef100Cluster;
import com.bio4j.model.uniref.vertices.UniRef50Cluster;
import com.bio4j.model.uniref.vertices.UniRef90Cluster;
import com.bio4j.angulillos.UntypedGraph;
import com.ohnosequences.xml.api.model.XMLElement;
import java.io.*;
import java.util.List;
import java.util.stream.Stream;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import org.jdom2.Element;
/**
* Imports uniref(100,90,50) clusters info into Bio4j
*
* @author <a href="mailto:ppareja@era7.com">Pablo Pareja Tobes</a>
*/
public abstract class ImportUniRef<I extends UntypedGraph<RV,RVT,RE,RET>,RV,RVT,RE,RET> {
public static final String ENTRY_TAG_NAME = "entry";
private static final Logger logger = Logger.getLogger("ImportUniRef");
private static FileHandler fh;
protected abstract UniRefGraph<I,RV,RVT,RE,RET> config(String dbFolder, String propertiesFile);
public void importUniRef(String[] args) {
if (args.length != 5) {
System.out.println("This program expects the following parameters: \n"
+ "1. UniRef 100 xml filename \n"
+ "2. UniRef 90 xml filename \n"
+ "3. UniRef 50 xml filename \n"
+ "4. Bio4j DB folder \n"
+ "5. DB Properties file (.properties)");
} else {
long initTime = System.nanoTime();
File uniref100File = new File(args[0]);
File uniref90File = new File(args[1]);
File uniref50File = new File(args[2]);
String dbFolder = args[3];
String propertiesFile = args[4];
BufferedWriter statsBuff = null;
int uniref100EntryCounter =0, uniref90EntryCounter = 0, uniref50EntryCounter = 0;
logger.log(Level.INFO, "creating manager...");
UniRefGraph<I,RV,RVT,RE,RET> uniRefGraph = config(dbFolder, propertiesFile);
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("ImportUniRefTitan.log", true);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
statsBuff = new BufferedWriter(new FileWriter(new File("ImportUniRefStats.txt")));
System.out.println("Reading UniRef 100 file...");
uniref100EntryCounter = importUniRefFile(uniRefGraph, uniref100File, 100);
System.out.println("Done! :)");
System.out.println("Reading UniRef 90 file...");
uniref90EntryCounter = importUniRefFile(uniRefGraph, uniref90File, 90);
System.out.println("Done! :)");
System.out.println("Reading UniRef 50 file...");
uniref50EntryCounter = importUniRefFile(uniRefGraph, uniref50File, 50);
System.out.println("Done! :)");
} catch (Exception ex) {
logger.log(Level.SEVERE, ex.getMessage());
StackTraceElement[] trace = ex.getStackTrace();
for (StackTraceElement stackTraceElement : trace) {
logger.log(Level.SEVERE, stackTraceElement.toString());
}
} finally {
try {
uniRefGraph.raw().commit();
//closing logger file handler
fh.close();
//closing neo4j managers
uniRefGraph.raw().shutdown();
long elapsedTime = System.nanoTime() - initTime;
long elapsedSeconds = Math.round((elapsedTime / 1000000000.0));
long hours = elapsedSeconds / 3600;
long minutes = (elapsedSeconds % 3600) / 60;
long seconds = (elapsedSeconds % 3600) % 60;
statsBuff.write("Statistics for program ImportUniRefTitan:\nInput files: " +
"\nUniRef 100 file: " + uniref100File.getName() +
"\nUniRef 90 file: " + uniref90File.getName() +
"\nUniRef 50 file: " + uniref50File.getName()
+ "\nThe following number of entries was parsed:\n"
+ "UniRef 100 --> " + uniref100EntryCounter + " entries\n"
+ "UniRef 90 --> " + uniref90EntryCounter + " entries\n"
+ "UniRef 50 --> " + uniref50EntryCounter + " entries\n"
+ "The elapsed time was: " + hours + "h " + minutes + "m " + seconds + "s\n");
statsBuff.close();
} catch (Exception e) {
logger.log(Level.SEVERE, e.getMessage());
StackTraceElement[] trace = e.getStackTrace();
for (StackTraceElement stackTraceElement : trace) {
logger.log(Level.SEVERE, stackTraceElement.toString());
}
}
}
System.out.println("Program finished!! :D");
}
}
private static String getRepresentantAccession(Element elem) {
String result = null;
Element dbReference = elem.getChild("dbReference");
List<Element> properties = dbReference.getChildren("property");
for (Element prop : properties) {
if (prop.getAttributeValue("type").equals("UniProtKB accession")) {
result = prop.getAttributeValue("value");
}
}
return result;
}
private int importUniRefFile(UniRefGraph<I,RV,RVT,RE,RET> uniRefGraph,
File unirefFile,
int unirefClusterNumber) throws Exception {
StringBuilder entryStBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(unirefFile));
String line;
int entryCounter = 0;
int limitForPrintingOut = 10000;
while ((line = reader.readLine()) != null) {
if (line.trim().startsWith("<" + ENTRY_TAG_NAME)) {
while (!line.trim().startsWith("</" + ENTRY_TAG_NAME + ">")) {
entryStBuilder.append(line);
line = reader.readLine();
}
//organism last line
entryStBuilder.append(line);
XMLElement entryXMLElem = new XMLElement(entryStBuilder.toString());
entryStBuilder.delete(0, entryStBuilder.length());
String entryId = entryXMLElem.asJDomElement().getAttributeValue("id");
String updatedDate = entryXMLElem.asJDomElement().getAttributeValue("updated");
String name = entryXMLElem.asJDomElement().getChildText("name");
Element representativeMember = entryXMLElem.asJDomElement().getChild("representativeMember");
String representantAccession = getRepresentantAccession(representativeMember);
if(representantAccession != null){
if(unirefClusterNumber == 50){
UniRef50Cluster<I,RV,RVT,RE,RET> cluster = uniRefGraph.addVertex(uniRefGraph.UniRef50Cluster());
cluster.set(uniRefGraph.UniRef50Cluster().id, entryId);
cluster.set(uniRefGraph.UniRef50Cluster().updatedDate, updatedDate);
cluster.set(uniRefGraph.UniRef50Cluster().name, name);
cluster.set(uniRefGraph.UniRef50Cluster().representantAccession, representantAccession);
}else if(unirefClusterNumber == 90){
UniRef90Cluster<I,RV,RVT,RE,RET> cluster = uniRefGraph.addVertex(uniRefGraph.UniRef90Cluster());
cluster.set(uniRefGraph.UniRef90Cluster().id, entryId);
cluster.set(uniRefGraph.UniRef90Cluster().updatedDate, updatedDate);
cluster.set(uniRefGraph.UniRef90Cluster().name, name);
cluster.set(uniRefGraph.UniRef90Cluster().representantAccession, representantAccession);
}else if(unirefClusterNumber == 100){
UniRef100Cluster<I,RV,RVT,RE,RET> cluster = uniRefGraph.addVertex(uniRefGraph.UniRef100Cluster());
cluster.set(uniRefGraph.UniRef100Cluster().id, entryId);
cluster.set(uniRefGraph.UniRef100Cluster().updatedDate, updatedDate);
cluster.set(uniRefGraph.UniRef100Cluster().name, name);
cluster.set(uniRefGraph.UniRef100Cluster().representantAccession, representantAccession);
}
}else{
logger.log(Level.INFO, (entryId + " cluster does not have a valid representant value, it won't be stored... :("));
}
}
entryCounter++;
if ((entryCounter % limitForPrintingOut) == 0) {
logger.log(Level.INFO, (entryCounter + " entries parsed!!"));
uniRefGraph.raw().commit();
}
}
reader.close();
return entryCounter;
}
}
|
package com.datasift.client.stream;
import com.datasift.client.DataSiftClient;
import com.datasift.client.DataSiftConfig;
import com.datasift.client.core.Stream;
import io.higgs.ws.client.WebSocketClient;
import io.higgs.ws.client.WebSocketEventListener;
import io.higgs.ws.client.WebSocketMessage;
import io.higgs.ws.client.WebSocketStream;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.util.concurrent.GenericFutureListener;
import org.cliffc.high_scale_lib.NonBlockingHashMap;
import org.cliffc.high_scale_lib.NonBlockingHashSet;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author Courtney Robinson <courtney@crlog.info>
*/
class DataSiftConnection implements WebSocketEventListener {
protected final DataSiftConfig config;
protected final URI endpoint;
protected WebSocketStream connection;
protected int maxAllowedSubscriptions;
protected StreamEventListener streamEventListener;
protected ErrorListener errorListener;
protected short MAX_TIMEOUT = 320, currentTimeout;
protected DateTime lastSeen;
protected Map<Stream, StreamSubscription> subscriptions = new NonBlockingHashMap<>();
protected final Set<StreamSubscription> unsentSubscriptions = new NonBlockingHashSet<>();
protected Logger log = LoggerFactory.getLogger(getClass());
protected boolean handshakeCompleted;
protected DataSiftConnection(int maxAllowedSubscriptions, DataSiftConfig config, URI endpoint,
ErrorListener errorListener, StreamEventListener streamEventListener) {
this.maxAllowedSubscriptions = maxAllowedSubscriptions;
this.config = config;
this.endpoint = endpoint;
this.errorListener = errorListener;
this.streamEventListener = streamEventListener;
connect();
}
protected DateTime lastSeen() {
return lastSeen;
}
protected void setStreamEventListener(StreamEventListener streamEventListener) {
this.streamEventListener = streamEventListener;
}
protected void setErrorListener(ErrorListener errorListener) {
this.errorListener = errorListener;
}
protected synchronized boolean canTakeSubscription() {
return (unsentSubscriptions.size() + subscriptions.size()) <= maxAllowedSubscriptions;
}
protected void subscribe(final StreamSubscription subscription) {
synchronized (unsentSubscriptions) {
unsentSubscriptions.add(subscription);
}
pushUnsentSubscriptions();
}
protected synchronized void pushUnsentSubscriptions() {
for (final StreamSubscription subscription : unsentSubscriptions) {
if (connection == null || !connection.channel().isActive()) {
connect();
return;
}
if (!handshakeCompleted) {
return;
}
connection.connectFuture().syncUninterruptibly();
connection.send("{\"action\":\"subscribe\",\"hash\":\"" + subscription.stream().hash() + "\"}")
.addListener(new GenericFutureListener<ChannelFuture>() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
subscriptions.put(subscription.stream(), subscription);
unsentSubscriptions.remove(subscription);
} else {
fireError(future.cause());
subscribe(subscription);
}
}
});
}
}
protected void unsubscribe(final Stream stream) {
if (connection == null) { //if true there's no need to unsubscribe
connect();
return;
}
connection.send(" { \"action\" : \"unsubscribe\" , \"hash\": \"" + stream.hash() + "\"}");
subscriptions.remove(stream);
for (StreamSubscription subscription : unsentSubscriptions) {
if (stream.isSameAs(subscription.stream())) {
unsentSubscriptions.remove(subscription);
}
}
}
@Override
public void onConnect(ChannelHandlerContext ctx) {
synchronized (this) {
handshakeCompleted = true;
}
streamEventListener.streamOpened();
pushUnsentSubscriptions();
}
@Override
public void onClose(ChannelHandlerContext ctx, CloseWebSocketFrame frame) {
synchronized (this) {
handshakeCompleted = false;
}
streamEventListener.streamClosed();
//re-subscribe
unsentSubscriptions.addAll(subscriptions.values());
subscriptions.clear();
connect();
}
protected void closeAndReconnect() {
try {
connection.channel().close();
} finally {
connect();
}
}
protected void connect() {
if (connection != null && connection.channel().isActive()) {
return;
}
if (currentTimeout < 1) {
currentTimeout = 1;
} else {
if (config.isAutoReconnect() &&
TimeUnit.SECONDS.toMillis(currentTimeout) <= TimeUnit.SECONDS.toMillis(MAX_TIMEOUT)) {
currentTimeout *= 2;
}
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(currentTimeout));
} catch (InterruptedException ignored) {
log.info("Sleep interrupted, reconnecting");
}
}
connection = WebSocketClient.connect(endpoint, false, config.sslProtocols());
connection.subscribe(this);
connection.connectFuture().syncUninterruptibly();
}
@Override
public void onPing(ChannelHandlerContext ctx, PingWebSocketFrame frame) {
//only on ping or message should we reset the timeout
currentTimeout = 1;
lastSeen = DateTime.now();
}
@Override
public void onMessage(ChannelHandlerContext ctx, WebSocketMessage msg) {
currentTimeout = 1;
lastSeen = DateTime.now();
try {
MultiStreamInteraction mi =
DataSiftClient.MAPPER.readValue(msg.data(), MultiStreamInteraction.class);
if (mi.isDataSiftMessage()) {
fireMessage(new DataSiftMessage(mi));
} else {
if (mi.getData().get("deleted") != null) {
streamEventListener.onDelete(new DeletedInteraction(mi));
} else {
fireInteraction(mi.getHash(), new Interaction(mi.getData()));
}
}
} catch (IOException e) {
fireError(e); //unlikely but possible
}
}
@Override
public void onError(ChannelHandlerContext ctx, Throwable cause, FullHttpResponse response) {
if (cause != null) {
fireError(cause);
}
}
protected void fireInteraction(String hash, Interaction interaction) {
for (Map.Entry<Stream, StreamSubscription> e : subscriptions.entrySet()) {
if (e.getKey().isSameAs(hash)) {
e.getValue().onMessage(interaction);
}
}
}
protected void fireMessage(DataSiftMessage message) {
if (message == null) {
throw new IllegalArgumentException("Message can't be null!");
}
for (Map.Entry<Stream, StreamSubscription> e : subscriptions.entrySet()) {
if (message.hashHashes()) {
//if we have hashes then only subscriptions for each hash should be notified
for (Stream hash : message.hashes()) {
if (e.getKey().isSameAs(hash)) {
e.getValue().onDataSiftLogMessage(message);
}
}
} else {
//otherwise let everyone know
e.getValue().onDataSiftLogMessage(message);
}
}
}
protected void fireError(Throwable e) {
if (e == null) {
throw new IllegalArgumentException("Error can't be null!");
}
errorListener.exceptionCaught(e);
}
protected boolean isFor(Stream stream) {
return subscriptions.get(stream) != null;
}
}
|
package com.blogspot.nurkiewicz.lazyseq;
import java.util.Comparator;
import java.util.Map;
import java.util.function.*;
import java.util.stream.Collectors;
/**
* Quick hack for having a {@link LazySeq} with tuples that provides also some map related functions such as
* <ul>
* <li>{@link #mapKeys(java.util.function.Function)}</li>
* <li>{@link #mapValues(java.util.function.Function)}</li>
* <li>{@link #toMap()}</li>
* </ul>
*
* @author Stefan Endrullis (stefan@endrullis.de)
*/
public class LazyTupleSeq<K,V> extends LazySeq<Tuple<K,V>> {
protected final Supplier<Map<K, V>> underlyingMap;
protected final Supplier<LazySeq<Tuple<K, V>>> underlyingSeq;
protected final IntSupplier underlyingSize;
protected final boolean empty;
public LazyTupleSeq(Map<K, V> map) {
this.underlyingMap = () -> map;
this.underlyingSeq = () -> LazySeq.of(map.entrySet()).map(e -> new Tuple<>(e.getKey(), e.getValue()));
this.underlyingSize = () -> map.size();
this.empty = map.isEmpty();
}
public LazyTupleSeq(LazySeq<Tuple<K, V>> seq) {
this.underlyingMap = () -> StreamUtils.toMap(seq.stream(), t -> t._1, t -> t._2);
this.underlyingSeq = () -> seq;
this.underlyingSize = () -> seq.size(); this.empty = seq.isEmpty();
}
@Override
public Tuple<K, V> head() {
return underlyingSeq.get().head();
}
@Override
public LazySeq<Tuple<K, V>> tail() {
return underlyingSeq.get().tail();
}
@Override
protected boolean isTailDefined() {
return underlyingSeq.get().isTailDefined();
}
public <R> LazySeq<R> map(Function<? super Tuple<K, V>, ? extends R> mapper) {
return underlyingSeq.get().map(mapper);
}
@Override
public LazyTupleSeq<K, V> filter(Predicate<? super Tuple<K, V>> predicate) {
return new LazyTupleSeq<>(underlyingSeq.get().filter(predicate));
}
@Override
public <R> LazySeq<R> flatMap(Function<? super Tuple<K, V>, ? extends Iterable<? extends R>> mapper) {
return underlyingSeq.get().flatMap(mapper);
}
@Override
public int size() {
return underlyingSize.getAsInt();
}
@Override
public boolean isEmpty() {
return empty;
}
@Override
public LazyTupleSeq<K, V> sorted() {
return sorted((o1, o2) -> ((Comparable<Tuple<K, V>>) o1).compareTo(o2));
}
@Override
public LazyTupleSeq<K, V> sorted(Comparator<? super Tuple<K, V>> comparator) {
return new LazyTupleSeq<>(super.sorted(comparator));
}
@Override
public LazyTupleSeq<K, V> sortedBy(Function<Tuple<K, V>, ? extends Comparable> attribute) {
return sorted(Comparator.comparing(attribute));
}
@Override
protected LazySeq<Tuple<K, V>> takeUnsafe(long maxSize) {
return underlyingSeq.get().takeUnsafe(maxSize);
}
public <R> LazyTupleSeq<R,V> mapKeys(Function<K,R> keyMapper) {
return new LazyTupleSeq<>(map(t -> new Tuple<>(keyMapper.apply(t._1), t._2)));
}
public <R> LazyTupleSeq<K,R> mapValues(Function<V, R> valueMapper) {
return new LazyTupleSeq<>(map(t -> new Tuple<>(t._1, valueMapper.apply(t._2))));
}
public <R> LazySeq<R> map(BiFunction<K, V, R> mapper) {
return map(t -> mapper.apply(t._1, t._2));
}
public LazySeq<K> keys() {
return underlyingSeq.get().map(t -> t._1);
}
public LazySeq<V> values() {
return underlyingSeq.get().map(t -> t._2);
}
public Map<K, V> toMap() {
return underlyingMap.get();
}
}
|
package org.roaringbitmap;
public final class RealDataset {
private RealDataset() {
}
public static final String CENSUS_INCOME = "census-income";
public static final String CENSUS1881 = "census1881";
public static final String DIMENSION_008 = "dimension_008";
public static final String DIMENSION_003 = "dimension_003";
public static final String DIMENSION_033 = "dimension_033";
public static final String USCENSUS2000 = "uscensus2000";
public static final String WEATHER_SEPT_85 = "weather_sept_85";
public static final String WIKILEAKS_NOQUOTES = "wikileaks-noquotes";
public static final String CENSUS_INCOME_SRT = "census-income_srt";
public static final String CENSUS1881_SRT = "census1881_srt";
public static final String WEATHER_SEPT_85_SRT = "weather_sept_85_srt";
public static final String WIKILEAKS_NOQUOTES_SRT = "wikileaks-noquotes_srt";
public static final String[] ALL = new String[]{
CENSUS_INCOME, CENSUS1881, DIMENSION_008, DIMENSION_003,
DIMENSION_033, USCENSUS2000, WEATHER_SEPT_85, WIKILEAKS_NOQUOTES,
CENSUS_INCOME_SRT, CENSUS1881_SRT, WEATHER_SEPT_85_SRT, WIKILEAKS_NOQUOTES_SRT
};
}
|
package com.continuuity.common.metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern;
public class MetricsHelper {
private static final Logger LOG =
LoggerFactory.getLogger(MetricsHelper.class);
public enum Status {
Received, Success, BadRequest, NotFound, NoData, Error
}
private final CMetrics metrics;
private String method;
private String scope;
private Class<?> classe;
private long startTime;
private static final String METRIC_LATENCY = "latency";
private String metricNamePerQualifier;
private String metricNamePerMethod;
private String metricNamePerMethodAndScope;
private static String appendToMetric(String base, String specific) {
return base + "." + specific;
}
public MetricsHelper(Class<?> caller, CMetrics metrics,
String qualifier, String method) {
this.classe = caller;
this.metrics = metrics;
this.startTime = System.currentTimeMillis();
this.setQualifier(qualifier);
this.scope = null;
if (method != null) {
this.setMethod(method);
}
}
public MetricsHelper(Class<?> caller, CMetrics metrics, String qualifier) {
this(caller, metrics, qualifier, null);
}
public void setQualifier(String qualifier) {
this.metricNamePerQualifier = qualifier;
this.meter(this.metricNamePerQualifier, Status.Received);
}
public void setMethod(String method) {
if (method == null) {
LOG.warn("Attempt to set the method of a metrics helper to null in " +
classe.getName());
return;
}
if (this.method != null) {
LOG.warn(String.format(
"Attempt to change the method of a metrics helper in %s to %s " +
"(old method is %s)", classe.getName(), this.method, method));
}
// set the method and emit a "received" metric
this.method = method;
metricNamePerMethod = appendToMetric(metricNamePerQualifier, method);
this.meter(this.metricNamePerMethod, Status.Received);
// if the scope is set, create and emit a combined "received" metric
if (this.scope != null) {
metricNamePerMethodAndScope = appendToMetric(metricNamePerMethod, scope);
this.meter(this.metricNamePerMethodAndScope, Status.Received);
}
}
public void setScope(byte[] scope) {
setScope(new String(scope));
}
static final Pattern pattern = Pattern.compile("[:/]+");
public void setScope(String scope) {
if (scope == null) {
LOG.warn("Attempt to set the scope of a metrics helper to null in " +
classe.getName());
return;
}
if (this.scope != null) {
LOG.warn(String.format(
"Attempt to change the scope of a metrics helper in %s to %s " +
"(old scope is %s)", classe.getName(), this.scope, scope));
}
// if (scope.contains(":"))
scope = pattern.matcher(scope).replaceAll(".");
// set the scope
this.scope = scope;
// if the method is set, create and emit a combined "received" metric
if (this.method != null) {
metricNamePerMethodAndScope = appendToMetric(metricNamePerMethod, scope);
this.meter(this.metricNamePerMethodAndScope, Status.Received);
}
}
private void meter(String metric, Status status) {
meter(metric, status, null);
}
private void meter(String metric, Status status, Long millis) {
String metricWithStatus = appendToMetric(metric, status.name());
// increment qualifier[.method[.scope]].status
this.metrics.meter(metricWithStatus, 1L);
if (millis == null) return;
// record qualifier[.method[.scope]].latency
this.metrics.histogram(
appendToMetric(metric, METRIC_LATENCY), millis);
// record qualifier[.method[.scope]].status.latency
this.metrics.histogram(
appendToMetric(metricWithStatus, METRIC_LATENCY), millis);
}
public void finish(Status status) {
this.meter(metricNamePerQualifier, status, null);
long latency = System.currentTimeMillis() - startTime;
if (method != null) {
this.meter(metricNamePerMethod, status, latency);
if (scope != null) {
this.meter(metricNamePerMethodAndScope, status, latency);
}
}
}
public void success() {
finish(Status.Success);
}
public void failure() {
finish(Status.Error);
}
public static void meterError(CMetrics metrics, String qualifier) {
metrics.meter(appendToMetric(qualifier, Status.Error.name()), 1L);
}
}
|
package com.chrisfolger.needsmoredojo.core.amd;
import com.chrisfolger.needsmoredojo.testutil.MockPsiFile;
import com.intellij.psi.PsiFile;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* the *Priority tests are to check if suggested imports for some common modules come up in the expected order
*/
public class TestImportCreator
{
private ImportCreator creator;
private List<SourceLibrary> libraries;
@Before
public void setup()
{
creator = new ImportCreator();
libraries = new ArrayList<SourceLibrary>();
// libraries are guaranteed to be sorted by length
libraries.add(new SourceLibrary("dijit", "js/dijit", false));
libraries.add(new SourceLibrary("dojox", "js/dojox", false));
libraries.add(new SourceLibrary("dgrid", "js/dgrid", false));
libraries.add(new SourceLibrary("dojo", "js/dojo", false));
libraries.add(new SourceLibrary("util", "js/util", false));
}
@Test
public void testDijitLibraryPriority()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("BorderContainer.js", "js/dojox/layout"),
new MockPsiFile("BorderContainer.js", "js/dijit/layout")
};
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]), "BorderContainer", null);
assertEquals("dijit/layout/BorderContainer", choices[0]);
}
@Test
public void testFunctionalPriority()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("functional.js", "js/dojox/lang"),
new MockPsiFile("functional.js", "js/util/docscripts/tests")
};
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]), "functional", null);
assertEquals("dojox/lang/functional", choices[0]);
}
@Test
// see Issue #24 entering a module with an underscore resolves into two underscores
public void testWidgetWithUnderscoreDoesNotGetTwoUnderscoresInserted()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("_WidgetBase.js", "js/dijit")
};
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]), "_WidgetBase", null);
assertEquals("dijit/_WidgetBase", choices[0]);
}
@Test
// a little unrealistic, but let's make sure this case works anyway
public void testWidgetWithDoubleUnderscoresIsStillInsertedCorrectly()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("__WidgetBase.js", "js/dijit")
};
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]), "__WidgetBase", null);
assertEquals("dijit/__WidgetBase", choices[0]);
}
@Test
public void testDgridPriority()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("Grid.js", "js/dojox/drawing/plugins/drawing"),
new MockPsiFile("Grid.js", "js/dojox/grid"),
new MockPsiFile("Grid.js", "js/dgrid"),
new MockPsiFile("Grid.js", "js/dojox/charting/plot2d")
};
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]), "Grid", null);
assertEquals("dgrid/Grid", choices[0]);
}
@Test
public void testDojoTestPriority()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("on.js", "js/dojo/tests"),
new MockPsiFile("on.js", "js/dojo")
};
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]), "on", null);
assertEquals("dojo/on", choices[0]);
}
@Test
public void testExternalLibrary()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("StandbyWrapper.js", "C:/foo/path/website/static/js/website")
};
libraries.add(new SourceLibrary("website", "C:/foo/path/website/static/js/website", true));
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]) , "StandbyWrapper" , null);
assertEquals("website/StandbyWrapper", choices[0]);
}
@Test
public void testLibrary_withNoSourceRoot()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("Grid.js", "website/static/js/dojo/foo")
};
libraries.add(new SourceLibrary("dojo", "website/static/js", true));
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]) , "Grid", null );
assertEquals("dojo/foo/Grid", choices[0]);
}
@Test
public void testDojoLibraryPriority()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("BorderContainer.js", "js/dojox"),
new MockPsiFile("BorderContainer.js", "js/dojo")
};
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]), "BorderContainer", null);
assertEquals("dojo/BorderContainer", choices[0]);
}
@Test
public void correctDojoSourceReferenceWithExternalLibrary()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("ContentPane.js", "website/static/deps/dijit/layout")
};
libraries = new ArrayList<SourceLibrary>();
libraries.add(new SourceLibrary("dijit", "website/static/deps/dijit", true));
libraries.add(new SourceLibrary("website", "website/static/js/website", true));
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]) , "ContentPane", null );
assertEquals("dijit/layout/ContentPane", choices[0]);
}
@Test
public void testRelativePathWithExternalModule()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("StandbyWrapper.js", "C:/foo/path/website/static/js/website")
};
libraries.add(new SourceLibrary("website", "C:/foo/path/website/static/js/website", true));
PsiFile originalModule = new MockPsiFile("FooModule.js", "C:/foo/path/website/static/js/website/anotherpackage");
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]) , "StandbyWrapper" , originalModule, true);
assertEquals("../StandbyWrapper", choices[0]);
}
@Test
public void testRelativePathWithExternalModuleInSameDirectory()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("StandbyWrapper.js", "C:/foo/path/website/static/js/website")
};
libraries.add(new SourceLibrary("website", "C:/foo/path/website/static/js/website", true));
PsiFile originalModule = new MockPsiFile("FooModule.js", "C:/foo/path/website/static/js/website");
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]) , "StandbyWrapper" , originalModule, true);
assertEquals("./StandbyWrapper", choices[0]);
}
@Test
public void testRelativePathWithExternalModuleInTopLevel()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("StandbyWrapper.js", "C:/foo/path/website/static/js/website/package")
};
libraries.add(new SourceLibrary("website", "C:/foo/path/website/static/js/website", true));
PsiFile originalModule = new MockPsiFile("FooModule.js", "C:/foo/path/website/static/js/website");
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]) , "StandbyWrapper" , originalModule, true);
assertEquals("./package/StandbyWrapper", choices[0]);
}
@Test
public void testRelativePathWithExternalModuleInAnotherPackage()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("StandbyWrapper.js", "C:/foo/path/website/static/js/theroot/website/package")
};
libraries.add(new SourceLibrary("theroot", "C:/foo/path/website/static/js/theroot", true));
PsiFile originalModule = new MockPsiFile("FooModule.js", "C:/foo/path/website/static/js/theroot/other");
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]) , "StandbyWrapper" , originalModule, true);
assertEquals("../website/package/StandbyWrapper", choices[0]);
}
@Test
public void pluginIsTakenIntoAccountCorrectly()
{
PsiFile[] files = new PsiFile[] {
new MockPsiFile("text.js", "dojo")
};
libraries = new ArrayList<SourceLibrary>();
libraries.add(new SourceLibrary("dojo", "dojo", true));
String[] choices = creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]) , "text!testing", null );
assertEquals("dojo/text!testing", choices[0]);
}
@Test
public void dojoxIsChosenAsFirstLibraryForModuleInDojox()
{
SourceLibrary result = creator.getFirstLibraryThatIncludesFile("/website/static/js/dojox/drawing/plugins/drawing/Grid.js", libraries.toArray(new SourceLibrary[0]));
assertEquals("dojox", result.getName());
}
@Test
public void correctLibraryIsChosenForFile()
{
SourceLibrary result = creator.getFirstLibraryThatIncludesFile("/website/static/js/dijit/module.js", libraries.toArray(new SourceLibrary[0]));
assertEquals("dijit", result.getName());
}
@Test
public void testImportOfExternalModuleFromDojoLibrary()
{
PsiFile original = new MockPsiFile("behavior.js", "website/static/js/dojo");
PsiFile[] files = new PsiFile[] {
new MockPsiFile("MainToolbar.js", "website/static/js/website/widgets")
};
SourceLibrary website = new SourceLibrary("website", "website/static/js/website", true);
libraries.add(website);
creator.getChoicesFromFiles(files, libraries.toArray(new SourceLibrary[0]), "MainToolbar", original);
}
}
|
package com.github.mathieudebrito.translator;
import java.util.ArrayList;
import java.util.List;
public enum Language {
AUTO_DETECT(""),
AFRIKAANS("af"),
ALBANIAN("sq"),
//AMHARIC("am"),
ARABIC("ar"),
ARMENIAN("hy"),
AZERBAIJANI("az"),
BASQUE("eu"),
BELARUSIAN("be"),
BENGALI("bn"),
//BIHARI("bh"),
BULGARIAN("bg"),
BURMESE("my"),
CATALAN("ca"),
//CHEROKEE("chr"),
CHINESE("zh"),
CHINESE_SIMPLIFIED("zh-CN"),
CHINESE_TRADITIONAL("zh-TW"),
CROATIAN("hr"),
CZECH("cs"),
DANISH("da"),
//DHIVEHI("dv"),
DUTCH("nl"),
ENGLISH("en"),
ESPERANTO("eo"),
ESTONIAN("et"),
FILIPINO("tl"),
FINNISH("fi"),
FRENCH("fr"),
GALICIAN("gl"),
GEORGIAN("ka"),
GERMAN("de"),
GREEK("el"),
//GUARANI("gn"),
GUJARATI("gu"),
HEBREW("iw"),
HINDI("hi"),
HUNGARIAN("hu"),
ICELANDIC("is"),
INDONESIAN("id"),
//INUKTITUT("iu"),
IRISH("ga"),
ITALIAN("it"),
JAPANESE("ja"),
KANNADA("kn"),
KAZAKH("kk"),
KHMER("km"),
KOREAN("ko"),
//KURDISH("ku"),
//KYRGYZ("ky"),
LAOTHIAN("lo"),
LATVIAN("lv"),
LITHUANIAN("lt"),
MACEDONIAN("mk"),
MALAY("ms"),
MALAYALAM("ml"),
MALTESE("mt"),
MARATHI("mr"),
MONGOLIAN("mn"),
NEPALI("ne"),
NORWEGIAN("no"),
//ORIYA("or"),
//PASHTO("ps"),
PERSIAN("fa"),
POLISH("pl"),
PORTUGUESE("pt"),
PUNJABI("pa"),
ROMANIAN("ro"),
RUSSIAN("ru"),
//SANSKRIT("sa"),
SERBIAN("sr"),
//SINDHI("sd"),
SINHALESE("si"),
SLOVAK("sk"),
SLOVENIAN("sl"),
SPANISH("es"),
SWAHILI("sw"),
SWEDISH("sv"),
TAJIK("tg"),
TAMIL("ta"),
TAGALOG("tl"),
TELUGU("te"),
THAI("th"),
//TIBETAN("bo"),
TURKISH("tr"),
UKRANIAN("uk"),
URDU("ur"),
UZBEK("uz"),
//UIGHUR("ug"),
VIETNAMESE("vi"),
WELSH("cy"),
YIDDISH("yi");
/**
* Google's String representation of this language.
*/
private final String language;
/**
* Enum constructor.
*
* @param pLanguage The language identifier.
*/
private Language(final String pLanguage) {
language = pLanguage;
}
public static Language fromString(final String pLanguage) {
for (Language l : values()) {
if (l.toString().equals(pLanguage)) {
return l;
}
}
return null;
}
/**
* Returns the String representation of this language.
*
* @return The String representation of this language.
*/
@Override
public String toString() {
return language;
}
public static List<Language> all() {
List<Language> languageList = new ArrayList<Language>();
Language[] possibleValues = Language.values();
for (int numLanguage = 0; numLanguage < possibleValues.length; numLanguage++) {
if (!possibleValues[numLanguage].toString().isEmpty()) {
languageList.add(possibleValues[numLanguage]);
}
}
return languageList;
}
public static List<Language> toList(Language... languages) {
List<Language> languageList = new ArrayList<Language>();
for (int numLanguage = 0; numLanguage < languages.length; numLanguage++) {
languageList.add(languages[numLanguage]);
}
return languageList;
}
public static List<Language> getGooglePlayCompliantLanguages() {
List<Language> languageList = new ArrayList<Language>();
languageList.add(Language.AFRIKAANS);
languageList.add(Language.GERMAN);
languageList.add(Language.ENGLISH);
languageList.add(Language.BELARUSIAN);
languageList.add(Language.BULGARIAN);
languageList.add(Language.CATALAN);
languageList.add(Language.CHINESE_SIMPLIFIED);
languageList.add(Language.CHINESE_TRADITIONAL);
languageList.add(Language.KOREAN);
languageList.add(Language.CROATIAN);
languageList.add(Language.DANISH);
languageList.add(Language.SPANISH);
languageList.add(Language.ESTONIAN);
languageList.add(Language.FILIPINO);
languageList.add(Language.FINNISH);
languageList.add(Language.FRENCH);
languageList.add(Language.GREEK);
languageList.add(Language.HEBREW);
languageList.add(Language.HINDI);
languageList.add(Language.HUNGARIAN);
languageList.add(Language.INDONESIAN);
languageList.add(Language.ITALIAN);
languageList.add(Language.JAPANESE);
languageList.add(Language.LITHUANIAN);
languageList.add(Language.MALAY);
languageList.add(Language.NORWEGIAN);
languageList.add(Language.PERSIAN);
languageList.add(Language.POLISH);
languageList.add(Language.PORTUGUESE);
languageList.add(Language.ROMANIAN);
languageList.add(Language.SERBIAN);
languageList.add(Language.SLOVAK);
languageList.add(Language.SLOVENIAN);
languageList.add(Language.SWEDISH);
languageList.add(Language.SWAHILI);
languageList.add(Language.CZECH);
languageList.add(Language.THAI);
languageList.add(Language.TURKISH);
languageList.add(Language.UKRANIAN);
languageList.add(Language.VIETNAMESE);
return languageList;
}
}
|
package com.erlantzoniga.stormcourse.utils;
public class Constants {
public static final String TOPOLOGY_NAME = "STORM_COURSE_TOPOLOGY";
public static final String SPOUT_RANDOM_SENTENCE = "RANDOM_SENTENCE_SPOUT";
public static final String BOLT_SPLIT_SENTENCE = "SPLIT_SENTENCE_BOLT";
public static final String BOLT_WORD_COUNT = "WORD_COUNT_BOLT";
public static final String TWEET_ID = "TWEET_ID";
public static final String TWEET_TEXT = "TWEET_TEXT";
public static final String TWEET_METADATA = "TWEET_METADATA";
public static final String WORD = "WORD";
public static final String COUNT = "COUNT";
public class Configuration {
public static final String RUN_ON_LOCAL = "Storm.Topology.Local";
public static final String TOPOLOGY_WORKERS = "Storm.Topology.Workers";
}
}
|
package com.ecyrd.jspwiki.auth.login;
import java.security.Principal;
import java.util.Properties;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import junit.framework.TestCase;
import com.ecyrd.jspwiki.NoRequiredPropertyException;
import com.ecyrd.jspwiki.TestHttpServletRequest;
import com.ecyrd.jspwiki.auth.WikiPrincipal;
import com.ecyrd.jspwiki.auth.authorize.Role;
import com.ecyrd.jspwiki.auth.user.UserDatabase;
import com.ecyrd.jspwiki.auth.user.XMLUserDatabase;
public class WebContainerLoginModuleTest extends TestCase
{
UserDatabase db;
Subject subject;
public final void testLogin()
{
Principal principal = new WikiPrincipal( "Andrew Jaquith" );
Principal wrapper = new PrincipalWrapper( principal );
TestHttpServletRequest request = new TestHttpServletRequest();
request.setUserPrincipal( principal );
try
{
// Test using Principal (WebContainerLoginModule succeeds)
CallbackHandler handler = new WebContainerCallbackHandler( request, db );
LoginContext context = new LoginContext( "JSPWiki-container", subject, handler );
context.login();
Set principals = subject.getPrincipals();
assertEquals( 3, principals.size() );
assertTrue( principals.contains( wrapper ) );
assertTrue( principals.contains( Role.AUTHENTICATED ) );
assertTrue( principals.contains( Role.ALL ) );
// Test using remote user (WebContainerLoginModule succeeds)
subject = new Subject();
request = new TestHttpServletRequest();
request.setRemoteUser( "Andrew Jaquith" );
handler = new WebContainerCallbackHandler( request, db );
context = new LoginContext( "JSPWiki-container", subject, handler );
context.login();
principals = subject.getPrincipals();
assertEquals( 3, principals.size() );
assertTrue( principals.contains( wrapper ) );
assertTrue( principals.contains( Role.AUTHENTICATED ) );
assertTrue( principals.contains( Role.ALL ) );
// Test using IP address (AnonymousLoginModule succeeds)
subject = new Subject();
request = new TestHttpServletRequest();
request.setRemoteAddr( "53.33.128.9" );
handler = new WebContainerCallbackHandler( request, db );
context = new LoginContext( "JSPWiki-container", subject, handler );
context.login();
principals = subject.getPrincipals();
assertEquals( 3, principals.size() );
assertFalse( principals.contains( principal ) );
assertFalse( principals.contains( Role.AUTHENTICATED ) );
assertTrue( principals.contains( Role.ALL ) );
}
catch( LoginException e )
{
System.err.println( e.getMessage() );
assertTrue( false );
}
}
public final void testLogout()
{
Principal principal = new WikiPrincipal( "Andrew Jaquith" );
Principal wrapper = new PrincipalWrapper( principal );
TestHttpServletRequest request = new TestHttpServletRequest();
request.setUserPrincipal( principal );
try
{
CallbackHandler handler = new WebContainerCallbackHandler( request, db );
LoginContext context = new LoginContext( "JSPWiki-container", subject, handler );
context.login();
Set principals = subject.getPrincipals();
assertEquals( 3, principals.size() );
assertTrue( principals.contains( wrapper ) );
assertTrue( principals.contains( Role.AUTHENTICATED ) );
assertTrue( principals.contains( Role.ALL ) );
context.logout();
assertEquals( 0, principals.size() );
}
catch( LoginException e )
{
System.err.println( e.getMessage() );
assertTrue( false );
}
}
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception
{
Properties props = new Properties();
props.put( XMLUserDatabase.PROP_USERDATABASE, "./etc/userdatabase.xml" );
db = new XMLUserDatabase();
subject = new Subject();
try
{
db.initialize( null, props );
}
catch( NoRequiredPropertyException e )
{
System.err.println( e.getMessage() );
assertTrue( false );
}
}
}
|
package com.gmail.nossr50.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;
import org.bukkit.scheduler.BukkitRunnable;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.database.DatabaseType;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.database.UpgradeType;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.runnables.database.UUIDUpdateAsyncTask;
import com.gmail.nossr50.util.Misc;
import snaq.db.ConnectionPool;
public final class SQLDatabaseManager implements DatabaseManager {
private static final String ALL_QUERY_VERSION = "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy";
private static final String S_ALL_QUERY_STRING = "s.taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing+s.alchemy";
private String tablePrefix = Config.getInstance().getMySQLTablePrefix();
private final int POOL_FETCH_TIMEOUT = 0; // How long a method will wait for a connection. Since none are on main thread, we can safely say wait for as long as you like.
private final Map<UUID, Integer> cachedUserIDs = new HashMap<UUID, Integer>();
private ConnectionPool connectionPool;
private ReentrantLock massUpdateLock = new ReentrantLock();
protected SQLDatabaseManager() {
String connectionString = "jdbc:mysql://" + Config.getInstance().getMySQLServerName() + ":" + Config.getInstance().getMySQLServerPort() + "/" + Config.getInstance().getMySQLDatabaseName();
try {
// Force driver to load if not yet loaded
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
return;
//throw e; // aborts onEnable() Riking if you want to do this, fully implement it.
}
Properties connectionProperties = new Properties();
connectionProperties.put("user", Config.getInstance().getMySQLUserName());
connectionProperties.put("password", Config.getInstance().getMySQLUserPassword());
connectionProperties.put("autoReconnect", "true");
connectionProperties.put("cachePrepStmts", "true");
connectionProperties.put("prepStmtCacheSize", "64");
connectionProperties.put("prepStmtCacheSqlLimit", "2048");
connectionProperties.put("useServerPrepStmts", "true");
connectionPool = new ConnectionPool("mcMMO-Pool",
1 /*Minimum of one*/,
Config.getInstance().getMySQLMaxPoolSize() /*max pool size */,
Config.getInstance().getMySQLMaxConnections() /*max num connections*/,
0 /* idle timeout of connections */,
connectionString,
connectionProperties);
connectionPool.init(); // Init first connection
connectionPool.registerShutdownHook(); // Auto release on jvm exit just in case
checkStructure();
}
public void purgePowerlessUsers() {
massUpdateLock.lock();
mcMMO.p.getLogger().info("Purging powerless users...");
Connection connection = null;
Statement statement = null;
int purged = 0;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
statement = connection.createStatement();
purged = statement.executeUpdate("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
"JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
"WHERE (" + S_ALL_QUERY_STRING + ") = 0");
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
massUpdateLock.unlock();
}
mcMMO.p.getLogger().info("Purged " + purged + " users from the database.");
}
public void purgeOldUsers() {
massUpdateLock.lock();
mcMMO.p.getLogger().info("Purging inactive users older than " + (PURGE_TIME / 2630000L) + " months...");
Connection connection = null;
Statement statement = null;
int purged = 0;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
statement = connection.createStatement();
purged = statement.executeUpdate("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
"JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
"WHERE ((UNIX_TIMESTAMP() - lastlogin) > " + PURGE_TIME + ")");
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
massUpdateLock.unlock();
}
mcMMO.p.getLogger().info("Purged " + purged + " users from the database.");
}
public boolean removeUser(String playerName) {
boolean success = false;
Connection connection = null;
PreparedStatement statement = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
statement = connection.prepareStatement("DELETE FROM u, e, h, s, c " +
"USING " + tablePrefix + "users u " +
"JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
"WHERE u.user = ?");
statement.setString(1, playerName);
success = statement.executeUpdate() != 0;
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
if (success) {
Misc.profileCleanup(playerName);
}
return success;
}
public boolean saveUser(PlayerProfile profile) {
boolean success = true;
PreparedStatement statement = null;
Connection connection = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
int id = getUserID(connection, profile.getPlayerName(), profile.getUniqueId());
if (id == -1) {
id = newUser(connection, profile.getPlayerName(), profile.getUniqueId());
if (id == -1) {
return false;
}
}
statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET lastlogin = UNIX_TIMESTAMP() WHERE id = ?");
statement.setInt(1, id);
success &= (statement.executeUpdate() != 0);
statement.close();
statement = connection.prepareStatement("UPDATE " + tablePrefix + "skills SET "
+ " taming = ?, mining = ?, repair = ?, woodcutting = ?"
+ ", unarmed = ?, herbalism = ?, excavation = ?"
+ ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
+ ", fishing = ?, alchemy = ? WHERE user_id = ?");
statement.setInt(1, profile.getSkillLevel(SkillType.TAMING));
statement.setInt(2, profile.getSkillLevel(SkillType.MINING));
statement.setInt(3, profile.getSkillLevel(SkillType.REPAIR));
statement.setInt(4, profile.getSkillLevel(SkillType.WOODCUTTING));
statement.setInt(5, profile.getSkillLevel(SkillType.UNARMED));
statement.setInt(6, profile.getSkillLevel(SkillType.HERBALISM));
statement.setInt(7, profile.getSkillLevel(SkillType.EXCAVATION));
statement.setInt(8, profile.getSkillLevel(SkillType.ARCHERY));
statement.setInt(9, profile.getSkillLevel(SkillType.SWORDS));
statement.setInt(10, profile.getSkillLevel(SkillType.AXES));
statement.setInt(11, profile.getSkillLevel(SkillType.ACROBATICS));
statement.setInt(12, profile.getSkillLevel(SkillType.FISHING));
statement.setInt(13, profile.getSkillLevel(SkillType.ALCHEMY));
statement.setInt(14, id);
success &= (statement.executeUpdate() != 0);
statement.close();
statement = connection.prepareStatement("UPDATE " + tablePrefix + "experience SET "
+ " taming = ?, mining = ?, repair = ?, woodcutting = ?"
+ ", unarmed = ?, herbalism = ?, excavation = ?"
+ ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
+ ", fishing = ?, alchemy = ? WHERE user_id = ?");
statement.setInt(1, profile.getSkillXpLevel(SkillType.TAMING));
statement.setInt(2, profile.getSkillXpLevel(SkillType.MINING));
statement.setInt(3, profile.getSkillXpLevel(SkillType.REPAIR));
statement.setInt(4, profile.getSkillXpLevel(SkillType.WOODCUTTING));
statement.setInt(5, profile.getSkillXpLevel(SkillType.UNARMED));
statement.setInt(6, profile.getSkillXpLevel(SkillType.HERBALISM));
statement.setInt(7, profile.getSkillXpLevel(SkillType.EXCAVATION));
statement.setInt(8, profile.getSkillXpLevel(SkillType.ARCHERY));
statement.setInt(9, profile.getSkillXpLevel(SkillType.SWORDS));
statement.setInt(10, profile.getSkillXpLevel(SkillType.AXES));
statement.setInt(11, profile.getSkillXpLevel(SkillType.ACROBATICS));
statement.setInt(12, profile.getSkillXpLevel(SkillType.FISHING));
statement.setInt(13, profile.getSkillXpLevel(SkillType.ALCHEMY));
statement.setInt(14, id);
success &= (statement.executeUpdate() != 0);
statement.close();
statement = connection.prepareStatement("UPDATE " + tablePrefix + "cooldowns SET "
+ " mining = ?, woodcutting = ?, unarmed = ?"
+ ", herbalism = ?, excavation = ?, swords = ?"
+ ", axes = ?, blast_mining = ? WHERE user_id = ?");
statement.setLong(1, profile.getAbilityDATS(AbilityType.SUPER_BREAKER));
statement.setLong(2, profile.getAbilityDATS(AbilityType.TREE_FELLER));
statement.setLong(3, profile.getAbilityDATS(AbilityType.BERSERK));
statement.setLong(4, profile.getAbilityDATS(AbilityType.GREEN_TERRA));
statement.setLong(5, profile.getAbilityDATS(AbilityType.GIGA_DRILL_BREAKER));
statement.setLong(6, profile.getAbilityDATS(AbilityType.SERRATED_STRIKES));
statement.setLong(7, profile.getAbilityDATS(AbilityType.SKULL_SPLITTER));
statement.setLong(8, profile.getAbilityDATS(AbilityType.BLAST_MINING));
statement.setInt(9, id);
success = (statement.executeUpdate() != 0);
statement.close();
statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ? WHERE user_id = ?");
statement.setString(1, profile.getMobHealthbarType() == null ? Config.getInstance().getMobHealthbarDefault().name() : profile.getMobHealthbarType().name());
statement.setInt(2, id);
success = (statement.executeUpdate() != 0);
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
return success;
}
public List<PlayerStat> readLeaderboard(SkillType skill, int pageNumber, int statsPerPage) {
List<PlayerStat> stats = new ArrayList<PlayerStat>();
String query = skill == null ? ALL_QUERY_VERSION : skill.name().toLowerCase();
ResultSet resultSet = null;
PreparedStatement statement = null;
Connection connection = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
statement = connection.prepareStatement("SELECT " + query + ", user, NOW() FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON (user_id = id) WHERE " + query + " > 0 ORDER BY " + query + " DESC, user LIMIT ?, ?");
statement.setInt(1, (pageNumber * statsPerPage) - statsPerPage);
statement.setInt(2, statsPerPage);
resultSet = statement.executeQuery();
while (resultSet.next()) {
ArrayList<String> column = new ArrayList<String>();
for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
column.add(resultSet.getString(i));
}
stats.add(new PlayerStat(column.get(1), Integer.valueOf(column.get(0))));
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
return stats;
}
public Map<SkillType, Integer> readRank(String playerName) {
Map<SkillType, Integer> skills = new HashMap<SkillType, Integer>();
ResultSet resultSet = null;
PreparedStatement statement = null;
Connection connection = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
for (SkillType skillType : SkillType.NON_CHILD_SKILLS) {
String skillName = skillType.name().toLowerCase();
String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
"AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE user = ?)";
statement = connection.prepareStatement(sql);
statement.setString(1, playerName);
resultSet = statement.executeQuery();
resultSet.next();
int rank = resultSet.getInt("rank");
sql = "SELECT user, " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
"AND " + skillName + " = (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE user = '" + playerName + "') ORDER BY user";
resultSet.close();
statement.close();
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
skills.put(skillType, rank + resultSet.getRow());
break;
}
}
resultSet.close();
statement.close();
}
String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE " + ALL_QUERY_VERSION + " > 0 " +
"AND " + ALL_QUERY_VERSION + " > " +
"(SELECT " + ALL_QUERY_VERSION + " " +
"FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?)";
statement = connection.prepareStatement(sql);
statement.setString(1, playerName);
resultSet = statement.executeQuery();
resultSet.next();
int rank = resultSet.getInt("rank");
resultSet.close();
statement.close();
sql = "SELECT user, " + ALL_QUERY_VERSION + " " +
"FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
"WHERE " + ALL_QUERY_VERSION + " > 0 " +
"AND " + ALL_QUERY_VERSION + " = " +
"(SELECT " + ALL_QUERY_VERSION + " " +
"FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?) ORDER BY user";
statement = connection.prepareStatement(sql);
statement.setString(1, playerName);
resultSet = statement.executeQuery();
while (resultSet.next()) {
if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
skills.put(null, rank + resultSet.getRow());
break;
}
}
resultSet.close();
statement.close();
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
return skills;
}
public void newUser(String playerName, UUID uuid) {
Connection connection = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
newUser(connection, playerName, uuid);
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
private int newUser(Connection connection, String playerName, UUID uuid) {
ResultSet resultSet = null;
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("INSERT INTO " + tablePrefix + "users (user, uuid, lastlogin) VALUES (?, ?, UNIX_TIMESTAMP())", Statement.RETURN_GENERATED_KEYS);
statement.setString(1, playerName);
statement.setString(2, uuid.toString());
statement.executeUpdate();
resultSet = statement.getGeneratedKeys();
if (!resultSet.next()) {
return -1;
}
writeMissingRows(connection, resultSet.getInt(1));
return resultSet.getInt(1);
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
}
return -1;
}
@Deprecated
public PlayerProfile loadPlayerProfile(String playerName, boolean create) {
return loadPlayerProfile(playerName, null, false, true);
}
public PlayerProfile loadPlayerProfile(UUID uuid) {
return loadPlayerProfile("", uuid, false, true);
}
public PlayerProfile loadPlayerProfile(String playerName, UUID uuid, boolean create) {
return loadPlayerProfile(playerName, uuid, create, true);
}
private PlayerProfile loadPlayerProfile(String playerName, UUID uuid, boolean create, boolean retry) {
PreparedStatement statement = null;
Connection connection = null;
ResultSet resultSet = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
int id = getUserID(connection, playerName, uuid);
if (id == -1) {
// There is no such user
if (create) {
id = newUser(connection, playerName, uuid);
create = false;
if (id == -1) {
return new PlayerProfile(playerName, false);
}
} else {
return new PlayerProfile(playerName, false);
}
}
// There is such a user
writeMissingRows(connection, id);
statement = connection.prepareStatement(
"SELECT "
+ "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, "
+ "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, "
+ "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, "
+ "h.mobhealthbar, u.uuid "
+ "FROM " + tablePrefix + "users u "
+ "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
+ "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
+ "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
+ "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
+ "WHERE u.id = ?");
statement.setInt(1, id);
resultSet = statement.executeQuery();
if (resultSet.next()) {
try {
PlayerProfile profile = loadFromResult(playerName, resultSet);
resultSet.close();
statement.close();
if (!playerName.isEmpty() && !profile.getPlayerName().isEmpty()) {
statement = connection.prepareStatement(
"UPDATE `" + tablePrefix + "users` "
+ "SET user = ?, uuid = ? "
+ "WHERE id = ?");
statement.setString(1, playerName);
statement.setString(2, uuid.toString());
statement.setInt(3, id);
statement.executeUpdate();
statement.close();
}
return profile;
}
catch (SQLException e) {
}
}
resultSet.close();
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
// Problem, nothing was returned
// return unloaded profile
if (!retry) {
return new PlayerProfile(playerName, false);
}
// Retry, and abort on re-failure
return loadPlayerProfile(playerName, uuid, create, false);
}
public void convertUsers(DatabaseManager destination) {
PreparedStatement statement = null;
Connection connection = null;
ResultSet resultSet = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
statement = connection.prepareStatement(
"SELECT "
+ "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, "
+ "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, "
+ "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, "
+ "h.mobhealthbar, u.uuid "
+ "FROM " + tablePrefix + "users u "
+ "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
+ "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
+ "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
+ "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
+ "WHERE u.user = ?");
List<String> usernames = getStoredUsers();
int convertedUsers = 0;
long startMillis = System.currentTimeMillis();
for (String playerName : usernames) {
statement.setString(1, playerName);
try {
resultSet = statement.executeQuery();
resultSet.next();
destination.saveUser(loadFromResult(playerName, resultSet));
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
convertedUsers++;
Misc.printProgress(convertedUsers, progressInterval, startMillis);
}
}
catch (SQLException e) {
printErrors(e);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
public boolean saveUserUUID(String userName, UUID uuid) {
PreparedStatement statement = null;
Connection connection = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
statement = connection.prepareStatement(
"UPDATE `" + tablePrefix + "users` SET "
+ " uuid = ? WHERE user = ?");
statement.setString(1, uuid.toString());
statement.setString(2, userName);
statement.execute();
return true;
}
catch (SQLException ex) {
printErrors(ex);
return false;
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
public boolean saveUserUUIDs(Map<String, UUID> fetchedUUIDs) {
PreparedStatement statement = null;
int count = 0;
Connection connection = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET uuid = ? WHERE user = ?");
for (Map.Entry<String, UUID> entry : fetchedUUIDs.entrySet()) {
statement.setString(1, entry.getValue().toString());
statement.setString(2, entry.getKey());
statement.addBatch();
count++;
if ((count % 500) == 0) {
statement.executeBatch();
count = 0;
}
}
if (count != 0) {
statement.executeBatch();
}
return true;
}
catch (SQLException ex) {
printErrors(ex);
return false;
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
public List<String> getStoredUsers() {
ArrayList<String> users = new ArrayList<String>();
Statement statement = null;
Connection connection = null;
ResultSet resultSet = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT user FROM " + tablePrefix + "users");
while (resultSet.next()) {
users.add(resultSet.getString("user"));
}
}
catch (SQLException e) {
printErrors(e);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
return users;
}
/**
* Checks that the database structure is present and correct
*/
private void checkStructure() {
PreparedStatement statement = null;
Statement createStatement = null;
ResultSet resultSet = null;
Connection connection = null;
try {
connection = connectionPool.getConnection(POOL_FETCH_TIMEOUT);
statement = connection.prepareStatement("SELECT table_name FROM INFORMATION_SCHEMA.TABLES"
+ " WHERE table_schema = ?"
+ " AND table_name = ?");
statement.setString(1, Config.getInstance().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "users");
resultSet = statement.executeQuery();
if (!resultSet.next()) {
createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` ("
+ "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
+ "`user` varchar(40) NOT NULL,"
+ "`uuid` varchar(36) NULL DEFAULT NULL,"
+ "`lastlogin` int(32) unsigned NOT NULL,"
+ "PRIMARY KEY (`id`),"
+ "UNIQUE KEY `user` (`user`),"
+ "UNIQUE KEY `uuid` (`uuid`)) DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
createStatement.close();
}
resultSet.close();
statement.setString(1, Config.getInstance().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "huds");
resultSet = statement.executeQuery();
if (!resultSet.next()) {
createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
createStatement.close();
}
resultSet.close();
statement.setString(1, Config.getInstance().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "cooldowns");
resultSet = statement.executeQuery();
if (!resultSet.next()) {
createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
createStatement.close();
}
resultSet.close();
statement.setString(1, Config.getInstance().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "skills");
resultSet = statement.executeQuery();
if (!resultSet.next()) {
createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`fishing` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`alchemy` int(10) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
createStatement.close();
}
resultSet.close();
statement.setString(1, Config.getInstance().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "experience");
resultSet = statement.executeQuery();
if (!resultSet.next()) {
createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`fishing` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`alchemy` int(10) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
createStatement.close();
}
resultSet.close();
statement.close();
for (UpgradeType updateType : UpgradeType.values()) {
checkDatabaseStructure(connection, updateType);
}
mcMMO.p.getLogger().info("Killing orphans");
createStatement = connection.createStatement();
createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "experience`.`user_id` = `u`.`id`)");
createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "huds` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "huds`.`user_id` = `u`.`id`)");
createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "cooldowns` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "cooldowns`.`user_id` = `u`.`id`)");
createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "skills` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "skills`.`user_id` = `u`.`id`)");
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (createStatement != null) {
try {
createStatement.close();
}
catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
/**
* Check database structure for necessary upgrades.
*
* @param upgrade Upgrade to attempt to apply
*/
private void checkDatabaseStructure(Connection connection, UpgradeType upgrade) {
if (!mcMMO.getUpgradeManager().shouldUpgrade(upgrade)) {
mcMMO.p.debug("Skipping " + upgrade.name() + " upgrade (unneeded)");
return;
}
Statement statement = null;
try {
statement = connection.createStatement();
switch (upgrade) {
case ADD_FISHING:
checkUpgradeAddFishing(statement);
break;
case ADD_BLAST_MINING_COOLDOWN:
checkUpgradeAddBlastMiningCooldown(statement);
break;
case ADD_SQL_INDEXES:
checkUpgradeAddSQLIndexes(statement);
break;
case ADD_MOB_HEALTHBARS:
checkUpgradeAddMobHealthbars(statement);
break;
case DROP_SQL_PARTY_NAMES:
checkUpgradeDropPartyNames(statement);
break;
case DROP_SPOUT:
checkUpgradeDropSpout(statement);
break;
case ADD_ALCHEMY:
checkUpgradeAddAlchemy(statement);
break;
case ADD_UUIDS:
checkUpgradeAddUUIDs(statement);
return;
default:
break;
}
mcMMO.getUpgradeManager().setUpgradeCompleted(upgrade);
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
private void writeMissingRows(Connection connection, int id) {
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "experience (user_id) VALUES (?)");
statement.setInt(1, id);
statement.execute();
statement.close();
statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "skills (user_id) VALUES (?)");
statement.setInt(1, id);
statement.execute();
statement.close();
statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "cooldowns (user_id) VALUES (?)");
statement.setInt(1, id);
statement.execute();
statement.close();
statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "huds (user_id, mobhealthbar) VALUES (?, ?)");
statement.setInt(1, id);
statement.setString(2, Config.getInstance().getMobHealthbarDefault().name());
statement.execute();
statement.close();
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
private PlayerProfile loadFromResult(String playerName, ResultSet result) throws SQLException {
Map<SkillType, Integer> skills = new EnumMap<SkillType, Integer>(SkillType.class); // Skill & Level
Map<SkillType, Float> skillsXp = new EnumMap<SkillType, Float>(SkillType.class); // Skill & XP
Map<AbilityType, Integer> skillsDATS = new EnumMap<AbilityType, Integer>(AbilityType.class); // Ability & Cooldown
MobHealthbarType mobHealthbarType;
UUID uuid;
final int OFFSET_SKILLS = 0; // TODO update these numbers when the query
// changes (a new skill is added)
final int OFFSET_XP = 13;
final int OFFSET_DATS = 26;
final int OFFSET_OTHER = 38;
skills.put(SkillType.TAMING, result.getInt(OFFSET_SKILLS + 1));
skills.put(SkillType.MINING, result.getInt(OFFSET_SKILLS + 2));
skills.put(SkillType.REPAIR, result.getInt(OFFSET_SKILLS + 3));
skills.put(SkillType.WOODCUTTING, result.getInt(OFFSET_SKILLS + 4));
skills.put(SkillType.UNARMED, result.getInt(OFFSET_SKILLS + 5));
skills.put(SkillType.HERBALISM, result.getInt(OFFSET_SKILLS + 6));
skills.put(SkillType.EXCAVATION, result.getInt(OFFSET_SKILLS + 7));
skills.put(SkillType.ARCHERY, result.getInt(OFFSET_SKILLS + 8));
skills.put(SkillType.SWORDS, result.getInt(OFFSET_SKILLS + 9));
skills.put(SkillType.AXES, result.getInt(OFFSET_SKILLS + 10));
skills.put(SkillType.ACROBATICS, result.getInt(OFFSET_SKILLS + 11));
skills.put(SkillType.FISHING, result.getInt(OFFSET_SKILLS + 12));
skills.put(SkillType.ALCHEMY, result.getInt(OFFSET_SKILLS + 13));
skillsXp.put(SkillType.TAMING, result.getFloat(OFFSET_XP + 1));
skillsXp.put(SkillType.MINING, result.getFloat(OFFSET_XP + 2));
skillsXp.put(SkillType.REPAIR, result.getFloat(OFFSET_XP + 3));
skillsXp.put(SkillType.WOODCUTTING, result.getFloat(OFFSET_XP + 4));
skillsXp.put(SkillType.UNARMED, result.getFloat(OFFSET_XP + 5));
skillsXp.put(SkillType.HERBALISM, result.getFloat(OFFSET_XP + 6));
skillsXp.put(SkillType.EXCAVATION, result.getFloat(OFFSET_XP + 7));
skillsXp.put(SkillType.ARCHERY, result.getFloat(OFFSET_XP + 8));
skillsXp.put(SkillType.SWORDS, result.getFloat(OFFSET_XP + 9));
skillsXp.put(SkillType.AXES, result.getFloat(OFFSET_XP + 10));
skillsXp.put(SkillType.ACROBATICS, result.getFloat(OFFSET_XP + 11));
skillsXp.put(SkillType.FISHING, result.getFloat(OFFSET_XP + 12));
skillsXp.put(SkillType.ALCHEMY, result.getFloat(OFFSET_XP + 13));
// Taming - Unused - result.getInt(OFFSET_DATS + 1)
skillsDATS.put(AbilityType.SUPER_BREAKER, result.getInt(OFFSET_DATS + 2));
// Repair - Unused - result.getInt(OFFSET_DATS + 3)
skillsDATS.put(AbilityType.TREE_FELLER, result.getInt(OFFSET_DATS + 4));
skillsDATS.put(AbilityType.BERSERK, result.getInt(OFFSET_DATS + 5));
skillsDATS.put(AbilityType.GREEN_TERRA, result.getInt(OFFSET_DATS + 6));
skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, result.getInt(OFFSET_DATS + 7));
// Archery - Unused - result.getInt(OFFSET_DATS + 8)
skillsDATS.put(AbilityType.SERRATED_STRIKES, result.getInt(OFFSET_DATS + 9));
skillsDATS.put(AbilityType.SKULL_SPLITTER, result.getInt(OFFSET_DATS + 10));
// Acrobatics - Unused - result.getInt(OFFSET_DATS + 11)
skillsDATS.put(AbilityType.BLAST_MINING, result.getInt(OFFSET_DATS + 12));
try {
mobHealthbarType = MobHealthbarType.valueOf(result.getString(OFFSET_OTHER + 2));
}
catch (Exception e) {
mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
}
try {
uuid = UUID.fromString(result.getString(OFFSET_OTHER + 3));
}
catch (Exception e) {
uuid = null;
}
return new PlayerProfile(playerName, uuid, skills, skillsXp, skillsDATS, mobHealthbarType);
}
private void printErrors(SQLException ex) {
StackTraceElement element = ex.getStackTrace()[ex.getStackTrace().length - 1];
mcMMO.p.getLogger().severe("Location: " + element.getMethodName() + " " + element.getLineNumber());
mcMMO.p.getLogger().severe("SQLException: " + ex.getMessage());
mcMMO.p.getLogger().severe("SQLState: " + ex.getSQLState());
mcMMO.p.getLogger().severe("VendorError: " + ex.getErrorCode());
}
public DatabaseType getDatabaseType() {
return DatabaseType.SQL;
}
private void checkUpgradeAddAlchemy(final Statement statement) throws SQLException {
try {
statement.executeQuery("SELECT `alchemy` FROM `" + tablePrefix + "skills` LIMIT 1");
}
catch (SQLException ex) {
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Alchemy...");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD `alchemy` int(10) NOT NULL DEFAULT '0'");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "experience` ADD `alchemy` int(10) NOT NULL DEFAULT '0'");
}
}
private void checkUpgradeAddBlastMiningCooldown(final Statement statement) throws SQLException {
try {
statement.executeQuery("SELECT `blast_mining` FROM `" + tablePrefix + "cooldowns` LIMIT 1");
}
catch (SQLException ex) {
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining...");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0'");
}
}
private void checkUpgradeAddFishing(final Statement statement) throws SQLException {
try {
statement.executeQuery("SELECT `fishing` FROM `" + tablePrefix + "skills` LIMIT 1");
}
catch (SQLException ex) {
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing...");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0'");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0'");
}
}
private void checkUpgradeAddMobHealthbars(final Statement statement) throws SQLException {
try {
statement.executeQuery("SELECT `mobhealthbar` FROM `" + tablePrefix + "huds` LIMIT 1");
}
catch (SQLException ex) {
mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for mob healthbars...");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "'");
}
}
private void checkUpgradeAddSQLIndexes(final Statement statement) throws SQLException {
ResultSet resultSet = null;
try {
resultSet = statement.executeQuery("SHOW INDEX FROM `" + tablePrefix + "skills` WHERE `Key_name` LIKE 'idx\\_%'");
resultSet.last();
if (resultSet.getRow() != SkillType.NON_CHILD_SKILLS.size()) {
mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases");
for (SkillType skill : SkillType.NON_CHILD_SKILLS) {
String skill_name = skill.name().toLowerCase();
try {
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_" + skill_name + "` (`" + skill_name + "`) USING BTREE");
}
catch (SQLException ex) {
// Ignore
}
}
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
private void checkUpgradeAddUUIDs(final Statement statement) {
ResultSet resultSet = null;
try {
resultSet = statement.executeQuery("SELECT * FROM `" + tablePrefix + "users` LIMIT 1");
ResultSetMetaData rsmeta = resultSet.getMetaData();
boolean column_exists = false;
for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
if (rsmeta.getColumnName(i).equalsIgnoreCase("uuid")) {
column_exists = true;
break;
}
}
if (!column_exists) {
mcMMO.p.getLogger().info("Adding UUIDs to mcMMO MySQL user table...");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` ADD `uuid` varchar(36) NULL DEFAULT NULL");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` ADD UNIQUE INDEX `uuid` (`uuid`) USING BTREE");
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
}
new GetUUIDUpdatesRequired().runTaskLaterAsynchronously(mcMMO.p, 100); // wait until after first purge
}
private class GetUUIDUpdatesRequired extends BukkitRunnable {
public void run() {
massUpdateLock.lock();
List<String> names = new ArrayList<String>();
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
try {
connection = connectionPool.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT `user` FROM `" + tablePrefix + "users` WHERE `uuid` IS NULL");
while (resultSet.next()) {
names.add(resultSet.getString("user"));
}
} catch (SQLException ex) {
printErrors(ex);
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// Ignore
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// Ignore
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// Ignore
}
}
}
if (!names.isEmpty()) {
new UUIDUpdateAsyncTask(mcMMO.p, names).run();;
}
} finally {
massUpdateLock.unlock();
}
}
}
private void checkUpgradeDropPartyNames(final Statement statement) {
ResultSet resultSet = null;
try {
resultSet = statement.executeQuery("SELECT * FROM `" + tablePrefix + "users` LIMIT 1");
ResultSetMetaData rsmeta = resultSet.getMetaData();
boolean column_exists = false;
for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
if (rsmeta.getColumnName(i).equalsIgnoreCase("party")) {
column_exists = true;
break;
}
}
if (column_exists) {
mcMMO.p.getLogger().info("Removing party name from users table...");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "users` DROP COLUMN `party`");
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
private void checkUpgradeDropSpout(final Statement statement) {
ResultSet resultSet = null;
try {
resultSet = statement.executeQuery("SELECT * FROM `" + tablePrefix + "huds` LIMIT 1");
ResultSetMetaData rsmeta = resultSet.getMetaData();
boolean column_exists = false;
for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
if (rsmeta.getColumnName(i).equalsIgnoreCase("hudtype")) {
column_exists = true;
break;
}
}
if (column_exists) {
mcMMO.p.getLogger().info("Removing Spout HUD type from huds table...");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "huds` DROP COLUMN `hudtype`");
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
}
}
private int getUserID(final Connection connection, final String playerName, final UUID uuid) {
if (cachedUserIDs.containsKey(uuid)) {
return cachedUserIDs.get(uuid);
}
ResultSet resultSet = null;
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("SELECT id, user FROM " + tablePrefix + "users WHERE uuid = ? OR (uuid IS NULL AND user = ?)");
statement.setString(1, uuid.toString());
statement.setString(2, playerName);
resultSet = statement.executeQuery();
if (resultSet.next()) {
int id = resultSet.getInt("id");
cachedUserIDs.put(uuid, id);
return id;
}
}
catch (SQLException ex) {
printErrors(ex);
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (SQLException e) {
// Ignore
}
}
if (statement != null) {
try {
statement.close();
}
catch (SQLException e) {
// Ignore
}
}
}
return -1;
}
@Override
public void onDisable() {
mcMMO.p.debug("Releasing connection pool resource...");
connectionPool.release();
}
}
|
package com.fragmentime.markdownj.elements.list;
import com.fragmentime.markdownj.elements.Element;
public class List extends Element {
public List() {
super.setType(Element.LIST);
}
public static boolean isList(String content) {
return content != null && content.trim().matches("^((\\-|\\d+\\.|\\+|\\*) +.+)$");
}
public static int indexOfList(String content) {
int index = 0;
while (content.charAt(index) == ' ') {
index++;
}
return index;
}
@Override
public String render() {
boolean ol = true;
if (this.getData().get(0).trim().charAt(0) == '-') {
ol = false;
}
StringBuilder sb = new StringBuilder();
sb.append(ol ? "<ol>" : "<ul>").append("\n");
if (this.hasRight()) {
sb.append(this.getRight().render());
}
sb.append(ol ? "</ol>" : "</ul>").append("\n");
if (this.hasLeft()) {
sb.append(this.getLeft().render());
}
return sb.toString();
}
}
|
package org.jgroups.tests;
import org.jgroups.Address;
import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.protocols.raft.ELECTION;
import org.jgroups.protocols.raft.RAFT;
import org.jgroups.protocols.raft.REDIRECT;
import org.jgroups.protocols.raft.StateMachine;
import org.jgroups.util.Util;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.io.DataInput;
import java.io.DataOutput;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.TimeoutException;
/**
* Tests the addServer() / removeServer) functionality
* @author Bela Ban
* @since 0.2
*/
@Test(groups=Global.FUNCTIONAL,singleThreaded=true)
public class DynamicMembershipTest {
protected JChannel[] channels;
protected RAFT[] rafts;
protected Address leader;
protected static final String CLUSTER=DynamicMembershipTest.class.getSimpleName();
protected static final List<String> mbrs = Arrays.asList("A", "B", "C");
protected static final List<String> mbrs2 = Arrays.asList("A", "B", "C", "D");
protected static final List<String> mbrs3 = Arrays.asList("A", "B", "C", "D", "E");
@AfterMethod protected void destroy() {
close(true, true, channels);
}
/** Start a member not in {A,B,C} -> expects an exception */
public void testStartOfNonMember() {
JChannel non_member=null;
try {
init("X");
assert false : "Starting a non-member should throw an exception";
}
catch(Exception e) {
System.out.println("received exception as expected: " + e.toString());
}
finally {
close(true, true, non_member);
}
}
/** Starts only 1 member: no leader. Calling {@link org.jgroups.protocols.raft.RAFT#addServer(String)} must throw an exception */
public void testMembershipChangeOnNonLeader() throws Exception {
init("A");
RAFT raft=raft(channels[0]);
try {
raft.addServer("X");
assert false : "Calling RAFT.addServer() on a non-leader must throw an exception";
}
catch(Exception ex) {
System.out.println("received exception calling RAFT.addServer() on a non-leader (as expected): " + ex);
}
}
/** {A,B,C} +D +E -E -D */
public void testSimpleAddAndRemove() throws Exception {
init("A", "B", "C");
leader=leader(10000, 500, channels);
System.out.println("leader = " + leader);
assert leader != null;
waitUntilAllRaftsHaveLeader(channels);
assertSameLeader(leader, channels);
assertMembers(5000, 500, mbrs, 2, channels);
System.out.println("\nAdding server D");
RAFT raft=raft(leader);
raft.addServer("D");
assertMembers(10000, 500, mbrs2, 3, channels);
System.out.println("\nAdding server E");
raft=raft(leader);
raft.addServer("E");
assertMembers(10000, 500, mbrs3, 3, channels);
System.out.println("\nRemoving server E");
raft=raft(leader);
raft.removeServer("E");
assertMembers(10000, 500, mbrs2, 3, channels);
System.out.println("\nRemoving server D");
raft=raft(leader);
raft.removeServer("D");
assertMembers(10000, 500, mbrs, 2, channels);
}
/**
* {A,B,C} +D +E +F +G +H +I +J
*/
public void testAddServerSimultaneously()
throws Exception {
init("A", "B", "C");
leader = leader(10000, 500, channels);
System.out.println("leader = " + leader);
assert leader != null;
waitUntilAllRaftsHaveLeader(channels);
assertSameLeader(leader, channels);
assertMembers(5000, 500, mbrs, 2, channels);
final RAFT raft = raft(leader);
final List<String> newServers = Arrays.asList("D", "E", "F", "G", "H", "I", "J");
final CountDownLatch addServerLatch = new CountDownLatch(1);
final CountDownLatch completionLatch = new CountDownLatch(newServers.size());
final AtomicBoolean success = new AtomicBoolean(true);
for (String newServer : newServers) {
new Thread(() -> {
try {
addServerLatch.await();
raft.addServer(newServer);
if (raft.requestTableSize() > 1){
success.compareAndSet(true, false);
}
} catch (IllegalStateException e) {
} catch (Exception e) {
e.printStackTrace();
}
completionLatch.countDown();
}).start();
}
addServerLatch.countDown();
completionLatch.await();
assert success.get();
}
/**
* {A,B} -> -B -> {A} (A is the leader). Then addServer(D) on A. Then another addServer(E) on A. The second addServer()
* should fail as A hasn't yet committed the first.
*/
public void testAddServerOnLeaderWhichCantCommit() throws Exception {
init("A", "B");
Util.waitUntilAllChannelsHaveSameView(10000, 500, channels);
leader=leader(10000, 500, channels);
System.out.println("leader = " + leader);
assert leader != null;
// close all non-leaders
for(JChannel ch: channels)
if(!ch.getAddress().equals(leader))
close(true, true, ch);
RAFT raft=raft(leader);
// try to add D. The leader will actually add this to the log, but won't be able to commit it, so the second
// addServer() below will fail
raft.addServer("D");
assertMembers(5000, 500, mbrs2, 3, channels);
// This will fail as the first addServer(D) has not yet been committed
try {
raft.addServer("E");
assert false : "Adding server E should fail as adding server D has not yet been committed";
}
catch(Exception ex) {
System.out.println("Caught exception (as expected) trying to add another server: " + ex);
}
// Now add B and C again, so that the first addServer(D) op can commit (it now needs 3 votes to commit)
channels=Arrays.copyOf(channels, 3);
channels[2]=create("C");
for(int i=0; i < channels.length; i++) {
if(channels[i].isClosed())
channels[i]=create(String.valueOf((char)('A' + i)));
}
Util.waitUntilAllChannelsHaveSameView(10000, 500, channels);
// Now wait (and assert) for RAFT.members to be {A,B,C,D}
assertMembers(10000, 500, mbrs2, 3, channels);
// wait until everyone has committed the addServer(D) operation
assertCommitIndex(20000, 500, raft(leader).lastAppended(), channels);
// Now addServer(E) should work
raft.addServer("E");
assertMembers(10000, 500, mbrs3, 3, channels);
}
protected void init(String ... nodes) throws Exception {
channels=new JChannel[nodes.length];
rafts=new RAFT[nodes.length];
for(int i=0; i < nodes.length; i++) {
channels[i]=create(nodes[i]);
rafts[i]=raft(channels[i]);
}
}
protected JChannel create(String name) throws Exception {
RAFT raft=new RAFT().members(mbrs).raftId(name).stateMachine(new DummyStateMachine())
.logClass("org.jgroups.protocols.raft.InMemoryLog").logName(name + "-" + CLUSTER);
JChannel ch=new JChannel(Util.getTestStack(new ELECTION(), raft, new REDIRECT())).name(name);
ch.connect(CLUSTER);
return ch;
}
protected static Address leader(long timeout, long interval, JChannel ... channels) {
long target_time=System.currentTimeMillis() + timeout;
while(System.currentTimeMillis() <= target_time) {
for(JChannel ch : channels) {
if(ch.isConnected() && raft(ch).leader() != null)
return raft(ch).leader();
}
Util.sleep(interval);
}
return null;
}
protected void assertSameLeader(Address leader, JChannel ... channels) {
for(JChannel ch: channels) {
final Address raftLeader = raft(ch).leader();
assert leader.equals(raftLeader)
: String.format("expected leader to be '%s' but was '%s'", leader, raftLeader);
}
}
protected void assertMembers(long timeout, long interval, List<String> members, int expected_majority, JChannel... channels) {
long target_time=System.currentTimeMillis() + timeout;
while(System.currentTimeMillis() <= target_time) {
boolean all_ok=true;
for(JChannel ch: channels) {
if(!ch.isConnected())
continue;
RAFT raft=raft(ch);
if(!new HashSet<>(raft.members()).equals(new HashSet<>(members)))
all_ok=false;
}
if(all_ok)
break;
Util.sleep(interval);
}
for(JChannel ch: channels) {
if(!ch.isConnected())
continue;
RAFT raft=raft(ch);
System.out.printf("%s: members=%s, majority=%d\n", ch.getAddress(), raft.members(), raft.majority());
assert new HashSet<>(raft.members()).equals(new HashSet<>(members))
: String.format("expected members=%s, actual members=%s", members, raft.members());
assert raft.majority() == expected_majority
: ch.getName() + ": expected majority=" + expected_majority + ", actual=" + raft.majority();
}
}
protected void assertCommitIndex(long timeout, long interval, int expected_commit, JChannel... channels) {
long target_time=System.currentTimeMillis() + timeout;
while(System.currentTimeMillis() <= target_time) {
boolean all_ok=true;
for(JChannel ch: channels) {
RAFT raft=raft(ch);
if(expected_commit != raft.commitIndex())
all_ok=false;
}
if(all_ok)
break;
Util.sleep(interval);
}
for(JChannel ch: channels) {
RAFT raft=raft(ch);
System.out.printf("%s: members=%s, last-applied=%d, commit-index=%d\n", ch.getAddress(), raft.members(),
raft.lastAppended(), raft.commitIndex());
assert raft.commitIndex() == expected_commit : String.format("%s: last-applied=%d, commit-index=%d",
ch.getAddress(), raft.lastAppended(), raft.commitIndex());
}
}
protected void waitUntilAllRaftsHaveLeader(JChannel[] channels) throws TimeoutException {
Util.waitUntil(5000, 250, () -> Arrays.stream(channels).allMatch(ch -> raft(ch).leader() != null));
}
protected RAFT raft(Address addr) {
return raft(channel(addr));
}
protected JChannel channel(Address addr) {
for(JChannel ch: Arrays.asList(channels)) {
if(ch.getAddress() != null && ch.getAddress().equals(addr))
return ch;
}
return null;
}
protected static RAFT raft(JChannel ch) {
return (RAFT)ch.getProtocolStack().findProtocol(RAFT.class);
}
protected void close(boolean remove_log, boolean remove_snapshot, JChannel ... channels) {
for(JChannel ch: channels) {
if(ch == null)
continue;
RAFT raft=ch.getProtocolStack().findProtocol(RAFT.class);
if(remove_log)
raft.log().delete(); // remove log files after the run
if(remove_snapshot)
raft.deleteSnapshot();
Util.close(ch);
}
}
protected static class DummyStateMachine implements StateMachine {
public byte[] apply(byte[] data, int offset, int length) throws Exception {return new byte[0];}
public void readContentFrom(DataInput in) throws Exception {}
public void writeContentTo(DataOutput out) throws Exception {}
}
}
|
package com.gmail.nossr50.skills.mining;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.metadata.FixedMetadataValue;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.runnables.skills.AbilityCooldownTask;
import com.gmail.nossr50.skills.SkillManager;
import com.gmail.nossr50.skills.mining.BlastMining.Tier;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.SkillUtils;
public class MiningManager extends SkillManager{
public MiningManager(McMMOPlayer mcMMOPlayer) {
super(mcMMOPlayer, SkillType.MINING);
}
public boolean canUseDemolitionsExpertise() {
return getSkillLevel() >= BlastMining.Tier.FOUR.getLevel() && Permissions.demolitionsExpertise(getPlayer());
}
public boolean canDetonate() {
Player player = getPlayer();
return canUseBlastMining() && player.isSneaking() && player.getItemInHand().getTypeId() == BlastMining.detonatorID && Permissions.remoteDetonation(player);
}
public boolean canUseBlastMining() {
return getSkillLevel() >= BlastMining.Tier.ONE.getLevel();
}
public boolean canUseBiggerBombs() {
return getSkillLevel() >= BlastMining.Tier.TWO.getLevel() && Permissions.biggerBombs(getPlayer());
}
/**
* Process double drops & XP gain for Mining.
*
* @param blockState The {@link BlockState} to check ability activation for
*/
public void miningBlockCheck(BlockState blockState) {
Player player = getPlayer();
applyXpGain(Mining.getBlockXp(blockState));
if (!Permissions.doubleDrops(player, skill)) {
return;
}
Material material = blockState.getType();
if (material != Material.GLOWING_REDSTONE_ORE && !Config.getInstance().getDoubleDropsEnabled(skill, material)) {
return;
}
boolean silkTouch = player.getItemInHand().containsEnchantment(Enchantment.SILK_TOUCH);
for (int i = mcMMOPlayer.getAbilityMode(skill.getAbility()) ? 2 : 1; i != 0; i
if (SkillUtils.activationSuccessful(getSkillLevel(), getActivationChance(), Mining.doubleDropsMaxChance, Mining.doubleDropsMaxLevel)) {
if (silkTouch) {
Mining.handleSilkTouchDrops(blockState);
}
else {
Mining.handleMiningDrops(blockState);
}
}
}
}
/**
* Detonate TNT for Blast Mining
*/
public void remoteDetonation() {
Player player = getPlayer();
HashSet<Byte> transparentBlocks = BlastMining.generateTransparentBlockList();
Block targetBlock = player.getTargetBlock(transparentBlocks, BlastMining.MAXIMUM_REMOTE_DETONATION_DISTANCE);
if (targetBlock.getType() != Material.TNT || !SkillUtils.blockBreakSimulate(targetBlock, player, true) || !blastMiningCooldownOver()) {
return;
}
TNTPrimed tnt = player.getWorld().spawn(targetBlock.getLocation(), TNTPrimed.class);
SkillUtils.sendSkillMessage(player, AbilityType.BLAST_MINING.getAbilityPlayer(player));
player.sendMessage(LocaleLoader.getString("Mining.Blast.Boom"));
tnt.setMetadata(mcMMO.tntMetadataKey, new FixedMetadataValue(mcMMO.p, player.getName()));
tnt.setFuseTicks(0);
targetBlock.setData((byte) 0x0);
targetBlock.setType(Material.AIR);
getProfile().setSkillDATS(AbilityType.BLAST_MINING, System.currentTimeMillis());
mcMMOPlayer.setAbilityInformed(AbilityType.BLAST_MINING, false);
new AbilityCooldownTask(mcMMOPlayer, AbilityType.BLAST_MINING).runTaskLaterAsynchronously(mcMMO.p, AbilityType.BLAST_MINING.getCooldown());
}
/**
* Handler for explosion drops and XP gain.
*
* @param event Event whose explosion is being processed
*/
public void blastMiningDropProcessing(float yield, List<Block> blockList) {
List<BlockState> ores = new ArrayList<BlockState>();
List<BlockState> debris = new ArrayList<BlockState>();
int xp = 0;
float oreBonus = (float) (getOreBonus() / 100);
float debrisReduction = (float) (getDebrisReduction() / 100);
int dropMultiplier = getDropMultiplier();
float debrisYield = yield - debrisReduction;
for (Block block : blockList) {
BlockState blockState = block.getState();
if (BlockUtils.isOre(blockState)) {
ores.add(blockState);
}
else {
debris.add(blockState);
}
}
for (BlockState blockState : ores) {
if (Misc.getRandom().nextFloat() < (yield + oreBonus)) {
if (!mcMMO.getPlaceStore().isTrue(blockState)) {
xp += Mining.getBlockXp(blockState);
}
Misc.dropItem(blockState.getLocation(), blockState.getData().toItemStack(1)); // Initial block that would have been dropped
if (!mcMMO.getPlaceStore().isTrue(blockState)) {
for (int i = 1; i < dropMultiplier; i++) {
Mining.handleSilkTouchDrops(blockState); // Bonus drops - should drop the block & not the items
}
}
}
}
if (debrisYield > 0) {
for (BlockState blockState : debris) {
if (Misc.getRandom().nextFloat() < debrisYield) {
Misc.dropItems(blockState.getLocation(), blockState.getBlock().getDrops());
}
}
}
applyXpGain(xp);
}
/**
* Increases the blast radius of the explosion.
*
* @param event Event whose explosion radius is being changed
*/
public float biggerBombs(float radius) {
return (float) (radius + getBlastRadiusModifier());
}
public int processDemolitionsExpertise(int damage) {
return (int) (damage * ((100.0D - getBlastDamageModifier()) / 100.0D));
}
/**
* Gets the Blast Mining tier
*
* @return the Blast Mining tier
*/
public int getBlastMiningTier() {
int skillLevel = getSkillLevel();
for (Tier tier : Tier.values()) {
if (skillLevel >= tier.getLevel()) {
return tier.toNumerical();
}
}
return 0;
}
/**
* Gets the Blast Mining tier
*
* @return the Blast Mining tier
*/
public double getOreBonus() {
int skillLevel = getSkillLevel();
for (Tier tier : Tier.values()) {
if (skillLevel >= tier.getLevel()) {
return tier.getOreBonus();
}
}
return 0;
}
/**
* Gets the Blast Mining tier
*
* @return the Blast Mining tier
*/
public double getDebrisReduction() {
int skillLevel = getSkillLevel();
for (Tier tier : Tier.values()) {
if (skillLevel >= tier.getLevel()) {
return tier.getDebrisReduction();
}
}
return 0;
}
/**
* Gets the Blast Mining tier
*
* @return the Blast Mining tier
*/
public int getDropMultiplier() {
int skillLevel = getSkillLevel();
for (Tier tier : Tier.values()) {
if (skillLevel >= tier.getLevel()) {
return tier.getDropMultiplier();
}
}
return 0;
}
/**
* Gets the Blast Mining tier
*
* @return the Blast Mining tier
*/
public double getBlastRadiusModifier() {
int skillLevel = getSkillLevel();
for (Tier tier : Tier.values()) {
if (skillLevel >= tier.getLevel()) {
return tier.getBlastRadiusModifier();
}
}
return 0;
}
/**
* Gets the Blast Mining tier
*
* @return the Blast Mining tier
*/
public double getBlastDamageModifier() {
int skillLevel = getSkillLevel();
for (Tier tier : Tier.values()) {
if (skillLevel >= tier.getLevel()) {
return tier.getBlastDamageDecrease();
}
}
return 0;
}
private boolean blastMiningCooldownOver() {
Player player = getPlayer();
PlayerProfile profile = getProfile();
long oldTime = profile.getSkillDATS(AbilityType.BLAST_MINING) * Misc.TIME_CONVERSION_FACTOR;
int cooldown = AbilityType.BLAST_MINING.getCooldown();
if (!SkillUtils.cooldownOver(oldTime, cooldown, player)) {
player.sendMessage(LocaleLoader.getString("Skills.TooTired", SkillUtils.calculateTimeLeft(oldTime, cooldown, player)));
return false;
}
return true;
}
}
|
package org.jfree.data.time.ohlc.junit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.DatasetChangeListener;
import org.jfree.data.time.TimePeriodAnchor;
import org.jfree.data.time.Year;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;
/**
* Tests for the {@link OHLCSeriesCollectionTests} class.
*/
public class OHLCSeriesCollectionTests extends TestCase
implements DatasetChangeListener {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(OHLCSeriesCollectionTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public OHLCSeriesCollectionTests(String name) {
super(name);
}
/**
* Confirm that the equals method can distinguish all the required fields.
*/
public void testEquals() {
OHLCSeriesCollection c1 = new OHLCSeriesCollection();
OHLCSeriesCollection c2 = new OHLCSeriesCollection();
assertEquals(c1, c2);
// add a series
OHLCSeries s1 = new OHLCSeries("Series");
s1.add(new Year(2006), 1.0, 1.1, 1.2, 1.3);
c1.addSeries(s1);
assertFalse(c1.equals(c2));
OHLCSeries s2 = new OHLCSeries("Series");
s2.add(new Year(2006), 1.0, 1.1, 1.2, 1.3);
c2.addSeries(s2);
assertTrue(c1.equals(c2));
// add an empty series
c1.addSeries(new OHLCSeries("Empty Series"));
assertFalse(c1.equals(c2));
c2.addSeries(new OHLCSeries("Empty Series"));
assertTrue(c1.equals(c2));
c1.setXPosition(TimePeriodAnchor.END);
assertFalse(c1.equals(c2));
c2.setXPosition(TimePeriodAnchor.END);
assertTrue(c1.equals(c2));
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
OHLCSeriesCollection c1 = new OHLCSeriesCollection();
OHLCSeries s1 = new OHLCSeries("Series");
s1.add(new Year(2006), 1.0, 1.1, 1.2, 1.3);
c1.addSeries(s1);
OHLCSeriesCollection c2 = null;
try {
c2 = (OHLCSeriesCollection) c1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(c1 != c2);
assertTrue(c1.getClass() == c2.getClass());
assertTrue(c1.equals(c2));
// check independence
s1.setDescription("XYZ");
assertFalse(c1.equals(c2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
OHLCSeriesCollection c1 = new OHLCSeriesCollection();
OHLCSeries s1 = new OHLCSeries("Series");
s1.add(new Year(2006), 1.0, 1.1, 1.2, 1.3);
c1.addSeries(s1);
OHLCSeriesCollection c2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(c1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
c2 = (OHLCSeriesCollection) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(c1, c2);
}
/**
* A test for bug report 1170825 (originally affected XYSeriesCollection,
* this test is just copied over).
*/
public void test1170825() {
OHLCSeries s1 = new OHLCSeries("Series1");
OHLCSeriesCollection dataset = new OHLCSeriesCollection();
dataset.addSeries(s1);
try {
/* XYSeries s = */ dataset.getSeries(1);
}
catch (IllegalArgumentException e) {
// correct outcome
}
catch (IndexOutOfBoundsException e) {
assertTrue(false); // wrong outcome
}
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
public void testHashcode() {
OHLCSeriesCollection c1 = new OHLCSeriesCollection();
OHLCSeries s1 = new OHLCSeries("S");
s1.add(new Year(2009), 1.0, 4.0, 0.5, 2.0);
c1.addSeries(s1);
OHLCSeriesCollection c2 = new OHLCSeriesCollection();
OHLCSeries s2 = new OHLCSeries("S");
s2.add(new Year(2009), 1.0, 4.0, 0.5, 2.0);
c2.addSeries(s2);
assertTrue(c1.equals(c2));
int h1 = c1.hashCode();
int h2 = c2.hashCode();
assertEquals(h1, h2);
}
/**
* Some checks for the {@link OHLCSeriesCollection#removeSeries(int)}
* method.
*/
public void testRemoveSeries_int() {
OHLCSeriesCollection c1 = new OHLCSeriesCollection();
OHLCSeries s1 = new OHLCSeries("Series 1");
OHLCSeries s2 = new OHLCSeries("Series 2");
OHLCSeries s3 = new OHLCSeries("Series 3");
OHLCSeries s4 = new OHLCSeries("Series 4");
c1.addSeries(s1);
c1.addSeries(s2);
c1.addSeries(s3);
c1.addSeries(s4);
c1.removeSeries(2);
assertTrue(c1.getSeries(2).equals(s4));
c1.removeSeries(0);
assertTrue(c1.getSeries(0).equals(s2));
assertEquals(2, c1.getSeriesCount());
}
/**
* Some checks for the
* {@link OHLCSeriesCollection#removeSeries(OHLCSeries)} method.
*/
public void testRemoveSeries() {
OHLCSeriesCollection c1 = new OHLCSeriesCollection();
OHLCSeries s1 = new OHLCSeries("Series 1");
OHLCSeries s2 = new OHLCSeries("Series 2");
OHLCSeries s3 = new OHLCSeries("Series 3");
OHLCSeries s4 = new OHLCSeries("Series 4");
c1.addSeries(s1);
c1.addSeries(s2);
c1.addSeries(s3);
c1.addSeries(s4);
c1.removeSeries(s3);
assertTrue(c1.getSeries(2).equals(s4));
c1.removeSeries(s1);
assertTrue(c1.getSeries(0).equals(s2));
assertEquals(2, c1.getSeriesCount());
}
/**
* A simple check for the removeAllSeries() method.
*/
public void testRemoveAllSeries() {
OHLCSeriesCollection c1 = new OHLCSeriesCollection();
c1.addChangeListener(this);
// there should be no change event when clearing an empty series
this.lastEvent = null;
c1.removeAllSeries();
assertNull(this.lastEvent);
OHLCSeries s1 = new OHLCSeries("Series 1");
OHLCSeries s2 = new OHLCSeries("Series 2");
c1.addSeries(s1);
c1.addSeries(s2);
c1.removeAllSeries();
assertEquals(0, c1.getSeriesCount());
assertNotNull(this.lastEvent);
this.lastEvent = null; // clean up
}
/** The last received event. */
private DatasetChangeEvent lastEvent;
/**
* Receives dataset change events.
*
* @param event the event.
*/
public void datasetChanged(DatasetChangeEvent event) {
this.lastEvent = event;
}
}
|
package com.github.snieking.retry;
import com.github.snieking.time.TimeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
public final class ExponentialRetryer implements Retryer {
private static final Logger LOG = LoggerFactory.getLogger(ExponentialRetryer.class);
private int maxExponent;
private long base;
private int exponent;
private Map<Class<Exception>, Object> ignorableExceptions;
private ExponentialRetryer(final int maxExponent, final long base) {
this.maxExponent = maxExponent;
this.exponent = 1;
this.base = base;
this.ignorableExceptions = new HashMap<>();
}
@Override
public ExponentialRetryer ignoreExceptions(Class[] exceptions) {
ignorableExceptions = new HashMap<>();
for (Class<Exception> exception : exceptions) {
ignorableExceptions.put(exception, null);
}
return this;
}
@Override
public void perform(final Runnable task) throws Exception {
Exception exception = null;
if (task != null) {
while (exponent < maxExponent) {
try {
task.run();
return;
} catch (Exception e) {
if (exception != null) {
exception.addSuppressed(e);
} else {
exception = e;
}
if (!ignorableExceptions.containsKey(e.getClass())) {
TimeManager.waitUntilDurationPassed(Duration.ofMillis((long) Math.pow(base, exponent++)));
}
}
}
}
if (exception != null) {
throw exception;
}
}
@Override
public Optional performAndGet(final Supplier task) throws Exception {
Exception exception = null;
boolean latestFailed = false;
if (task != null) {
while (exponent < maxExponent) {
try {
return Optional.ofNullable(task.get());
} catch (Exception e) {
if (exception != null) {
exception.addSuppressed(e);
} else {
exception = e;
}
if (!ignorableExceptions.containsKey(e.getClass())) {
TimeManager.waitUntilDurationPassed(Duration.ofMillis((long) Math.pow(base, exponent++)));
}
}
}
}
if (latestFailed && exception != null) {
throw exception;
} else {
return Optional.empty();
}
}
/**
* Creates a ExpontentialRetryer with a default max exponent of 5, and a default base of 10 milliseconds.
*/
public static ExponentialRetryer create() {
return new ExponentialRetryer(5, 10);
}
/**
* Creates a ExponentialRetryer with a provided max exponent, and a default base of 10 milliseconds.
*/
public static ExponentialRetryer create(int maxExponent) {
return new ExponentialRetryer(maxExponent, 10);
}
/**
* Creates an ExponentialRetryer with a default max exponent of 5, and a base of a provided milliseconds.
*/
public static ExponentialRetryer create(long base) {
return new ExponentialRetryer(5, base);
}
}
|
package com.javacook.testdatagenerator;
import com.javacook.easyexcelaccess.ExcelCoordinate;
import com.javacook.easyexcelaccess.ExcelCoordinateSequencer;
import com.javacook.easyexcelaccess.ExcelUtil;
import com.javacook.testdatagenerator.excelreader.BeanPathCalculator;
import com.javacook.testdatagenerator.excelreader.MyExcelAccessor;
import com.javacook.testdatagenerator.testdatamodel.BeanPath;
import com.javacook.testdatagenerator.testdatamodel.BeanPathTree;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class TestDataReader {
public final int DATA_START_ROW = 2;
public final Set<String> NIL_MARKERS = new HashSet() {{
add("NIL");
add("NULL");
add("~");
}};
private final BeanPathCalculator beanPathCalculator;
private final MyExcelAccessor excelAccessor;
private final int headStartCol;
private final int oidCol;
/**
* @param excelFile
* @param headerStartColumn like "A",...,"Z", "AA", "AB",...
* @param oidColumn
* @throws IOException
*/
public TestDataReader(File excelFile, String headerStartColumn, String oidColumn) throws IOException {
headStartCol = ExcelUtil.calculateColNo(headerStartColumn); // starting with 1
oidCol = ExcelUtil.calculateColNo(oidColumn); // starting with 1
this.excelAccessor = new MyExcelAccessor(excelFile);
beanPathCalculator = new BeanPathCalculator(excelAccessor, headStartCol-1, oidCol-1);
}
public TestDataReader(String resourceName, String headerStartColumn, String oidColumn) throws IOException {
headStartCol = ExcelUtil.calculateColNo(headerStartColumn); // starting with 1
oidCol = ExcelUtil.calculateColNo(oidColumn); // starting with 1
this.excelAccessor = new MyExcelAccessor(resourceName);
beanPathCalculator = new BeanPathCalculator(excelAccessor, headStartCol-1, oidCol-1);
}
/**
*
* @param sheet starting with 0
* @return
* @throws IOException
*/
public BeanPathTree getBeanPathTree(int sheet) throws IOException {
final BeanPathTree beanPathTree = new BeanPathTree();
new ExcelCoordinateSequencer()
.from(new ExcelCoordinate(headStartCol, DATA_START_ROW))
.to(new ExcelCoordinate(excelAccessor.noCols(sheet), excelAccessor.noRows(sheet)))
.forEach(coord -> {
final Object value = excelAccessor.readCell(sheet, coord);
if (value != null) {
final BeanPath beanPath = beanPathCalculator.beanPath(sheet, coord);
if (NIL_MARKERS.contains(value)) {
beanPathTree.nil(beanPath);
}
else {
beanPathTree.put(beanPath, value);
}
}
});
return beanPathTree;
}
}
|
package com.j256.ormlite.jdbc;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Types;
import com.j256.ormlite.dao.ObjectCache;
import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.logger.Logger;
import com.j256.ormlite.logger.LoggerFactory;
import com.j256.ormlite.misc.IOUtils;
import com.j256.ormlite.misc.VersionUtils;
import com.j256.ormlite.stmt.GenericRowMapper;
import com.j256.ormlite.stmt.StatementBuilder.StatementType;
import com.j256.ormlite.support.CompiledStatement;
import com.j256.ormlite.support.DatabaseConnection;
import com.j256.ormlite.support.DatabaseResults;
import com.j256.ormlite.support.GeneratedKeyHolder;
/**
* Wrapper around a JDBC {@link Connection} object which we delegate to.
*
* @author graywatson
*/
public class JdbcDatabaseConnection implements DatabaseConnection {
private static final String JDBC_VERSION = "VERSION__4.49-SNAPSHOT__";
private static Logger logger = LoggerFactory.getLogger(JdbcDatabaseConnection.class);
private static final String JDBC_META_TABLE_NAME_COLUMN = "TABLE_NAME";
private static Object[] noArgs = new Object[0];
private static FieldType[] noArgTypes = new FieldType[0];
private static GenericRowMapper<Long> longWrapper = new OneLongWrapper();
private Connection connection;
private Boolean supportsSavePoints = null;
static {
VersionUtils.checkCoreVersusJdbcVersions(JDBC_VERSION);
}
public JdbcDatabaseConnection(Connection connection) {
this.connection = connection;
logger.trace("connection opened: {}", connection);
}
@Override
public boolean isAutoCommitSupported() {
return true;
}
@Override
public boolean isAutoCommit() throws SQLException {
boolean autoCommit = connection.getAutoCommit();
logger.trace("connection autoCommit is {}", autoCommit);
return autoCommit;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
connection.setAutoCommit(autoCommit);
logger.trace("connection set autoCommit to {}", autoCommit);
}
@Override
public Savepoint setSavePoint(String name) throws SQLException {
if (supportsSavePoints == null) {
DatabaseMetaData metaData = connection.getMetaData();
supportsSavePoints = metaData.supportsSavepoints();
logger.trace("connection supports save points is {}", supportsSavePoints);
}
if (supportsSavePoints) {
Savepoint savepoint = connection.setSavepoint(name);
logger.trace("save-point {} set with name {}", savepoint, name);
return savepoint;
} else {
return null;
}
}
@Override
public void commit(Savepoint savepoint) throws SQLException {
if (savepoint == null) {
connection.commit();
logger.trace("connection committed");
} else {
// release might clear the name so we record it beforehand
Object obj = savepoint.getSavepointName();
if (obj == null) {
obj = savepoint;
}
/*
* Initially I was doing a connection.releaseSavepoint(savepoint) which was only dropping the savepoint --
* not committing it like I thought. I'm still surprised there is not a commit(savepoint).
*/
connection.commit();
logger.trace("connection is committed for save-point {}", obj);
}
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
if (savepoint == null) {
connection.rollback();
logger.trace("connection is rolled back");
} else {
// rollback might clear the name so we record it beforehand
Object obj = savepoint.getSavepointName();
if (obj == null) {
obj = savepoint;
}
connection.rollback(savepoint);
logger.trace("save-point {} is rolled back", obj);
}
}
@Override
public int executeStatement(String statementStr, int resultFlags) throws SQLException {
if (resultFlags == DatabaseConnection.DEFAULT_RESULT_FLAGS) {
resultFlags = ResultSet.TYPE_FORWARD_ONLY;
}
Statement statement = connection.createStatement(resultFlags, ResultSet.CONCUR_READ_ONLY);
statement.execute(statementStr);
return statement.getUpdateCount();
}
@Override
public CompiledStatement compileStatement(String statement, StatementType type, FieldType[] argFieldTypes,
int resultFlags, boolean cacheStore) throws SQLException {
if (resultFlags == DatabaseConnection.DEFAULT_RESULT_FLAGS) {
resultFlags = ResultSet.TYPE_FORWARD_ONLY;
}
JdbcCompiledStatement compiledStatement = new JdbcCompiledStatement(
connection.prepareStatement(statement, resultFlags, ResultSet.CONCUR_READ_ONLY), type, cacheStore);
logger.trace("compiled statement: {}", statement);
return compiledStatement;
}
@Override
public void close() throws IOException {
try {
connection.close();
} catch (SQLException e) {
throw new IOException("could not close SQL connection", e);
}
logger.trace("connection closed: {}", connection);
}
@Override
public void closeQuietly() {
IOUtils.closeQuietly(this);
}
/**
* Returns whether the connection has already been closed. Used by {@link JdbcConnectionSource}.
*/
@Override
public boolean isClosed() throws SQLException {
boolean isClosed = connection.isClosed();
logger.trace("connection is closed returned {}", isClosed);
return isClosed;
}
@Override
public int insert(String statement, Object[] args, FieldType[] argFieldTypes, GeneratedKeyHolder keyHolder)
throws SQLException {
PreparedStatement stmt;
if (keyHolder == null) {
stmt = connection.prepareStatement(statement);
} else {
stmt = connection.prepareStatement(statement, Statement.RETURN_GENERATED_KEYS);
}
try {
statementSetArgs(stmt, args, argFieldTypes);
int rowN = stmt.executeUpdate();
logger.trace("insert statement is prepared and executed: {}", statement);
if (keyHolder != null) {
ResultSet resultSet = stmt.getGeneratedKeys();
ResultSetMetaData metaData = resultSet.getMetaData();
int colN = metaData.getColumnCount();
boolean wasSet = false;
while (resultSet.next()) {
for (int colC = 1; colC <= colN; colC++) {
// get the id column data so we can pass it back to the caller thru the keyHolder
Number id = getIdColumnData(resultSet, metaData, colC);
keyHolder.addKey(id);
wasSet = true;
}
}
if (!wasSet) {
throw new SQLException(
"no generated-keys were returned from statement, maybe a schema mismatch between entity and database table?: "
+ statement);
}
}
return rowN;
} finally {
stmt.close();
}
}
@Override
public int update(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException {
return update(statement, args, argFieldTypes, "update");
}
@Override
public int delete(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException {
// it's a call to executeUpdate
return update(statement, args, argFieldTypes, "delete");
}
@Override
public <T> Object queryForOne(String statement, Object[] args, FieldType[] argFieldTypes,
GenericRowMapper<T> rowMapper, ObjectCache objectCache) throws SQLException {
return queryForOne(statement, args, argFieldTypes, rowMapper, objectCache, "query for one");
}
@Override
public long queryForLong(String statement) throws SQLException {
return queryForLong(statement, noArgs, noArgTypes);
}
@Override
public long queryForLong(String statement, Object[] args, FieldType[] argFieldTypes) throws SQLException {
// don't care about the object cache here
Object result = queryForOne(statement, args, argFieldTypes, longWrapper, null, "query for long");
if (result == null) {
throw new SQLException("No results returned in query-for-long: " + statement);
} else if (result == MORE_THAN_ONE) {
throw new SQLException("More than 1 result returned in query-for-long: " + statement);
} else {
return (Long) result;
}
}
@Override
public boolean isTableExists(String tableName) throws SQLException {
DatabaseMetaData metaData = connection.getMetaData();
logger.trace("Got meta data from connection");
ResultSet results = null;
try {
results = metaData.getTables(null, null, "%", new String[] { "TABLE" });
// we do it this way because some result sets don't like us to findColumn if no results
if (!results.next()) {
return false;
}
int col = results.findColumn(JDBC_META_TABLE_NAME_COLUMN);
do {
String dbTableName = results.getString(col);
if (tableName.equalsIgnoreCase(dbTableName)) {
return true;
}
} while (results.next());
return false;
} finally {
if (results != null) {
results.close();
}
}
}
/**
* Return the internal database connection. Most likely for testing purposes.
*/
public Connection getInternalConnection() {
return connection;
}
/**
* Set the internal database connection. Most likely for testing purposes.
*/
public void setInternalConnection(Connection connection) {
this.connection = connection;
}
private int update(String statement, Object[] args, FieldType[] argFieldTypes, String label) throws SQLException {
PreparedStatement stmt = connection.prepareStatement(statement);
try {
statementSetArgs(stmt, args, argFieldTypes);
int rowCount = stmt.executeUpdate();
logger.trace("{} statement is prepared and executed returning {}: {}", label, rowCount, statement);
return rowCount;
} finally {
stmt.close();
}
}
private <T> Object queryForOne(String statement, Object[] args, FieldType[] argFieldTypes,
GenericRowMapper<T> rowMapper, ObjectCache objectCache, String label) throws SQLException {
PreparedStatement stmt =
connection.prepareStatement(statement, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
DatabaseResults results = null;
try {
statementSetArgs(stmt, args, argFieldTypes);
results = new JdbcDatabaseResults(stmt, stmt.executeQuery(), objectCache, true);
logger.trace("{} statement is prepared and executed: {}", label, statement);
if (!results.first()) {
// no results at all
return null;
}
T first = rowMapper.mapRow(results);
if (results.next()) {
return MORE_THAN_ONE;
} else {
return first;
}
} finally {
IOUtils.closeQuietly(results);
stmt.close();
}
}
/**
* Return the id associated with the column.
*/
private Number getIdColumnData(ResultSet resultSet, ResultSetMetaData metaData, int columnIndex)
throws SQLException {
int typeVal = metaData.getColumnType(columnIndex);
switch (typeVal) {
case Types.BIGINT:
case Types.DECIMAL:
case Types.NUMERIC:
return (Number) resultSet.getLong(columnIndex);
case Types.INTEGER:
return (Number) resultSet.getInt(columnIndex);
default:
String columnName = metaData.getColumnName(columnIndex);
throw new SQLException(
"Unexpected ID column type " + TypeValMapper.getSqlTypeForTypeVal(typeVal) + " (typeVal "
+ typeVal + ") in column " + columnName + "(#" + columnIndex + ") is not a number");
}
}
private void statementSetArgs(PreparedStatement stmt, Object[] args, FieldType[] argFieldTypes)
throws SQLException {
if (args == null) {
return;
}
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
int typeVal = TypeValMapper.getTypeValForSqlType(argFieldTypes[i].getSqlType());
if (arg == null) {
stmt.setNull(i + 1, typeVal);
} else {
stmt.setObject(i + 1, arg, typeVal);
}
}
}
/**
* Row mapper that handles a single long result.
*/
private static class OneLongWrapper implements GenericRowMapper<Long> {
@Override
public Long mapRow(DatabaseResults rs) throws SQLException {
// maps the first column (sql
return rs.getLong(0);
}
}
}
|
package com.kencook.sharpspring.services;
import com.kencook.sharpspring.Event;
import com.kencook.sharpspring.SharpspringMethod;
import com.kencook.sharpspring.SharpspringOperations;
import com.kencook.sharpspring.SharpspringRequest;
import com.kencook.sharpspring.SharpspringException;
import com.kencook.sharpspring.responses.GetEventsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import static com.kencook.sharpspring.SharpspringRequestBuilder.request;
/**
* Service for Sharpspring events.
*
* @since 0.1.0
*/
@Component
public class EventService {
private SharpspringOperations operations;
@Autowired
public EventService(SharpspringOperations operations) {
this.operations = operations;
}
/**
* Returns a list of events related to the provided timestamp string.
* @param timestamp yyyy-MM-dd HH:mm:ss dates without time will pull events for the entire date.
* @return a list of events associated with the timestamp
*/
public List<Event> getEvents(String timestamp) throws SharpspringException {
SharpspringRequest request = request(1, SharpspringMethod.GET_EVENTS)
.where("createTimestamp").is("2017-05-23")
.build();
GetEventsResponse result = operations.query(request, GetEventsResponse.class);
if(result.getError() != null)
throw new SharpspringException(result.getError());
return result.getResult().getEvent();
}
}
|
package org.slc.sli.domain.enums;
import org.springframework.security.core.GrantedAuthority;
/**
* A simple enum describing our basic rights that are required.
* ADMIN_ACCESS -> allows operations on entities in Admin Sphere
* FULL_ACCESS -> allows operations on all entities everywhere without regard for associations
*/
public enum Right implements GrantedAuthority {
ANONYMOUS_ACCESS,
READ_GENERAL,
WRITE_GENERAL,
READ_RESTRICTED,
WRITE_RESTRICTED,
AGGREGATE_READ,
AGGREGATE_WRITE,
ADMIN_ACCESS,
FULL_ACCESS,
APP_REGISTER,
APP_EDORG_SELECT,
APP_CREATION,
WRITE_GENERAL_REALM,
WRITE_ROLE_MAPPING;
@Override
public String getAuthority() {
return this.toString();
}
}
|
package com.kryptnostic.api.v1.sharing;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.kryptnostic.api.v1.KryptnosticConnection;
import com.kryptnostic.api.v1.KryptnosticCryptoManager;
import com.kryptnostic.indexing.v1.ObjectSearchPair;
import com.kryptnostic.kodex.v1.crypto.ciphers.BlockCiphertext;
import com.kryptnostic.kodex.v1.crypto.ciphers.CryptoService;
import com.kryptnostic.kodex.v1.crypto.ciphers.RsaCompressingEncryptionService;
import com.kryptnostic.kodex.v1.exceptions.types.ResourceNotFoundException;
import com.kryptnostic.kodex.v1.exceptions.types.SecurityConfigurationException;
import com.kryptnostic.krypto.engine.KryptnosticEngine;
import com.kryptnostic.sharing.v1.SharingClient;
import com.kryptnostic.v2.crypto.CryptoServiceLoader;
import com.kryptnostic.v2.sharing.api.SharingApi;
import com.kryptnostic.v2.sharing.models.RevocationRequest;
import com.kryptnostic.v2.sharing.models.Share;
import com.kryptnostic.v2.sharing.models.SharingRequest;
import com.kryptnostic.v2.sharing.models.VersionedObjectSearchPair;
import com.kryptnostic.v2.storage.models.VersionedObjectKey;
public class SharingManager implements SharingClient {
private static final Logger logger = LoggerFactory.getLogger( SharingManager.class );
private final KryptnosticCryptoManager context;
private final SharingApi sharingApi;
private final KryptnosticConnection connection;
public SharingManager( KryptnosticConnection connection ) {
this.context = connection.newCryptoManager();
this.sharingApi = connection.getSharingApi();
this.connection = connection;
}
@Override
public Optional<byte[]> getSearchPair( VersionedObjectKey objectKey ) {
byte[] objectSearchPair = sharingApi.getSearchPair( objectKey.getObjectId(), objectKey.getVersion() );
if ( ( objectSearchPair == null ) || ( objectSearchPair.length != 2080 ) ) {
return Optional.absent();
}
return Optional.of( objectSearchPair );
}
@Override
public Optional<byte[]> getSharingPair( VersionedObjectKey objectKey ) throws ResourceNotFoundException {
Optional<byte[]> maybeSearchPair = getSearchPair( objectKey );
if ( maybeSearchPair.isPresent() ) {
return Optional.of( connection
.getKryptnosticEngine()
.getObjectSharePairFromObjectSearchPair( maybeSearchPair.get() ) );
}
return Optional.absent();
}
@Override
public void shareObjectWithUsers( VersionedObjectKey objectId, Set<UUID> users ) throws ResourceNotFoundException {
shareObjectWithUsers( objectId, users, getSharingPair( objectId ) );
}
@Override
public void shareObjectWithUsers( VersionedObjectKey objectId, Set<UUID> users, Optional<byte[]> sharingPair )
throws ResourceNotFoundException {
CryptoServiceLoader loader = connection.getCryptoServiceLoader();
CryptoService service;
try {
Optional<CryptoService> maybeService = loader.get( objectId );
if ( maybeService.isPresent() ) {
service = maybeService.get();
Map<UUID, RsaCompressingEncryptionService> services = context.getEncryptionServiceForUsers( users );
Map<UUID, byte[]> seals = Maps.newHashMap();
for ( Entry<UUID, RsaCompressingEncryptionService> serviceEntry : services.entrySet() ) {
seals.put( serviceEntry.getKey(), serviceEntry.getValue().encrypt( service ) );
}
Optional<BlockCiphertext> encryptedSharingPair;
if ( sharingPair.isPresent() ) {
encryptedSharingPair = Optional.of( service.encrypt( sharingPair.get() ) );
} else {
encryptedSharingPair = Optional.absent();
}
SharingRequest request = new SharingRequest( objectId, seals, encryptedSharingPair );
sharingApi.share( request );
} else {
logger.error( "Unable to load crypto service for object {}", objectId );
throw new SecurityConfigurationException( "Failed to load crypto service for object " + objectId );
}
} catch ( SecurityConfigurationException | IOException | ExecutionException e ) {
logger.error( "Failured while sharing object {} with users {}", objectId, users, e );
}
}
@Override
public Set<VersionedObjectKey> processIncomingShares() throws IOException, SecurityConfigurationException {
CryptoServiceLoader loader = connection.getCryptoServiceLoader();
Iterable<Share> incomingShares = sharingApi.getIncomingShares();
if ( incomingShares == null || Iterables.isEmpty( incomingShares ) ) {
return ImmutableSet.of();
}
Set<VersionedObjectSearchPair> objectSearchPairs = Sets.newHashSet();
for ( Share share : incomingShares ) {
VersionedObjectKey id = share.getObjectKey();
CryptoService decryptor;
try {
logger.info( "Processing share for {}", id );
Optional<CryptoService> maybeService = loader.get( id );
if ( maybeService.isPresent() ) {
decryptor = maybeService.get();
} else {
logger.error( "Unable to retrieve crypto service for object {}", share.getObjectKey() );
throw new SecurityConfigurationException( "Unable to retrieve crypto service for object {}"
+ share.getObjectKey() );
}
} catch ( ExecutionException e ) {
throw new IOException( e );
}
Optional<BlockCiphertext> encryptedSharingPair = share.getEncryptedSharingPair();
if ( encryptedSharingPair.isPresent() ) {
byte[] sharePair = decryptor.decryptBytes( encryptedSharingPair.get() );
Preconditions.checkState( sharePair.length == KryptnosticEngine.SHARE_PAIR_LENGTH,
"Sharing pair must be 2064 bytes long." );
VersionedObjectSearchPair pair = new VersionedObjectSearchPair(
id,
new ObjectSearchPair( connection
.getKryptnosticEngine()
.getObjectSearchPairFromObjectSharePair( sharePair ) ) );
objectSearchPairs.add( pair );
}
}
sharingApi.addSearchPairs( objectSearchPairs );
return objectSearchPairs.keySet();
}
@Override
public void unshareObjectWithUsers( VersionedObjectKey objectId, Set<UUID> users ) {
RevocationRequest revocation = new RevocationRequest( objectId, users );
sharingApi.revokeAccess( revocation );
}
@Override
public int getIncomingSharesCount() {
Set<Share> incomingShares = sharingApi.getIncomingShares();
if ( incomingShares == null || incomingShares.isEmpty() ) {
return 0;
}
return incomingShares.size();
}
}
|
package com.jvm_bloggers.facebook.client;
import com.jvm_bloggers.facebook.client.fb.FacebookPublisher;
import com.jvm_bloggers.facebook.client.fb.PageAccessToken;
import com.jvm_bloggers.facebook.client.fb.PageAccessTokenProvider;
import com.jvm_bloggers.facebook.client.kafka.KafkaConsumer;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import java.io.IOException;
public class Application {
public static void main(String[] args) throws IOException {
final Config fbConfig = getFacebookConfig();
final PageAccessToken pageAccessToken = getPageAccessToken(fbConfig);
FacebookPublisher facebookPublisher = new FacebookPublisher(fbConfig, pageAccessToken);
new KafkaConsumer(facebookPublisher).run();
}
private static PageAccessToken getPageAccessToken(Config fbConfig) throws IOException {
return new PageAccessTokenProvider(fbConfig).getToken();
}
private static Config getFacebookConfig() {
final Config systemProperties = ConfigFactory.systemProperties();
return ConfigFactory.load().withFallback(systemProperties).getConfig("facebook");
}
}
|
package com.lothrazar.samscontent.item;//.entity.projectile;
import com.lothrazar.samscontent.MessagePotion;
import com.lothrazar.samscontent.ModSamsContent;
import com.lothrazar.samscontent.potion.PotionRegistry;
import com.lothrazar.util.Reference;
import com.lothrazar.util.SamsUtilities;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntityBlaze;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntitySnowball;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.Blocks;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.BlockPos;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
public class EntitySnowBolt extends EntitySnowball
{
public EntitySnowBolt(World worldIn)
{
super(worldIn);
}
public EntitySnowBolt(World worldIn, EntityLivingBase ent)
{
super(worldIn, ent);
}
public EntitySnowBolt(World worldIn, double x, double y, double z)
{
super(worldIn, x, y, z);
}
@Override
protected void onImpact(MovingObjectPosition mop)
{
if (mop.entityHit != null)
{
float damage = 0;
if (mop.entityHit instanceof EntityBlaze)
{
damage = 3;
}
mop.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), damage);
System.out.println("thrower "+this.getThrower().getName());
if(mop.entityHit instanceof EntityLivingBase)
{
EntityLivingBase e = (EntityLivingBase)mop.entityHit;
e.addPotionEffect(new PotionEffect(PotionRegistry.frozen.id,5 * Reference.TICKS_PER_SEC,0));
}
// on block impact, extenguish fire
}
for (int i = 0; i < 10; ++i)
{
this.worldObj.spawnParticle(EnumParticleTypes.SNOWBALL, this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D, new int[0]);
this.worldObj.spawnParticle(EnumParticleTypes.SNOW_SHOVEL, this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D, new int[0]);
}
if (this.worldObj.isRemote == false)
{
if( mop.sideHit != null && this.getThrower() instanceof EntityPlayer)
this.worldObj.extinguishFire((EntityPlayer)this.getThrower(), mop.getBlockPos(), mop.sideHit);
if(this.isInWater() )
{
BlockPos waterPos = this.getPosition();
if(this.worldObj.getBlockState(waterPos) != Blocks.water.getDefaultState() )
{
waterPos = null;//look for the closest water source, sometimes it was air and we got ice right above the water if we dont do this check
if(this.worldObj.getBlockState(mop.getBlockPos()) == Blocks.water.getDefaultState())
waterPos = mop.getBlockPos();
else if(this.worldObj.getBlockState(mop.getBlockPos().offset(mop.sideHit)) == Blocks.water.getDefaultState())
waterPos = mop.getBlockPos().offset(mop.sideHit);
}
if(waterPos != null) //rarely happens but it does
this.worldObj.setBlockState(waterPos, Blocks.ice.getDefaultState());
}
this.setDead();
}
}
}
|
package org.jboss.as.clustering.jgroups;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import javax.management.MBeanServer;
import org.jboss.as.clustering.ManagedExecutorService;
import org.jboss.as.clustering.ManagedScheduledExecutorService;
import org.jboss.as.network.SocketBinding;
import org.jboss.logging.Logger;
import org.jgroups.Address;
import org.jgroups.Channel;
import org.jgroups.ChannelException;
import org.jgroups.ChannelListener;
import org.jgroups.Global;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.jmx.JmxConfigurator;
import org.jgroups.protocols.TP;
import org.jgroups.stack.Protocol;
import org.jgroups.util.SocketFactory;
/**
* @author Paul Ferraro
*
*/
public class JChannelFactory implements ChannelFactory, ChannelListener, ProtocolStackConfigurator {
private static final Logger log = Logger.getLogger(JChannelFactory.class);
private final ProtocolStackConfiguration configuration;
private final Map<Channel, String> channels = Collections.synchronizedMap(new WeakHashMap<Channel, String>());
public JChannelFactory(ProtocolStackConfiguration configuration) {
this.configuration = configuration;
}
@Override
public Channel createChannel(String id) throws Exception {
JChannel channel = new JChannel(this);
// We need to synchronize on shared transport,
// so we don't attempt to init a shared transport multiple times
TP transport = channel.getProtocolStack().getTransport();
if (transport.isSingleton()) {
synchronized (transport) {
this.init(transport);
}
} else {
this.init(transport);
}
channel.setName(id);
MBeanServer server = this.configuration.getMBeanServer();
if (server != null) {
try {
this.channels.put(channel, id);
JmxConfigurator.registerChannel(channel, server, id);
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
channel.addChannelListener(this);
}
return channel;
}
private void init(TP transport) {
TransportConfiguration transportConfig = this.configuration.getTransport();
SocketBinding binding = transportConfig.getSocketBinding();
if (binding != null) {
SocketFactory factory = transport.getSocketFactory();
if (!(factory instanceof ManagedSocketFactory)) {
transport.setSocketFactory(new ManagedSocketFactory(factory, binding.getSocketBindings()));
}
}
ThreadFactory threadFactory = transportConfig.getThreadFactory();
if (threadFactory != null) {
if (!(transport.getThreadFactory() instanceof ThreadFactoryAdapter)) {
transport.setThreadFactory(new ThreadFactoryAdapter(threadFactory));
}
}
ExecutorService defaultExecutor = transportConfig.getDefaultExecutor();
if (defaultExecutor != null) {
if (!(transport.getDefaultThreadPool() instanceof ManagedExecutorService)) {
transport.setDefaultThreadPool(new ManagedExecutorService(defaultExecutor));
}
}
ExecutorService oobExecutor = transportConfig.getOOBExecutor();
if (oobExecutor != null) {
if (!(transport.getOOBThreadPool() instanceof ManagedExecutorService)) {
transport.setOOBThreadPool(new ManagedExecutorService(oobExecutor));
}
}
ScheduledExecutorService timerExecutor = transportConfig.getTimerExecutor();
if (timerExecutor != null) {
if (!(transport.getTimer() instanceof TimerSchedulerAdapter)) {
this.setValue(transport, "timer", new TimerSchedulerAdapter(new ManagedScheduledExecutorService(timerExecutor)));
}
}
}
/**
* {@inheritDoc}
* @see org.jgroups.conf.ProtocolStackConfigurator#getProtocolStackString()
*/
@Override
public String getProtocolStackString() {
return null;
}
/**
* {@inheritDoc}
* @see org.jgroups.conf.ProtocolStackConfigurator#getProtocolStack()
*/
@Override
public List<org.jgroups.conf.ProtocolConfiguration> getProtocolStack() {
List<org.jgroups.conf.ProtocolConfiguration> configs = new ArrayList<org.jgroups.conf.ProtocolConfiguration>(this.configuration.getProtocols().size() + 1);
TransportConfiguration transport = this.configuration.getTransport();
org.jgroups.conf.ProtocolConfiguration config = this.createProtocol(this.configuration.getTransport());
Map<String, String> properties = config.getProperties();
if (transport.isShared() && !transport.getProperties().containsKey(Global.SINGLETON_NAME)) {
properties.put(Global.SINGLETON_NAME, this.configuration.getName());
}
SocketBinding binding = transport.getSocketBinding();
if (binding != null) {
this.configureBindAddress(config, binding);
this.configureServerSocket(config, "bind_port", binding);
this.configureMulticastSocket(config, "mcast_addr", "mcast_port", binding);
}
SocketBinding diagnosticsSocketBinding = transport.getDiagnosticsSocketBinding();
boolean diagnostics = (diagnosticsSocketBinding != null);
properties.put("enable_diagnostics", String.valueOf(diagnostics));
if (diagnostics) {
this.configureMulticastSocket(config, "diagnostics_addr", "diagnostics_port", diagnosticsSocketBinding);
}
configs.add(config);
for (ProtocolConfiguration protocol: this.configuration.getProtocols()) {
config = this.createProtocol(protocol);
binding = protocol.getSocketBinding();
if (binding != null) {
this.configureBindAddress(config, binding);
this.configureServerSocket(config, "bind_port", binding);
this.configureServerSocket(config, "start_port", binding);
this.configureMulticastSocket(config, "mcast_addr", "mcast_port", binding);
} else if (transport.getSocketBinding() != null) {
// If no socket-binding was specified, use bind address transport
this.configureBindAddress(config, transport.getSocketBinding());
}
configs.add(config);
}
return configs;
}
private void configureBindAddress(org.jgroups.conf.ProtocolConfiguration config, SocketBinding binding) {
config.getProperties().put("bind_addr", binding.getSocketAddress().getAddress().getHostAddress());
}
private void configureServerSocket(org.jgroups.conf.ProtocolConfiguration config, String portProperty, SocketBinding binding) {
config.getProperties().put(portProperty, String.valueOf(binding.getSocketAddress().getPort()));
}
private void configureMulticastSocket(org.jgroups.conf.ProtocolConfiguration config, String addressProperty, String portProperty, SocketBinding binding) {
Map<String, String> properties = config.getProperties();
try {
InetSocketAddress mcastSocketAddress = binding.getMulticastSocketAddress();
properties.put(addressProperty, mcastSocketAddress.getAddress().getHostAddress());
properties.put(portProperty, String.valueOf(mcastSocketAddress.getPort()));
} catch (IllegalStateException e) {
log.tracef(e, "Could not set %s.%s and %s.%s, %s socket binding does not specify a multicast socket", config.getProtocolName(), addressProperty, config.getProtocolName(), portProperty, binding.getName());
}
}
private org.jgroups.conf.ProtocolConfiguration createProtocol(final ProtocolConfiguration protocolConfig) {
String protocol = protocolConfig.getName();
final Map<String, String> properties = new HashMap<String, String>(this.configuration.getDefaults().getProperties(protocol));
properties.putAll(protocolConfig.getProperties());
return new org.jgroups.conf.ProtocolConfiguration(protocol, properties) {
@Override
public Map<String, String> getOriginalProperties() {
return properties;
}
};
}
private void setValue(Protocol protocol, String property, Object value) {
log.tracef("Setting %s.%s=%d", protocol.getName(), property, value);
try {
protocol.setValue(property, value);
} catch (IllegalArgumentException e) {
log.tracef(e, "Failed to set non-existent %s.%s=%d", protocol.getName(), property, value);
}
}
@Override
public void channelConnected(Channel channel) {
// no-op
}
@Override
public void channelDisconnected(Channel channel) {
// no-op
}
@Override
public void channelClosed(Channel channel) {
MBeanServer server = this.configuration.getMBeanServer();
if (server != null) {
try {
JmxConfigurator.unregisterChannel((JChannel) channel, server, this.channels.remove(channel));
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
}
}
@Override
@Deprecated
public void channelShunned() {
// no-op
}
@Override
@Deprecated
public void channelReconnected(Address addr) {
// no-op
}
// Workaround for JGRP-1314
// Synchronize on shared transport during channel connect
public static class JChannel extends org.jgroups.JChannel {
JChannel(ProtocolStackConfigurator configurator) throws ChannelException {
super(configurator);
}
@Override
public void connect(final String clusterName, final boolean useFlushIfPresent) throws ChannelException {
TP transport = this.getProtocolStack().getTransport();
if (transport.isSingleton()) {
synchronized (transport) {
super.connect(clusterName, useFlushIfPresent);
}
} else {
super.connect(clusterName, useFlushIfPresent);
}
}
@Override
public void connect(String clusterName, Address target, String stateId, long timeout, boolean useFlushIfPresent) throws ChannelException {
TP transport = this.getProtocolStack().getTransport();
if (transport.isSingleton()) {
synchronized (transport) {
super.connect(clusterName, target, stateId, timeout, useFlushIfPresent);
}
} else {
super.connect(clusterName, target, stateId, timeout, useFlushIfPresent);
}
}
}
}
|
package com.lothrazar.samscontent.item;
import java.util.ArrayList;
import com.lothrazar.samscontent.ItemRegistry;
import com.lothrazar.samscontent.ModSamsContent;
import com.lothrazar.util.*;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class ItemWandWater extends Item
{
public static int DURABILITY;
public ItemWandWater()
{
super();
this.setMaxDamage(DURABILITY);
this.setMaxStackSize(1);
this.setCreativeTab(ModSamsContent.tabSamsContent);
}
public static void addRecipe()
{
GameRegistry.addShapelessRecipe(new ItemStack(ItemRegistry.wandWater),
Items.blaze_rod,
Items.water_bucket );
}
public static void cast(PlayerInteractEvent event)
{
BlockPos hit;
if(event.face == null || event.world.getBlockState(event.pos).getBlock().isReplaceable(event.world, event.pos))
{
hit = event.pos; //if we clicked water, then it does not have a face
//or maybe its replaceable, such as if we clicked on a flower
}
else
{
hit = event.pos.offset(event.face);//get the neighbouring block, like if we hit the side of dirt
}
boolean success = false;
ArrayList<Block> waterBoth = new ArrayList<Block>();
waterBoth.add(Blocks.flowing_water);
waterBoth.add(Blocks.water);
Block hitBlock = event.world.getBlockState(hit).getBlock();
if( event.action.RIGHT_CLICK_BLOCK == event.action )
{
if(event.world.isAirBlock(hit) || waterBoth.contains(hitBlock) || hitBlock.isReplaceable(event.world, hit))
{
//if its water or air, we just set the block , but if its replaceable then break it first for drops
if(hitBlock.isReplaceable(event.world, hit))
{
event.world.destroyBlock(hit, true);
}
event.world.setBlockState(hit, Blocks.water.getDefaultState());
success = true;
}
}
if(success)
{
if(event.world.isRemote)
SamsUtilities.spawnParticle(event.world, EnumParticleTypes.WATER_BUBBLE, hit);
else
SamsUtilities.damageOrBreakHeld(event.entityPlayer);
SamsUtilities.playSoundAt(event.entityPlayer, "liquid.water");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.