answer
stringlengths 17
10.2M
|
|---|
package app.lsgui.gui.channelinfopanel;
import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import app.lsgui.gui.MainWindow;
import app.lsgui.gui.chat.ChatWindow;
import app.lsgui.model.Channel;
import app.lsgui.model.Service;
import app.lsgui.model.twitch.TwitchChannel;
import app.lsgui.utils.Utils;
import app.lsgui.utils.WrappedImageView;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
public class ChannelInfoPanel extends BorderPane { // NOSONAR
private static final Logger LOGGER = LoggerFactory.getLogger(ChannelInfoPanel.class);
private static final String CHANNELINFOPANELFXML = "fxml/ChannelInfoPanel.fxml";
private static FXMLLoader loader;
private ComboBox<Service> serviceComboBox;
private ComboBox<String> qualityComboBox;
private ObjectProperty<Channel> modelProperty;
private WrappedImageView previewImageView;
private Label channelDescription;
private Label channelUptime;
private Label channelViewers;
private Label channelGame;
@FXML
private BorderPane rootBorderPane;
@FXML
private CheckBox notifyCheckBox;
@FXML
private GridPane descriptionGrid;
@FXML
private ToolBar buttonBox;
public ChannelInfoPanel(ComboBox<Service> serviceComboBox, ComboBox<String> qualityComboBox) {
LOGGER.debug("Construct StreamInfoPanel");
modelProperty = new SimpleObjectProperty<>();
this.serviceComboBox = serviceComboBox;
this.qualityComboBox = qualityComboBox;
loader = new FXMLLoader();
loader.setRoot(this);
loader.setController(this);
try {
loader.load(getClass().getClassLoader().getResourceAsStream(CHANNELINFOPANELFXML));
} catch (IOException e) {
LOGGER.error("ERROR while loading ChannelInfoPanel FXML", e);
}
setupChannelInfoPanel();
setupModelListener();
}
private void setupModelListener() {
modelProperty.addListener((observable, oldValue, newValue) -> {
Channel valueStreamModel = newValue == null ? oldValue : newValue;
if (valueStreamModel.getClass().equals(TwitchChannel.class)) {
previewImageView.imageProperty().bind(((TwitchChannel) valueStreamModel).getPreviewImage());
channelDescription.textProperty().bind(((TwitchChannel) valueStreamModel).getDescription());
channelUptime.textProperty().bind(((TwitchChannel) valueStreamModel).getUptimeString());
channelUptime.setGraphic(GlyphsDude.createIcon(FontAwesomeIcon.CLOCK_ALT));
channelViewers.textProperty().bind(((TwitchChannel) valueStreamModel).getViewersString());
channelViewers.setGraphic(GlyphsDude.createIcon(FontAwesomeIcon.USER));
channelGame.textProperty().bind(((TwitchChannel) valueStreamModel).getGame());
channelGame.setGraphic(GlyphsDude.createIcon(FontAwesomeIcon.GAMEPAD));
} else {
channelDescription.textProperty().bind(modelProperty.get().getName());
}
});
}
private void setupChannelInfoPanel() {
previewImageView = new WrappedImageView(null);
rootBorderPane.setCenter(previewImageView);
channelDescription = new Label();
channelDescription.setWrapText(true);
channelUptime = new Label();
channelViewers = new Label();
channelGame = new Label();
descriptionGrid.add(channelGame, 0, 0, 1, 1);
descriptionGrid.add(channelViewers, 0, 1, 1, 1);
descriptionGrid.add(channelUptime, 0, 2, 1, 1);
descriptionGrid.add(channelDescription, 0, 3, 1, 1);
final Button startStreamButton = GlyphsDude.createIconButton(FontAwesomeIcon.PLAY);
startStreamButton.setOnAction(event -> startStream());
final Button recordStreamButton = GlyphsDude.createIconButton(FontAwesomeIcon.DOWNLOAD);
recordStreamButton.setOnAction(event -> recordStream());
final Button openChatButton = GlyphsDude.createIconButton(FontAwesomeIcon.COMMENT);
openChatButton.setOnAction(event -> openChat());
final Button openBrowserButton = GlyphsDude.createIconButton(FontAwesomeIcon.EDGE);
openBrowserButton.setOnAction(event -> openBrowser());
buttonBox.getItems().add(startStreamButton);
buttonBox.getItems().add(recordStreamButton);
buttonBox.getItems().add(openChatButton);
buttonBox.getItems().add(openBrowserButton);
}
public void setStream(final Channel model) {
modelProperty.setValue(model);
}
private void startStream() {
if (modelProperty.get() != null && modelProperty.get().isOnline().get()) {
final String url = buildURL();
final String quality = buildQuality();
Utils.startLivestreamer(url, quality);
}
}
private void recordStream() {
if (modelProperty.get() != null && !"".equals(modelProperty.get().getName().get())
&& modelProperty.get().isOnline().get()) {
final String url = buildURL();
final String quality = buildQuality();
final FileChooser recordFileChooser = new FileChooser();
recordFileChooser.setTitle("Choose Target file");
recordFileChooser.getExtensionFilters().add(new ExtensionFilter("MPEG4", ".mpeg4"));
final File recordFile = recordFileChooser.showSaveDialog(MainWindow.getRootStage());
if (recordFile != null) {
Utils.recordLivestreamer(url, quality, recordFile);
}
}
}
private void openChat() {
if (modelProperty.get() != null && !"".equals(modelProperty.get().getName().get())) {
final String channel = modelProperty.get().getName().get();
ChatWindow cw = new ChatWindow(channel);
cw.connect();
}
}
private void openBrowser() {
if (modelProperty.get() != null && !"".equals(modelProperty.get().getName().get())) {
final String channel = modelProperty.get().getName().get();
Utils.openURLInBrowser(serviceComboBox.getSelectionModel().getSelectedItem().getUrl().get() + channel);
}
}
public ObjectProperty<Channel> getModelProperty() {
return modelProperty;
}
public void setModelProperty(ObjectProperty<Channel> modelProperty) {
this.modelProperty = modelProperty;
}
private String buildURL() {
return serviceComboBox.getSelectionModel().getSelectedItem().getUrl().get()
+ modelProperty.get().getName().get();
}
private String buildQuality() {
return qualityComboBox.getSelectionModel().getSelectedItem();
}
}
|
package com.zwitserloot.ivyplusplus;
import static java.util.Collections.unmodifiableMap;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.Setter;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DynamicAttribute;
import org.apache.tools.ant.RuntimeConfigurable;
import org.apache.tools.ant.UnknownElement;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.taskdefs.Mkdir;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.facade.FacadeTaskHelper;
import org.apache.tools.ant.util.facade.ImplementationSpecificArgument;
public class Compile extends MatchingTask implements DynamicAttribute {
private UnknownElement javac, copy, mkdir;
private Path src;
private boolean doCopy = true;
@Setter private String copyExcludes;
private boolean destdirSet;
public void setCopy(boolean copy) {
this.doCopy = copy;
}
public void init() {
javac = new UnknownElement("javac");
copy = new UnknownElement("copy");
mkdir = new UnknownElement("mkdir");
javac.setTaskName("compile:javac");
copy.setTaskName("compile:copy");
mkdir.setTaskName("compile:mkdir");
new RuntimeConfigurable(javac, javac.getTaskName());
new RuntimeConfigurable(copy, copy.getTaskName());
new RuntimeConfigurable(mkdir, mkdir.getTaskName());
javac.setProject(getProject());
copy.setProject(getProject());
mkdir.setProject(getProject());
}
private static final Map<String, String> JAVAC_ATTR_MAP, COPY_ATTR_MAP, MKDIR_ATTR_MAP, JAVAC_DEFAULTS, COPY_DEFAULTS;
static {
Map<String, String> m;
m = new HashMap<String, String>();
m.put("destdir", "dir");
MKDIR_ATTR_MAP = unmodifiableMap(m);
m = new HashMap<String, String>();
m.put("destdir", "destdir");
m.put("classpath", "classpath");
m.put("sourcepath", "sourcepath");
m.put("bootclasspath", "bootclasspath");
m.put("classpathref", "classpathref");
m.put("sourcepathref", "sourcepathref");
m.put("bootclasspathref", "bootclasspathref");
m.put("extdirs", "extdirs");
m.put("encoding", "encoding");
m.put("nowarn", "nowarn");
m.put("debug", "debug");
m.put("debuglevel", "debuglevel");
m.put("deprecation", "deprecation");
m.put("target", "target");
m.put("source", "source");
m.put("verbose", "verbose");
m.put("depend", "depend");
m.put("includeantruntime", "includeantruntime");
m.put("includejavaruntime", "includejavaruntime");
m.put("fork", "fork");
m.put("executable", "executable");
m.put("memoryinitialsize", "memoryinitialsize");
m.put("memorymaximumsize", "memorymaximumsize");
m.put("failonerror", "failonerror");
m.put("errorproperty", "errorproperty");
m.put("compiler", "compiler");
m.put("listfiles", "listfiles");
m.put("tempdir", "tempdir");
m.put("updatedproperty", "updatedproperty");
m.put("includedestclasses", "includedestclasses");
JAVAC_ATTR_MAP = unmodifiableMap(m);
m = new HashMap<String, String>();
m.put("encoding", "UTF-8");
m.put("debug", "on");
m.put("target", "1.6");
m.put("source", "1.6");
m.put("includeAntRuntime", "false");
JAVAC_DEFAULTS = unmodifiableMap(m);
m = new HashMap<String, String>();
m.put("destdir", "todir");
m.put("preservelastmodified", "preservelastmodified");
m.put("includeemptydirs", "includeemptydirs");
m.put("failonerror", "failonerror");
m.put("verbose", "verbose");
COPY_ATTR_MAP = unmodifiableMap(m);
m = new HashMap<String, String>();
m.put("includeemptydirs", "false");
COPY_DEFAULTS = unmodifiableMap(m);
}
private boolean setWithKey(UnknownElement elem, Map<String, String> map, String name, String value) {
String key = map.get(name);
if (key == null) return false;
elem.getWrapper().setAttribute(key, value);
return true;
}
public void setDynamicAttribute(String name, String value) throws BuildException {
boolean matched = false;
matched |= setWithKey(mkdir, MKDIR_ATTR_MAP, name, value);
matched |= setWithKey(javac, JAVAC_ATTR_MAP, name, value);
matched |= setWithKey(copy, COPY_ATTR_MAP, name, value);
if (!matched) throw new BuildException("Unknown property of compile task: " + name, getLocation());
if ("destdir".equals(name)) destdirSet = true;
}
public void setSrcdir(Path srcDir) {
if (src == null) src = srcDir;
else src.append(srcDir);
}
public Path createSrc() {
if (src == null) {
src = new Path(getProject());
}
return src.createPath();
}
private Path compileClasspath, compileSourcepath, bootclasspath, extdirs;
public Path createSourcepath() {
if (compileSourcepath == null) compileSourcepath = new Path(getProject());
return compileSourcepath.createPath();
}
public Path createClasspath() {
if (compileClasspath == null) compileClasspath = new Path(getProject());
return compileClasspath.createPath();
}
public Path createBootclasspath() {
if (bootclasspath == null) bootclasspath = new Path(getProject());
return bootclasspath.createPath();
}
public Path createExtdirs() {
if (extdirs == null) extdirs = new Path(getProject());
return extdirs.createPath();
}
private List<ImplementationSpecificArgument> compilerArgs = new ArrayList<ImplementationSpecificArgument>();
public ImplementationSpecificArgument createCompilerArg() {
ImplementationSpecificArgument arg = new ImplementationSpecificArgument();
compilerArgs.add(arg);
return arg;
}
public void execute() {
if (!destdirSet) throw new BuildException("mandatory property 'destdir' not set.");
if (src == null) src = new Path(getProject());
Map<?, ?> attributeMap = javac.getWrapper().getAttributeMap();
for (Map.Entry<String, String> e : JAVAC_DEFAULTS.entrySet()) {
if (!attributeMap.containsKey(e.getKey())) javac.getWrapper().setAttribute(e.getKey(), e.getValue());
}
attributeMap = copy.getWrapper().getAttributeMap();
for (Map.Entry<String, String> e : COPY_DEFAULTS.entrySet()) {
if (!attributeMap.containsKey(e.getKey())) copy.getWrapper().setAttribute(e.getKey(), e.getValue());
}
mkdir.maybeConfigure();
Mkdir mkdirTask = (Mkdir) mkdir.getRealThing();
mkdirTask.execute();
javac.maybeConfigure();
Javac javacTask = (Javac) javac.getRealThing();
javacTask.setSrcdir(src);
javacTask.createCompilerArg().setValue("-Xlint:unchecked");
if (bootclasspath != null) javacTask.setBootclasspath(bootclasspath);
if (compileClasspath != null) javacTask.setClasspath(compileClasspath);
if (compileSourcepath != null) javacTask.setSourcepath(compileSourcepath);
if (extdirs != null) javacTask.setExtdirs(extdirs);
try {
Field f = MatchingTask.class.getDeclaredField("fileset");
f.setAccessible(true);
f.set(javacTask, getImplicitFileSet().clone());
f = Javac.class.getDeclaredField("facade");
f.setAccessible(true);
FacadeTaskHelper facade = (FacadeTaskHelper) f.get(javacTask);
for (ImplementationSpecificArgument isa : compilerArgs) facade.addImplementationArgument(isa);
} catch (Exception e) {
throw new BuildException(e, getLocation());
}
javacTask.execute();
if (doCopy) {
copy.maybeConfigure();
Copy copyTask = (Copy) copy.getRealThing();
for (String pathElem : src.list()) {
File srcPath = getProject().resolveFile(pathElem);
FileSet fs = (FileSet) getImplicitFileSet().clone();
fs.setDir(srcPath);
fs.createExclude().setName("**/*.java");
if (copyExcludes != null) fs.createExclude().setName(copyExcludes);
copyTask.addFileset(fs);
}
copyTask.execute();
}
}
}
|
package io.luna.game.plugin;
import io.luna.LunaContext;
import plugin.events.AsyncPluginEvent;
import plugin.events.DeadEventHandler;
import plugin.events.GamePluginEvent;
import com.google.common.eventbus.EventBus;
public final class PluginManager extends EventBus {
/**
* The context this {@code PluginManager} is under.
*/
private final LunaContext context;
/**
* Creates a new {@link PluginManager}.
*/
public PluginManager(LunaContext context) {
super(new PluginExceptionHandler());
this.context = context;
register(new DeadEventHandler());
}
/**
* {@inheritDoc}
* <p>
* <p>
* {@link AsyncPluginEvent}s are posted asynchronously while all other
* events are posted synchronously.
*/
@Override
public void post(Object event) {
if (event instanceof AsyncPluginEvent) {
context.getService().execute(() -> super.post(event));
} else if (event instanceof GamePluginEvent) {
GamePluginEvent evt = (GamePluginEvent) event;
evt.context_$eq(context);
super.post(evt);
} else {
super.post(event);
}
}
/**
* {@inheritDoc}
* <p>
* <p>
* Not all plugins registered using this function will be submitted to the
* underlying event bus.
*/
@Override
public void register(Object object) {
// XXX: Not all plugins need to be submitted to the event bus, some need
// to be submitted elsewhere such as combat strategies,
// minigames, etc. and that can be done through here.
super.register(object);
}
}
|
package br.com.caelum.brutal.controllers;
import java.util.List;
import org.joda.time.DateTime;
import br.com.caelum.brutal.components.RecentTagsContainer;
import br.com.caelum.brutal.dao.QuestionDAO;
import br.com.caelum.brutal.dao.TagDAO;
import br.com.caelum.brutal.model.Question;
import br.com.caelum.brutal.model.Tag;
import br.com.caelum.brutal.providers.BrutalRoutesParser;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
@Resource
public class ListController {
private final QuestionDAO questions;
private final Result result;
private final TagDAO tags;
private final RecentTagsContainer recentTagsContainer;
public ListController(QuestionDAO questions, TagDAO tags, Result result, RecentTagsContainer recentTagsContainer) {
this.questions = questions;
this.tags = tags;
this.result = result;
this.recentTagsContainer = recentTagsContainer;
}
/**
* actually, this path will not be used, we use the path defined in the current environment
* be careful when modifying its signature
* @see BrutalRoutesParser
*/
@Get("/")
public void home(Integer p) {
Integer page = getPage(p);
List<Question> visible = questions.allVisible(page);
if (visible.isEmpty() && p != 1) {
result.notFound();
return;
}
result.include("questions", visible);
result.include("recentTags", recentTagsContainer.getRecentTagsUsage());
result.include("totalPages", questions.numberOfPages());
result.include("currentPage", page);
}
@Get("/nao-resolvido")
public void unsolved() {
result.include("questions", questions.unsolvedVisible());
result.include("recentTags", recentTagsContainer.getRecentTagsUsage());
}
@Get("/sem-respostas")
public void unanswered() {
result.include("questions", questions.noAnswers());
result.include("recentTags", recentTagsContainer.getRecentTagsUsage());
}
@Get("/tag/{tagName}")
public void withTag(String tagName, Integer p) {
Integer page = getPage(p);
Tag tag = tags.findByName(tagName);
List<Question> questionsWithTag = questions.withTagVisible(tag, page);
result.include("totalPages", questions.numberOfPages(tag));
result.include("tagName", tagName);
result.include("recentTags", tags.getRecentTagsSince(new DateTime().minusMonths(3)));
result.include("questions", questionsWithTag);
result.include("currentPage", page);
}
@Get("/tags")
public void listTags(){
result.include("tags", tags.all());
}
private Integer getPage(Integer p) {
Integer page = p == null ? 1 : p;
return page;
}
}
|
package com.zwitserloot.ivyplusplus;
public class Version {
// ** CAREFUL ** - this class must always compile with 0 dependencies (it must not refer to any other sources or libraries).
private static final String VERSION = "1.32";
private Version() {
//Prevent instantiation
}
/**
* Prints the version followed by a newline, and exits.
*/
public static void main(String[] args) {
System.out.println(VERSION);
}
/**
* Get the current ivyplusplus version.
*/
public static String getVersion() {
return VERSION;
}
}
|
package ai.elimu.model.content;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
@Entity
public class Emoji extends Content {
@NotNull
@Length(max = 4)
@Column(length = 4)
private String glyph;
/**
* The Unicode version when the glyph was first introduced.
* <p />
* Should be 9.0 or lower, in order to be compatible with Android SDK 7.0 (API level 24).
*/
@NotNull
private Double unicodeVersion;
@NotNull
private Double unicodeEmojiVersion;
public String getGlyph() {
return glyph;
}
public void setGlyph(String glyph) {
this.glyph = glyph;
}
public Double getUnicodeVersion() {
return unicodeVersion;
}
public void setUnicodeVersion(Double unicodeVersion) {
this.unicodeVersion = unicodeVersion;
}
public Double getUnicodeEmojiVersion() {
return unicodeEmojiVersion;
}
public void setUnicodeEmojiVersion(Double unicodeEmojiVersion) {
this.unicodeEmojiVersion = unicodeEmojiVersion;
}
}
|
package ch.liquidmind.inflection.compiler;
import java.io.File;
import ch.liquidmind.inflection.compiler.CompilationJob.CompilationMode;
import ch.liquidmind.inflection.compiler.CompilationUnit.CompilationUnitCompiled.PackageImport;
import ch.liquidmind.inflection.compiler.CompilationUnit.CompilationUnitCompiled.PackageImport.PackageImportType;
import ch.liquidmind.inflection.grammar.InflectionParser.APackageContext;
import ch.liquidmind.inflection.grammar.InflectionParser.DefaultPackageContext;
import ch.liquidmind.inflection.grammar.InflectionParser.SpecificPackageContext;
import ch.liquidmind.inflection.grammar.InflectionParser.TaxonomyNameContext;
import ch.liquidmind.inflection.model.compiled.TaxonomyCompiled;
public class Pass1Listener extends AbstractInflectionListener
{
public Pass1Listener( CompilationUnit compilationUnit )
{
super( compilationUnit );
}
@Override
public void enterSpecificPackage( SpecificPackageContext specificPackageContext )
{
APackageContext aPackageContext = (APackageContext)specificPackageContext.getChild( 1 );
String packageName = getPackageName( aPackageContext );
validateDoesntUseReservedNames( aPackageContext, packageName );
validateCorrespondsWithFileName( aPackageContext, packageName );
setPackageName( packageName );
getPackageImports().add( new PackageImport( packageName, null, PackageImportType.OWN_PACKAGE ) );
if ( !packageName.equals( DEFAULT_PACKAGE_NAME ) )
getPackageImports().add( new PackageImport( DEFAULT_PACKAGE_NAME, null, PackageImportType.OTHER_PACKAGE ) );
}
@Override
public void enterDefaultPackage( DefaultPackageContext defaultPackageContext )
{
setPackageName( DEFAULT_PACKAGE_NAME );
getPackageImports().add( new PackageImport( DEFAULT_PACKAGE_NAME, null, PackageImportType.OWN_PACKAGE ) );
}
@Override
public void enterTaxonomyName( TaxonomyNameContext taxonomyNameContext )
{
String taxonomyName = getTaxonomyName( taxonomyNameContext );
validateTaxonomyNotRedundant( taxonomyNameContext, taxonomyName );
TaxonomyCompiled taxonomyCompiled = new TaxonomyCompiled( taxonomyName );
getKnownTaxonomiesCompiled().put( taxonomyName, taxonomyCompiled );
getTaxonomiesCompiled().add( taxonomyCompiled );
}
// VALIDATION
private void validateTaxonomyNotRedundant( TaxonomyNameContext taxonomyNameContext, String taxonomyName )
{
if ( getKnownTaxonomiesCompiled().keySet().contains( taxonomyName ) )
reportError( taxonomyNameContext.start, taxonomyNameContext.stop, "Taxonomy '" + taxonomyName + "' already defined in compilation unit '" + getCompilationUnit().getCompilationUnitRaw().getSourceFile() + "'" );
if ( getTaxonomyLoader().loadTaxonomy( taxonomyName ) != null )
reportError( taxonomyNameContext.start, taxonomyNameContext.stop, "Taxonomy '" + taxonomyName + "' already defined in previously compiled taxonomy." );
}
private void validateDoesntUseReservedNames( APackageContext aPackageContext, String packageName )
{
if ( getCompilationUnit().getParentCompilationJob().getCompilationMode().equals( CompilationMode.NORMAL ) &&
( packageName.startsWith( JAVA_PACKAGE ) || packageName.startsWith( CH_LIQUIDMIND_INFLECTION_PACKAGE ) ) )
reportError( aPackageContext.start, aPackageContext.stop,
"Package names must not start with reserved names '" + JAVA_PACKAGE + "' or '" + CH_LIQUIDMIND_INFLECTION_PACKAGE + "'." );
}
private void validateCorrespondsWithFileName( APackageContext aPackageContext, String packageName )
{
String fileName = getCompilationUnit().getCompilationUnitRaw().getSourceFile().getParentFile().getAbsolutePath();
String expectedFileName = packageName.replace( ".", File.separator ) ;
if ( !fileName.endsWith( expectedFileName ) )
reportError( aPackageContext.start, aPackageContext.stop, "Package name '" + packageName +
"' does not correspond with file name '" + fileName + "'." );
}
}
|
package me.nallar.patched;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.google.common.collect.ImmutableSetMultimap;
import javassist.is.faulty.ThreadLocals;
import me.nallar.tickthreading.Log;
import me.nallar.tickthreading.collections.ForcedChunksRedirectMap;
import me.nallar.tickthreading.minecraft.entitylist.EntityList;
import me.nallar.tickthreading.minecraft.entitylist.LoadedTileEntityList;
import me.nallar.tickthreading.patcher.Declare;
import net.minecraft.block.Block;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityTracker;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.profiler.Profiler;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ReportedException;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.ChunkProviderServer;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
@SuppressWarnings ("ForLoopReplaceableByForEach")
public abstract class PatchWorld extends World {
private int forcedUpdateCount;
@Declare
public Set<Entity> unloadedEntitySet_;
@Declare
public Set<TileEntity> tileEntityRemovalSet_;
@Declare
public com.google.common.collect.ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> forcedChunks_;
@Declare
public int tickCount_;
public void construct() {
tickCount = rand.nextInt(5);
tileEntityRemovalSet = new HashSet<TileEntity>();
unloadedEntitySet = new HashSet<Entity>();
}
public PatchWorld(ISaveHandler par1ISaveHandler, String par2Str, WorldProvider par3WorldProvider, WorldSettings par4WorldSettings, Profiler par5Profiler) {
super(par1ISaveHandler, par2Str, par3WorldProvider, par4WorldSettings, par5Profiler);
}
@Override
public void removeEntity(Entity entity) {
if (entity == null) {
return;
}
try {
if (entity.riddenByEntity != null) {
entity.riddenByEntity.mountEntity((Entity) null);
}
if (entity.ridingEntity != null) {
entity.mountEntity((Entity) null);
}
entity.setDead();
// The next instanceof, somehow, seems to throw NPEs. I don't even. :(
if (entity instanceof EntityPlayer) {
this.playerEntities.remove(entity);
this.updateAllPlayersSleepingFlag();
}
} catch (Exception e) {
Log.severe("Exception removing a player entity", e);
}
}
@Override
public int getBlockId(int x, int y, int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y > 0 && y < 256) {
try {
return getChunkFromChunkCoords(x >> 4, z >> 4).getBlockID(x & 15, y, z & 15);
} catch (Throwable t) {
Log.severe("Exception getting block ID in " + Log.name(this) + " at x,y,z" + x + ',' + y + ',' + z, t);
}
}
return 0;
}
@Override
@Declare
public int getBlockIdWithoutLoad(int x, int y, int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y > 0 && y < 256) {
try {
Chunk chunk = ((ChunkProviderServer) chunkProvider).getChunkIfExists(x >> 4, z >> 4);
return chunk == null ? -1 : chunk.getBlockID(x & 15, y, z & 15);
} catch (Throwable t) {
Log.severe("Exception getting block ID in " + Log.name(this) + " at x,y,z" + x + ',' + y + ',' + z, t);
}
}
return 0;
}
@Override
protected void notifyBlockOfNeighborChange(int x, int y, int z, int par4) {
if (!this.editingBlocks && !this.isRemote) {
int var5 = this.getBlockIdWithoutLoad(x, y, z);
Block var6 = var5 < 1 ? null : Block.blocksList[var5];
if (var6 != null) {
try {
var6.onNeighborBlockChange(this, x, y, z, par4);
} catch (Throwable t) {
Log.severe("Exception while updating block neighbours", t);
}
}
}
}
@Override
public ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> getPersistentChunks() {
return forcedChunks == null ? ForcedChunksRedirectMap.emptyMap : forcedChunks;
}
@Override
public TileEntity getBlockTileEntity(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
Chunk chunk = this.getChunkFromChunkCoords(x >> 4, z >> 4);
return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
@Declare
public TileEntity getTEWithoutLoad(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
Chunk chunk = ((ChunkProviderServer) this.chunkProvider).getChunkIfExists(x >> 4, z >> 4);
return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
public void updateEntityWithOptionalForce(Entity par1Entity, boolean par2) {
int x = MathHelper.floor_double(par1Entity.posX);
int z = MathHelper.floor_double(par1Entity.posZ);
Boolean isForced = par1Entity.isForced;
if (isForced == null || forcedUpdateCount++ % 7 == 0) {
par1Entity.isForced = isForced = getPersistentChunks().containsKey(new ChunkCoordIntPair(x >> 4, z >> 4));
}
byte range = isForced ? (byte) 0 : 32;
boolean canUpdate = !par2 || this.checkChunksExist(x - range, 0, z - range, x + range, 0, z + range);
if (canUpdate) {
par1Entity.lastTickPosX = par1Entity.posX;
par1Entity.lastTickPosY = par1Entity.posY;
par1Entity.lastTickPosZ = par1Entity.posZ;
par1Entity.prevRotationYaw = par1Entity.rotationYaw;
par1Entity.prevRotationPitch = par1Entity.rotationPitch;
if (par2 && par1Entity.addedToChunk) {
if (par1Entity.ridingEntity != null) {
par1Entity.updateRidden();
} else {
++par1Entity.ticksExisted;
par1Entity.onUpdate();
}
}
this.theProfiler.startSection("chunkCheck");
if (Double.isNaN(par1Entity.posX) || Double.isInfinite(par1Entity.posX)) {
par1Entity.posX = par1Entity.lastTickPosX;
}
if (Double.isNaN(par1Entity.posY) || Double.isInfinite(par1Entity.posY)) {
par1Entity.posY = par1Entity.lastTickPosY;
}
if (Double.isNaN(par1Entity.posZ) || Double.isInfinite(par1Entity.posZ)) {
par1Entity.posZ = par1Entity.lastTickPosZ;
}
if (Double.isNaN((double) par1Entity.rotationPitch) || Double.isInfinite((double) par1Entity.rotationPitch)) {
par1Entity.rotationPitch = par1Entity.prevRotationPitch;
}
if (Double.isNaN((double) par1Entity.rotationYaw) || Double.isInfinite((double) par1Entity.rotationYaw)) {
par1Entity.rotationYaw = par1Entity.prevRotationYaw;
}
int var6 = MathHelper.floor_double(par1Entity.posX / 16.0D);
int var7 = MathHelper.floor_double(par1Entity.posY / 16.0D);
int var8 = MathHelper.floor_double(par1Entity.posZ / 16.0D);
if (!par1Entity.addedToChunk || par1Entity.chunkCoordX != var6 || par1Entity.chunkCoordY != var7 || par1Entity.chunkCoordZ != var8) {
if (par1Entity.addedToChunk && this.chunkExists(par1Entity.chunkCoordX, par1Entity.chunkCoordZ)) {
this.getChunkFromChunkCoords(par1Entity.chunkCoordX, par1Entity.chunkCoordZ).removeEntityAtIndex(par1Entity, par1Entity.chunkCoordY);
}
if (this.chunkExists(var6, var8)) {
par1Entity.addedToChunk = true;
this.getChunkFromChunkCoords(var6, var8).addEntity(par1Entity);
} else {
par1Entity.addedToChunk = false;
}
}
this.theProfiler.endSection();
if (par2 && par1Entity.addedToChunk && par1Entity.riddenByEntity != null) {
if (!par1Entity.riddenByEntity.isDead && par1Entity.riddenByEntity.ridingEntity == par1Entity) {
this.updateEntity(par1Entity.riddenByEntity);
} else {
par1Entity.riddenByEntity.ridingEntity = null;
par1Entity.riddenByEntity = null;
}
}
}
}
@Override
public void addLoadedEntities(List par1List) {
EntityTracker entityTracker = null;
if (((Object) this instanceof WorldServer)) {
entityTracker = ((WorldServer) (Object) this).getEntityTracker();
}
for (int var2 = 0; var2 < par1List.size(); ++var2) {
Entity entity = (Entity) par1List.get(var2);
if (MinecraftForge.EVENT_BUS.post(new EntityJoinWorldEvent(entity, this))) {
par1List.remove(var2
} else if (entityTracker == null || !entityTracker.isTracking(entity.entityId)) {
loadedEntityList.add(entity);
this.obtainEntitySkin(entity);
}
}
}
@Override
@Declare
public boolean hasCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
List collidingBoundingBoxes = (List) ThreadLocals.collidingBoundingBoxes.get();
collidingBoundingBoxes.clear();
int minX = MathHelper.floor_double(par2AxisAlignedBB.minX);
int maxX = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D);
int minY = MathHelper.floor_double(par2AxisAlignedBB.minY);
int maxY = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D);
int minZ = MathHelper.floor_double(par2AxisAlignedBB.minZ);
int maxZ = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D);
int ystart = ((minY - 1) < 0) ? 0 : (minY - 1);
for (int chunkx = (minX >> 4); chunkx <= ((maxX - 1) >> 4); chunkx++) {
int cx = chunkx << 4;
for (int chunkz = (minZ >> 4); chunkz <= ((maxZ - 1) >> 4); chunkz++) {
if (!this.chunkExists(chunkx, chunkz)) {
continue;
}
int cz = chunkz << 4;
Chunk chunk = this.getChunkFromChunkCoords(chunkx, chunkz);
// Compute ranges within chunk
int xstart = (minX < cx) ? cx : minX;
int xend = (maxX < (cx + 16)) ? maxX : (cx + 16);
int zstart = (minZ < cz) ? cz : minZ;
int zend = (maxZ < (cz + 16)) ? maxZ : (cz + 16);
// Loop through blocks within chunk
for (int x = xstart; x < xend; x++) {
for (int z = zstart; z < zend; z++) {
for (int y = ystart; y < maxY; y++) {
int blkid = chunk.getBlockID(x - cx, y, z - cz);
if (blkid > 0) {
Block block = Block.blocksList[blkid];
if (block != null) {
block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity);
}
if (!collidingBoundingBoxes.isEmpty()) {
return true;
}
}
}
}
}
}
}
double var14 = 0.25D;
List var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), 100);
for (int var15 = 0; var15 < var16.size(); ++var15) {
AxisAlignedBB var13 = ((Entity) var16.get(var15)).getBoundingBox();
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
return true;
}
var13 = par1Entity.getCollisionBox((Entity) var16.get(var15));
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
return true;
}
}
return false;
}
@Override
@Declare
public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) {
List collidingBoundingBoxes = (List) ThreadLocals.collidingBoundingBoxes.get();
collidingBoundingBoxes.clear();
int var3 = MathHelper.floor_double(par2AxisAlignedBB.minX);
int var4 = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D);
int var5 = MathHelper.floor_double(par2AxisAlignedBB.minY);
int var6 = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D);
int var7 = MathHelper.floor_double(par2AxisAlignedBB.minZ);
int var8 = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D);
int ystart = ((var5 - 1) < 0) ? 0 : (var5 - 1);
for (int chunkx = (var3 >> 4); chunkx <= ((var4 - 1) >> 4); chunkx++) {
int cx = chunkx << 4;
for (int chunkz = (var7 >> 4); chunkz <= ((var8 - 1) >> 4); chunkz++) {
if (!this.chunkExists(chunkx, chunkz)) {
continue;
}
int cz = chunkz << 4;
Chunk chunk = this.getChunkFromChunkCoords(chunkx, chunkz);
// Compute ranges within chunk
int xstart = (var3 < cx) ? cx : var3;
int xend = (var4 < (cx + 16)) ? var4 : (cx + 16);
int zstart = (var7 < cz) ? cz : var7;
int zend = (var8 < (cz + 16)) ? var8 : (cz + 16);
// Loop through blocks within chunk
for (int x = xstart; x < xend; x++) {
for (int z = zstart; z < zend; z++) {
for (int y = ystart; y < var6; y++) {
int blkid = chunk.getBlockID(x - cx, y, z - cz);
if (blkid > 0) {
Block block = Block.blocksList[blkid];
if (block != null) {
block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity);
}
}
}
}
}
}
}
double var14 = 0.25D;
List var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), limit);
for (int var15 = 0; var15 < var16.size(); ++var15) {
AxisAlignedBB var13 = ((Entity) var16.get(var15)).getBoundingBox();
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
collidingBoundingBoxes.add(var13);
}
var13 = par1Entity.getCollisionBox((Entity) var16.get(var15));
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
collidingBoundingBoxes.add(var13);
}
}
return collidingBoundingBoxes;
}
@Override
public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
return getCollidingBoundingBoxes(par1Entity, par2AxisAlignedBB, 2000);
}
@Override
public void addTileEntity(Collection tileEntities) {
List dest = scanningTileEntities ? addedTileEntityList : loadedTileEntityList;
for (TileEntity tileEntity : (Iterable<TileEntity>) tileEntities) {
tileEntity.validate();
if (tileEntity.canUpdate()) {
dest.add(tileEntity);
}
}
}
@Override
@Declare
public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) {
List entitiesWithinAABBExcludingEntity = (List) ThreadLocals.entitiesWithinAABBExcludingEntity.get();
entitiesWithinAABBExcludingEntity.clear();
int minX = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D);
int maxX = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D);
int minZ = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D);
int maxZ = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D);
for (int x = minX; x <= maxX; ++x) {
for (int z = minZ; z <= maxZ; ++z) {
if (this.chunkExists(x, z)) {
this.getChunkFromChunkCoords(x, z).getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, entitiesWithinAABBExcludingEntity, limit);
}
}
}
return entitiesWithinAABBExcludingEntity;
}
@Override
public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
List entitiesWithinAABBExcludingEntity = (List) ThreadLocals.entitiesWithinAABBExcludingEntity.get();
entitiesWithinAABBExcludingEntity.clear();
int var3 = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D);
int var4 = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D);
int var5 = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D);
int var6 = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D);
for (int var7 = var3; var7 <= var4; ++var7) {
for (int var8 = var5; var8 <= var6; ++var8) {
if (this.chunkExists(var7, var8)) {
this.getChunkFromChunkCoords(var7, var8).getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, entitiesWithinAABBExcludingEntity);
}
}
}
return entitiesWithinAABBExcludingEntity;
}
@Override
public int countEntities(Class entityType) {
if (loadedEntityList instanceof EntityList) {
return ((EntityList) this.loadedEntityList).manager.getEntityCount(entityType);
}
int var2 = 0;
for (int var3 = 0; var3 < this.loadedEntityList.size(); ++var3) {
Entity var4 = (Entity) this.loadedEntityList.get(var3);
if (entityType.isAssignableFrom(var4.getClass())) {
++var2;
}
}
return var2;
}
@Override
public void unloadEntities(List entitiesToUnload) {
this.unloadedEntitySet.addAll(entitiesToUnload);
}
@Override
public void updateEntities() {
this.theProfiler.startSection("entities");
this.theProfiler.startSection("global");
int var1;
Entity var2;
CrashReport var4;
CrashReportCategory var5;
for (var1 = 0; var1 < this.weatherEffects.size(); ++var1) {
var2 = (Entity) this.weatherEffects.get(var1);
try {
++var2.ticksExisted;
var2.onUpdate();
} catch (Throwable var6) {
var4 = CrashReport.makeCrashReport(var6, "Ticking entity");
var5 = var4.makeCategory("Entity being ticked");
var2.func_85029_a(var5);
throw new ReportedException(var4);
}
if (var2.isDead) {
this.weatherEffects.remove(var1
}
}
this.theProfiler.endStartSection("remove");
int var3;
int var13;
if (this.loadedEntityList instanceof EntityList) {
((EntityList) this.loadedEntityList).manager.batchRemoveEntities(unloadedEntitySet);
} else {
this.loadedEntityList.removeAll(this.unloadedEntitySet);
for (Entity entity : unloadedEntitySet) {
var3 = entity.chunkCoordX;
var13 = entity.chunkCoordZ;
if (entity.addedToChunk && this.chunkExists(var3, var13)) {
this.getChunkFromChunkCoords(var3, var13).removeEntity(entity);
}
releaseEntitySkin(entity);
}
}
this.unloadedEntitySet.clear();
this.theProfiler.endStartSection("regular");
boolean shouldTickThreadingTick = true;
if (this.loadedEntityList instanceof EntityList) {
((EntityList) this.loadedEntityList).manager.doTick();
shouldTickThreadingTick = false;
} else {
for (var1 = 0; var1 < this.loadedEntityList.size(); ++var1) {
var2 = (Entity) this.loadedEntityList.get(var1);
if (var2.ridingEntity != null) {
if (!var2.ridingEntity.isDead && var2.ridingEntity.riddenByEntity == var2) {
continue;
}
var2.ridingEntity.riddenByEntity = null;
var2.ridingEntity = null;
}
this.theProfiler.startSection("tick");
if (!var2.isDead) {
try {
this.updateEntity(var2);
} catch (Throwable var7) {
var4 = CrashReport.makeCrashReport(var7, "Ticking entity");
var5 = var4.makeCategory("Entity being ticked");
var2.func_85029_a(var5);
throw new ReportedException(var4);
}
}
this.theProfiler.endSection();
this.theProfiler.startSection("remove");
if (var2.isDead) {
var3 = var2.chunkCoordX;
var13 = var2.chunkCoordZ;
if (var2.addedToChunk && this.chunkExists(var3, var13)) {
this.getChunkFromChunkCoords(var3, var13).removeEntity(var2);
}
this.loadedEntityList.remove(var1
this.releaseEntitySkin(var2);
}
this.theProfiler.endSection();
}
}
this.theProfiler.endStartSection("tileEntities");
if (this.loadedEntityList instanceof EntityList) {
if (shouldTickThreadingTick) {
((EntityList) this.loadedEntityList).manager.doTick();
}
} else {
this.scanningTileEntities = true;
Iterator var14 = this.loadedTileEntityList.iterator();
while (var14.hasNext()) {
TileEntity var9 = (TileEntity) var14.next();
if (!var9.isInvalid() && var9.func_70309_m() && this.blockExists(var9.xCoord, var9.yCoord, var9.zCoord)) {
try {
var9.updateEntity();
} catch (Throwable var8) {
var4 = CrashReport.makeCrashReport(var8, "Ticking tile entity");
var5 = var4.makeCategory("Tile entity being ticked");
var9.func_85027_a(var5);
throw new ReportedException(var4);
}
}
if (var9.isInvalid()) {
var14.remove();
if (this.chunkExists(var9.xCoord >> 4, var9.zCoord >> 4)) {
Chunk var11 = this.getChunkFromChunkCoords(var9.xCoord >> 4, var9.zCoord >> 4);
if (var11 != null) {
var11.cleanChunkBlockTileEntity(var9.xCoord & 15, var9.yCoord, var9.zCoord & 15);
}
}
}
}
}
this.theProfiler.endStartSection("removingTileEntities");
if (!this.tileEntityRemovalSet.isEmpty()) {
if (loadedTileEntityList instanceof LoadedTileEntityList) {
((LoadedTileEntityList) loadedTileEntityList).manager.batchRemoveTileEntities(tileEntityRemovalSet);
} else {
for (Object tile : tileEntityRemovalSet) {
((TileEntity) tile).onChunkUnload();
}
this.loadedTileEntityList.removeAll(tileEntityRemovalSet);
}
tileEntityRemovalSet.clear();
}
this.scanningTileEntities = false;
this.theProfiler.endStartSection("pendingTileEntities");
if (!this.addedTileEntityList.isEmpty()) {
for (int var10 = 0; var10 < this.addedTileEntityList.size(); ++var10) {
TileEntity var12 = (TileEntity) this.addedTileEntityList.get(var10);
if (!var12.isInvalid()) {
if (!this.loadedTileEntityList.contains(var12)) {
this.loadedTileEntityList.add(var12);
}
} else {
if (this.chunkExists(var12.xCoord >> 4, var12.zCoord >> 4)) {
Chunk var15 = this.getChunkFromChunkCoords(var12.xCoord >> 4, var12.zCoord >> 4);
if (var15 != null) {
var15.cleanChunkBlockTileEntity(var12.xCoord & 15, var12.yCoord, var12.zCoord & 15);
}
}
}
}
this.addedTileEntityList.clear();
}
this.theProfiler.endSection();
this.theProfiler.endSection();
}
@Override
public void markTileEntityForDespawn(TileEntity tileEntity) {
tileEntityRemovalSet.add(tileEntity);
}
}
|
package org.wyona.yanel.impl.resources.yaneluser;
import org.wyona.yanel.core.ResourceConfiguration;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import org.wyona.security.core.api.User;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.log4j.Logger;
/**
* A resource to edit/update the profile of a user
*/
public class EditYanelUserProfileResource extends BasicXMLResource {
private static Logger log = Logger.getLogger(EditYanelUserProfileResource.class);
/*
* This method overrides the method to create the InputStream called by BasicXMLResource
* Since you extend the BasicXMLResource this has to contain well-formed xml.
* Should return a InputStream which contains XML.
* Use String, StingBuffer, dom, jdom, org.apache.commons.io.IOUtils and so on to generate the XML.
*/
protected InputStream getContentXML(String viewId) {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
try {
return getXMLAsStream();
} catch(Exception e) {
log.error(e, e);
return null;
}
}
/**
* Get XML as stream
*/
private java.io.InputStream getXMLAsStream() throws Exception {
String userId = getUserId();
if (userId != null) {
User user = realm.getIdentityManager().getUserManager().getUser(userId);
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<user id=\"" + userId + "\" email=\"" + user.getEmail() + "\" language=\"" + user.getLanguage() + "\">");
sb.append(" <name>" + user.getName() + "</name>");
sb.append(" <expiration-date>" + user.getExpirationDate() + "</expiration-date>");
sb.append(" <description>" + user.getDescription() + "</description>");
org.wyona.security.core.api.Group[] groups = user.getGroups();
if (groups != null && groups.length > 0) {
sb.append(" <groups>");
for (int i = 0; i < groups.length; i++) {
sb.append(" <group id=\"" + groups[i].getID() + "\"/>");
}
sb.append(" </groups>");
}
sb.append("</user>");
return new java.io.StringBufferInputStream(sb.toString());
} else {
return new java.io.StringBufferInputStream("<no-user-id/>");
}
}
/**
* Get user id from resource configuration
*/
private String getUserId() throws Exception {
String userId = null;
if (getEnvironment().getRequest().getParameter("id") != null) {
return getEnvironment().getRequest().getParameter("id");
}
ResourceConfiguration resConfig = getConfiguration();
if(resConfig != null) {
userId = getConfiguration().getProperty("user");
} else {
log.warn("DEPRECATED: Do not use RTI but rather a resource configuration");
userId = getRTI().getProperty("user");
}
return userId;
}
}
|
package apostov;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.math3.fraction.Fraction;
import org.apache.commons.math3.util.Combinations;
import org.apache.commons.math3.util.CombinatoricsUtils;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
public class HandResultEnumerator {
public ImmutableMap<HolecardHand, Fraction> enumerateBoardsAndMeasureWins(final ImmutableList<HolecardHand> candidates) {
final ImmutableList<Card> deck = new DeckFactory().newDeck(
candidates.stream()
.map(HolecardHand::getHolecardsAsList)
.flatMap(Collection::stream)
.collect(toSet())
);
final ShowdownEvaluator evaluator = new ShowdownEvaluator();
final int binomialCoefficient = (int) CombinatoricsUtils.binomialCoefficient(deck.size(), 5);
final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
final Map<HolecardHand, Fraction> overallSuccessChanceByHand;
final Callable<ConcurrentMap<HolecardHand, Fraction>> successChanceComputationTask =
() -> StreamSupport.stream(new Combinations(deck.size(), 5).spliterator(), true)
.map((a) -> stream(a).mapToObj(i -> deck.get(i)).collect(toList()))
.map(l -> {
assert l.size() == 5;
return new Board(l.get(0), l.get(1), l.get(2), l.get(3), l.get(4));
})
.map(b -> evaluator.evaluateShowdown(candidates, b))
.map(wc -> Maps.toMap(wc, w -> new Fraction(1, binomialCoefficient * wc.size())))
.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(Collectors.toConcurrentMap(
Map.Entry::getKey,
Map.Entry::getValue,
(x, y) -> x.add(y)));
try {
overallSuccessChanceByHand = pool.submit(successChanceComputationTask).get();
} catch (final InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
return ImmutableMap.copyOf(overallSuccessChanceByHand);
}
}
|
package ch.uzh.csg.reimbursement.service;
import java.util.Date;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ch.uzh.csg.reimbursement.dto.ExpenseDto;
import ch.uzh.csg.reimbursement.model.Expense;
import ch.uzh.csg.reimbursement.model.ExpenseItem;
import ch.uzh.csg.reimbursement.model.User;
import ch.uzh.csg.reimbursement.model.exception.ExpenseNotFoundException;
import ch.uzh.csg.reimbursement.repository.ExpenseRepositoryProvider;
@Service
@Transactional
public class ExpenseService {
private final Logger LOG = LoggerFactory.getLogger(ExpenseService.class);
@Autowired
private ExpenseRepositoryProvider expenseRepository;
@Autowired
private UserService userService;
public void create(ExpenseDto dto) {
User user = userService.getLoggedInUser();
//TODO Determine where contactPerson will be defined
User contactPerson = userService.findByUid("cleib");
Date currentDate = new Date();
Expense expense = new Expense(user, currentDate, contactPerson, dto.getBookingText());
expenseRepository.create(expense);
}
public Set<Expense> findAllByUser(String uid) {
return expenseRepository.findAllByUser(uid);
}
public Set<Expense> findAllByCurrentUser() {
User user = userService.getLoggedInUser();
return findAllByUser(user.getUid());
}
public void updateExpense(String uid, ExpenseDto dto) {
Expense expense = findByUid(uid);
//TODO Determine where contactPerson will be defined
User contactPerson = userService.findByUid("cleib");
Date currentDate = new Date();
expense.updateExpense(currentDate, contactPerson, dto.getBookingText());
}
public void computeTotalAmount(String uid) {
Expense expense = findByUid(uid);
double totalAmount=0;
for(ExpenseItem item: expense.getExpenseItems()){
totalAmount += totalAmount + item.getAmount();
}
expense.setTotalAmount(totalAmount);
}
public Expense findByUid(String uid) {
Expense expense = expenseRepository.findByUid(uid);
if (expense == null) {
LOG.debug("Expense not found in database with uid: " + uid);
throw new ExpenseNotFoundException();
}
return expense;
}
public Set<ExpenseItem> findAllExpenseItemsByUid(String uid) {
Expense expense = findByUid(uid);
return expense.getExpenseItems();
}
}
|
package at.pria.koza.harmonic;
import java.io.Serializable;
/**
* <p>
* The class {@code Entity} represents a single object that is part of an {@linkplain Engine engine's} state. An
* entity can only belong to one engine at a time. In this engine, it is identified by an id assigned by the
* engine. The id assignment scheme is deterministic so that systems of distributed engines can replay
* {@link Action Actions} that create new entities.
* </p>
*
* @version V1.0 27.07.2013
* @author SillyFreak
*/
public interface Entity extends Serializable {
/**
* <p>
* Returns the engine to which this entity belongs.
* </p>
*
* @return the engine to which this entity belongs
*/
public Engine getEngine();
/**
* <p>
* Returns the id assigned to this entity by the engine.
* </p>
*
* @return this entity's id
*/
public int getId();
}
|
package bdv.viewer;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import org.scijava.ui.behaviour.KeyStrokeAdder;
import org.scijava.ui.behaviour.util.Actions;
import org.scijava.ui.behaviour.util.InputActionBindings;
import bdv.viewer.ViewerPanel.AlignPlane;
public class NavigationActions extends Actions
{
public static final String TOGGLE_INTERPOLATION = "toggle interpolation";
public static final String TOGGLE_FUSED_MODE = "toggle fused mode";
public static final String TOGGLE_GROUPING = "toggle grouping";
public static final String SET_CURRENT_SOURCE = "set current source %d";
public static final String TOGGLE_SOURCE_VISIBILITY = "toggle source visibility %d";
public static final String ALIGN_PLANE = "align %s plane";
public static final String NEXT_TIMEPOINT = "next timepoint";
public static final String PREVIOUS_TIMEPOINT = "previous timepoint";
/**
* Create navigation actions and install them in the specified
* {@link InputActionBindings}.
*
* @param inputActionBindings
* {@link InputMap} and {@link ActionMap} are installed here.
* @param viewer
* Navigation actions are targeted at this {@link ViewerPanel}.
* @param keyProperties
* user-defined key-bindings.
*/
public static void installActionBindings(
final InputActionBindings inputActionBindings,
final ViewerPanel viewer,
final KeyStrokeAdder.Factory keyProperties )
{
final NavigationActions actions = new NavigationActions( keyProperties );
actions.modes( viewer );
actions.sources( viewer );
actions.time( viewer );
actions.alignPlanes( viewer );
actions.install( inputActionBindings, "navigation" );
}
public NavigationActions( final KeyStrokeAdder.Factory keyConfig )
{
super( keyConfig, new String[] { "bdv", "navigation" } );
}
public void alignPlaneAction( final ViewerPanel viewer, final AlignPlane plane, final String... defaultKeyStrokes )
{
runnableAction(
() -> viewer.align( plane ),
String.format( ALIGN_PLANE, plane.getName() ), defaultKeyStrokes );
}
public void modes( final ViewerPanel viewer )
{
runnableAction(
() -> viewer.toggleInterpolation(),
TOGGLE_INTERPOLATION, "I" );
runnableAction(
() -> viewer.getVisibilityAndGrouping().setFusedEnabled( !viewer.visibilityAndGrouping.isFusedEnabled() ),
TOGGLE_FUSED_MODE, "F" );
runnableAction(
() -> viewer.getVisibilityAndGrouping().setGroupingEnabled( !viewer.visibilityAndGrouping.isGroupingEnabled() ),
TOGGLE_GROUPING, "G" );
}
public void time( final ViewerPanel viewer )
{
runnableAction(
() -> viewer.nextTimePoint(),
NEXT_TIMEPOINT, "CLOSE_BRACKET", "M" );
runnableAction(
() -> viewer.previousTimePoint(),
PREVIOUS_TIMEPOINT, "OPEN_BRACKET", "N" );
}
public void sources( final ViewerPanel viewer )
{
final String[] numkeys = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
for ( int i = 0; i < numkeys.length; ++i )
{
final int sourceIndex = i;
runnableAction(
() -> viewer.getVisibilityAndGrouping().setCurrentGroupOrSource( sourceIndex ),
String.format( SET_CURRENT_SOURCE, i ), numkeys[ i ] );
runnableAction(
() -> viewer.getVisibilityAndGrouping().toggleActiveGroupOrSource( sourceIndex ),
String.format( TOGGLE_SOURCE_VISIBILITY, i ), "shift " + numkeys[ i ] );
}
}
public void alignPlanes( final ViewerPanel viewer )
{
alignPlaneAction( viewer, AlignPlane.XY, "shift Z" );
alignPlaneAction( viewer, AlignPlane.ZY, "shift X" );
alignPlaneAction( viewer, AlignPlane.XZ, "shift Y", "shift A" );
}
}
|
package com.akiban.server.service;
import com.akiban.server.AkServer;
import com.akiban.server.service.config.ConfigurationService;
import com.akiban.server.service.config.ConfigurationServiceImpl;
import com.akiban.server.service.dxl.DXLService;
import com.akiban.server.service.dxl.DXLServiceImpl;
import com.akiban.server.service.jmx.JmxRegistryService;
import com.akiban.server.service.jmx.JmxRegistryServiceImpl;
import com.akiban.server.service.memcache.MemcacheService;
import com.akiban.server.service.memcache.MemcacheServiceImpl;
import com.akiban.server.service.network.NetworkService;
import com.akiban.server.service.network.NetworkServiceImpl;
import com.akiban.server.service.session.SessionService;
import com.akiban.server.service.session.SessionServiceImpl;
import com.akiban.server.service.tree.TreeService;
import com.akiban.server.service.tree.TreeServiceImpl;
import com.akiban.qp.persistitadapter.OperatorStore;
import com.akiban.server.store.PersistitStore;
import com.akiban.server.store.PersistitStoreSchemaManager;
import com.akiban.server.store.SchemaManager;
import com.akiban.server.store.Store;
public class DefaultServiceFactory implements ServiceFactory {
private Service<JmxRegistryService> jmxRegistryService;
private Service<ConfigurationService> configurationService;
private Service<NetworkService> networkService;
private Service<AkServer> chunkserverService;
private Service<TreeService> treeService;
private Service<Store> storeService;
private Service<SchemaManager> schemaService;
private Service<MemcacheService> memcacheService;
private Service<DXLService> dxlService;
private Service<SessionService> sessionService;
@Override
public Service<ConfigurationService> configurationService() {
if (configurationService == null) {
configurationService = new ConfigurationServiceImpl();
}
return configurationService;
}
@Override
public Service<NetworkService> networkService() {
if (networkService == null) {
ConfigurationService config = configurationService().cast();
networkService = new NetworkServiceImpl(config);
}
return networkService;
}
@Override
public Service<AkServer> chunkserverService() {
if (chunkserverService == null) {
final AkServer chunkserver = new AkServer();
chunkserverService = chunkserver;
}
return chunkserverService;
}
@Override
public Service<JmxRegistryService> jmxRegistryService() {
if (jmxRegistryService == null) {
jmxRegistryService = new JmxRegistryServiceImpl();
}
return jmxRegistryService;
}
@Override
public Service<TreeService> treeService() {
if (treeService == null) {
treeService = new TreeServiceImpl();
}
return treeService;
}
@Override
public Service<Store> storeService() {
if (storeService == null) {
// TODO once the operator store is fully tested, we should remove this switch and always use it
ConfigurationService config = configurationService().cast();
String useOperatorStore = config.getProperty("akserver.debug.useOperatorStore", "false");
storeService = Boolean.valueOf(useOperatorStore) ? new OperatorStore() : new PersistitStore();
}
return storeService;
}
@Override
public Service<SchemaManager> schemaManager() {
if (schemaService == null) {
schemaService = new PersistitStoreSchemaManager();
}
return schemaService;
}
@Override
public Service<MemcacheService> memcacheService()
{
if (memcacheService == null)
{
memcacheService = new MemcacheServiceImpl();
}
return memcacheService;
}
@Override
public Service<DXLService> dxlService() {
if (dxlService == null) {
dxlService = new DXLServiceImpl();
}
return dxlService;
}
@Override
public Service<SessionService> sessionService() {
if (sessionService == null) {
sessionService = new SessionServiceImpl();
}
return sessionService;
}
}
|
// SwingOverlayView.java
package imagej.ui.swing.display;
import imagej.data.display.AbstractOverlayView;
import imagej.data.display.ImageDisplay;
import imagej.data.overlay.Overlay;
import imagej.ui.swing.overlay.IJHotDrawOverlayAdapter;
import imagej.ui.swing.overlay.JHotDrawAdapterFinder;
import java.awt.EventQueue;
import org.jhotdraw.draw.Drawing;
import org.jhotdraw.draw.Figure;
import org.jhotdraw.draw.event.FigureAdapter;
import org.jhotdraw.draw.event.FigureEvent;
/**
* TODO
*
* @author Curtis Rueden
* @author Lee Kamentsky
*/
@SuppressWarnings("synthetic-access")
public class SwingOverlayView extends AbstractOverlayView implements FigureView {
private final ImageDisplay display;
/** JHotDraw {@link Figure} linked to the associated {@link Overlay}. */
private final Figure figure;
private final IJHotDrawOverlayAdapter adapter;
private boolean updatingFigure = false;
private boolean updatingOverlay = false;
private boolean updateScheduled = false;
private boolean disposeScheduled = false;
private boolean disposed = false;
private boolean figureAdded = false;
/**
* Constructor to use to discover the figure to use for an overlay
* @param display - hook to this display
* @param overlay - represent this overlay
*/
public SwingOverlayView(final ImageDisplay display, final Overlay overlay) {
this(display, overlay, null);
}
/**
* Constructor to use if the figure already exists, for instance if it
* was created using the CreationTool
*
* @param display - hook to this display
* @param overlay - represent this overlay
* @param figure - draw using this figure
*/
public SwingOverlayView(final ImageDisplay display,
final Overlay overlay, Figure figure)
{
super(overlay);
this.display = display;
adapter = JHotDrawAdapterFinder.getAdapterForOverlay(overlay, figure);
if (figure == null) {
this.figure = adapter.createDefaultFigure();
adapter.updateFigure(this, this.figure);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
synchronized(SwingOverlayView.this) {
if (! disposeScheduled) {
final JHotDrawImageCanvas canvas = (JHotDrawImageCanvas) display.getCanvas();
final Drawing drawing = canvas.getDrawing();
drawing.add(SwingOverlayView.this.figure);
figureAdded = true;
}
}
}
});
} else {
this.figure = figure;
figureAdded = true;
}
this.figure.addFigureListener(new FigureAdapter() {
@Override
public void attributeChanged(FigureEvent e) {
synchronized(SwingOverlayView.this) {
if (! updatingFigure) {
updatingOverlay = true;
try {
adapter.updateOverlay(SwingOverlayView.this.figure, SwingOverlayView.this);
overlay.update();
} finally {
updatingOverlay = false;
}
}
}
}
@Override
public void figureChanged(FigureEvent e) {
synchronized(SwingOverlayView.this) {
if (! updatingFigure) {
updatingOverlay = true;
try {
adapter.updateOverlay(SwingOverlayView.this.figure, SwingOverlayView.this);
overlay.update();
} finally {
updatingOverlay = false;
}
}
}
}
@Override
public void figureRemoved(FigureEvent e) {
synchronized(SwingOverlayView.this) {
if (disposed || disposeScheduled) return;
}
if (display.isVisible(SwingOverlayView.this)) {
display.remove(SwingOverlayView.this);
dispose();
display.update();
}
}
});
}
// -- DataView methods --
private void show(final boolean doShow) {
final JHotDrawImageCanvas canvas = (JHotDrawImageCanvas) display.getCanvas();
final Drawing drawing = canvas.getDrawing();
final Figure fig = getFigure();
if (doShow) {
if (! drawing.contains(fig)) {
drawing.add(fig);
}
} else {
if (drawing.contains(fig)) {
drawing.remove(fig);
}
}
}
@Override
public int getPreferredWidth() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getPreferredHeight() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void update() {
updateFigure();
}
@Override
public void rebuild() {
updateFigure();
}
@Override
public Figure getFigure() {
return figure;
}
@Override
public void dispose() {
synchronized(this) {
if (! disposeScheduled) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
synchronized(SwingOverlayView.this) {
if (figureAdded) {
figure.requestRemove();
}
disposed = true;
}
}});
disposeScheduled = true;
}
}
super.dispose();
}
private synchronized void updateFigure() {
if (updatingOverlay || disposeScheduled) return;
if (! updateScheduled) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
doUpdateFigure();
} finally {
updateScheduled = false;
}
}});
updateScheduled = true;
}
}
private synchronized void doUpdateFigure() {
if (disposeScheduled) return;
updatingFigure = true;
try {
adapter.updateFigure(this, figure);
} finally {
updatingFigure = false;
}
show(display.isVisible(this));
}
}
|
package biz.paluch.spinach;
import static com.google.common.base.Preconditions.*;
import static com.lambdaworks.redis.LettuceStrings.*;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.google.common.net.HostAndPort;
import com.lambdaworks.redis.ConnectionPoint;
import io.netty.channel.unix.DomainSocketAddress;
/**
* Disque URI. Contains connection details for the Disque connections. You can provide as well the database, password and
* timeouts within the DisqueURI. Either build your self the object
*
* @author <a href="mailto:mpaluch@paluch.biz">Mark Paluch</a>
* @since 3.0
*/
@SuppressWarnings("serial")
public class DisqueURI implements Serializable {
public static final String URI_SCHEME_DISQUE = "disque";
public static final String URI_SCHEME_DISQUE_SOCKET = "disque-socket";
public static final String URI_SCHEME_DISQUE_SECURE = "disquess";
/**
* The default disque port.
*/
public static final int DEFAULT_DISQUE_PORT = 7711;
private int database;
private char[] password;
private boolean ssl = false;
private boolean verifyPeer = true;
private boolean startTls = false;
private long timeout = 60;
private TimeUnit unit = TimeUnit.SECONDS;
private final List<ConnectionPoint> connectionPoints = new ArrayList<ConnectionPoint>();
/**
* Default empty constructor.
*/
public DisqueURI() {
}
/**
* Constructor with host/port and timeout.
*
* @param host the host
* @param port the port
* @param timeout timeout value
* @param unit unit of the timeout value
*/
public DisqueURI(String host, int port, long timeout, TimeUnit unit) {
DisqueHostAndPort hap = new DisqueHostAndPort();
hap.setHost(host);
hap.setPort(port);
connectionPoints.add(hap);
this.timeout = timeout;
this.unit = unit;
}
/**
* Create a Disque URI from an URI string. Supported formats are:
* <ul>
* <li>disque://[password@]host[:port][/databaseNumber]</li>
* </ul>
*
* The uri must follow conventions of {@link java.net.URI}
*
* @param uri The URI string.
* @return An instance of {@link DisqueURI} containing details from the URI.
*/
public static DisqueURI create(String uri) {
return create(URI.create(uri));
}
/**
* Create a Disque URI from an URI string. Supported formats are:
* <ul>
* <li>disque://[password@]host[:port][/databaseNumber]</li>
* </ul>
*
* The uri must follow conventions of {@link java.net.URI}
*
* @param uri The URI.
* @return An instance of {@link DisqueURI} containing details from the URI.
*/
public static DisqueURI create(URI uri) {
DisqueURI.Builder builder;
builder = configureDisque(uri);
if (URI_SCHEME_DISQUE_SECURE.equals(uri.getScheme())) {
builder.withSsl(true);
}
String userInfo = uri.getUserInfo();
if (isEmpty(userInfo) && isNotEmpty(uri.getAuthority()) && uri.getAuthority().indexOf('@') > 0) {
userInfo = uri.getAuthority().substring(0, uri.getAuthority().indexOf('@'));
}
if (isNotEmpty(userInfo)) {
String password = userInfo;
if (password.startsWith(":")) {
password = password.substring(1);
}
builder.withPassword(password);
}
if (!URI_SCHEME_DISQUE_SOCKET.equals(uri.getScheme())) {
if (isNotEmpty(uri.getPath())) {
String pathSuffix = uri.getPath().substring(1);
if (isNotEmpty(pathSuffix)) {
builder.withDatabase(Integer.parseInt(pathSuffix));
}
}
}
return builder.build();
}
private static DisqueURI.Builder configureDisque(URI uri) {
DisqueURI.Builder builder = null;
if (URI_SCHEME_DISQUE_SOCKET.equals(uri.getScheme())) {
builder = Builder.disqueSocket(uri.getPath());
} else
if (isNotEmpty(uri.getHost())) {
if (uri.getPort() != -1) {
builder = DisqueURI.Builder.disque(uri.getHost(), uri.getPort());
} else {
builder = DisqueURI.Builder.disque(uri.getHost());
}
}
if (builder == null && isNotEmpty(uri.getAuthority())) {
String authority = uri.getAuthority();
if (authority.indexOf('@') > -1) {
authority = authority.substring(authority.indexOf('@') + 1);
}
String[] hosts = authority.split("\\,");
for (String host : hosts) {
if (uri.getScheme().equals(URI_SCHEME_DISQUE_SOCKET)) {
if (builder == null) {
builder = DisqueURI.Builder.disqueSocket(host);
} else {
builder.withSocket(host);
}
} else {
HostAndPort hostAndPort = HostAndPort.fromString(host);
if (builder == null) {
if (hostAndPort.hasPort()) {
builder = DisqueURI.Builder.disque(hostAndPort.getHostText(), hostAndPort.getPort());
} else {
builder = DisqueURI.Builder.disque(hostAndPort.getHostText());
}
} else {
if (hostAndPort.hasPort()) {
builder.withDisque(hostAndPort.getHostText(), hostAndPort.getPort());
} else {
builder.withDisque(hostAndPort.getHostText());
}
}
}
}
}
checkArgument(builder != null, "Invalid URI, cannot get host part");
return builder;
}
public char[] getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password.toCharArray();
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public TimeUnit getUnit() {
return unit;
}
public void setUnit(TimeUnit unit) {
this.unit = unit;
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
public boolean isVerifyPeer() {
return verifyPeer;
}
public void setVerifyPeer(boolean verifyPeer) {
this.verifyPeer = verifyPeer;
}
public boolean isStartTls() {
return startTls;
}
public void setStartTls(boolean startTls) {
this.startTls = startTls;
}
public List<ConnectionPoint> getConnectionPoints() {
return connectionPoints;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" ").append(connectionPoints);
return sb.toString();
}
/**
* Builder for Disque URI.
*/
public static class Builder {
private final DisqueURI disqueURI = new DisqueURI();
/**
* Set Disque host. Creates a new builder.
*
* @param host the host name
* @return New builder with Disque host/port.
*/
public static Builder disque(String host) {
return disque(host, DEFAULT_DISQUE_PORT);
}
/**
* Set Disque host and port. Creates a new builder
*
* @param host the host name
* @param port the port
* @return New builder with Disque host/port.
*/
public static Builder disque(String host, int port) {
checkNotNull(host, "Host must not be null");
Builder builder = new Builder();
builder.withDisque(host, port);
return builder;
}
/**
* Set Disque socket. Creates a new builder .
*
* @param socket the socket name
* @return New builder with Disque socket.
*/
public static Builder disqueSocket(String socket) {
checkNotNull(socket, "Socket must not be null");
Builder builder = new Builder();
builder.withSocket(socket);
return builder;
}
public Builder withSocket(String socket) {
checkNotNull(socket, "Socket must not be null");
this.disqueURI.connectionPoints.add(new DisqueSocket(socket));
return this;
}
public Builder withDisque(String host) {
checkNotNull(host, "Host must not be null");
return withDisque(host, DEFAULT_DISQUE_PORT);
}
public Builder withDisque(String host, int port) {
checkNotNull(host, "Host must not be null");
DisqueHostAndPort hap = new DisqueHostAndPort(host, port);
this.disqueURI.connectionPoints.add(hap);
return this;
}
/**
* Adds ssl information to the builder.
*
* @param ssl {@literal true} if use SSL
* @return the builder
*/
public Builder withSsl(boolean ssl) {
disqueURI.setSsl(ssl);
return this;
}
/**
* Enables/disables StartTLS when using SSL.
*
* @param startTls {@literal true} if use StartTLS
* @return the builder
*/
public Builder withStartTls(boolean startTls) {
disqueURI.setStartTls(startTls);
return this;
}
/**
* Enables/disables peer verification.
*
* @param verifyPeer {@literal true} to verify hosts when using SSL
* @return the builder
*/
public Builder withVerifyPeer(boolean verifyPeer) {
disqueURI.setVerifyPeer(verifyPeer);
return this;
}
/**
* Adds database selection.
*
* @param database the database number
* @return the builder
*/
public Builder withDatabase(int database) {
disqueURI.setDatabase(database);
return this;
}
/**
* Adds authentication.
*
* @param password the password
* @return the builder
*/
public Builder withPassword(String password) {
checkNotNull(password, "Password must not be null");
disqueURI.setPassword(password);
return this;
}
/**
* Adds timeout.
*
* @param timeout must be greater or equal 0"
* @param unit the timeout time unit.
* @return the builder
*/
public Builder withTimeout(long timeout, TimeUnit unit) {
checkNotNull(unit, "TimeUnit must not be null");
checkArgument(timeout >= 0, "Timeout must be greater or equal 0");
disqueURI.setTimeout(timeout);
disqueURI.setUnit(unit);
return this;
}
/**
*
* @return the DisqueURI.
*/
public DisqueURI build() {
return disqueURI;
}
}
public static class DisqueSocket implements Serializable, ConnectionPoint {
private String socket;
private transient SocketAddress resolvedAddress;
public DisqueSocket() {
}
public DisqueSocket(String socket) {
this.socket = socket;
}
@Override
public String getHost() {
return null;
}
@Override
public int getPort() {
return -1;
}
@Override
public String getSocket() {
return socket;
}
public void setSocket(String socket) {
this.socket = socket;
}
public SocketAddress getResolvedAddress() {
if (resolvedAddress == null) {
resolvedAddress = new DomainSocketAddress(getSocket());
}
return resolvedAddress;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
sb.append("[socket=").append(socket);
sb.append(']');
return sb.toString();
}
}
public static class DisqueHostAndPort implements Serializable, ConnectionPoint {
private String host;
private int port;
private transient SocketAddress resolvedAddress;
public DisqueHostAndPort() {
}
public DisqueHostAndPort(String host, int port) {
this.host = host;
this.port = port;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
@Override
public String getSocket() {
return null;
}
public void setPort(int port) {
this.port = port;
}
public SocketAddress getResolvedAddress() {
if (resolvedAddress == null) {
resolvedAddress = new InetSocketAddress(host, port);
}
return resolvedAddress;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
sb.append("[port=").append(port);
sb.append(", host='").append(host).append('\'');
sb.append(']');
return sb.toString();
}
}
}
|
package com.akiban.server.service.servicemanager;
import com.akiban.server.error.CircularDependencyException;
import com.akiban.server.service.servicemanager.configuration.ServiceBinding;
import com.akiban.util.ArgumentValidation;
import com.akiban.util.Exceptions;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.ProvisionException;
import com.google.inject.Scopes;
import com.google.inject.grapher.GrapherModule;
import com.google.inject.grapher.InjectorGrapher;
import com.google.inject.grapher.graphviz.GraphvizModule;
import com.google.inject.grapher.graphviz.GraphvizRenderer;
import com.google.inject.spi.Dependency;
import com.google.inject.spi.InjectionPoint;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
public final class Guicer {
// Guicer interface
public Collection<Class<?>> directlyRequiredClasses() {
return directlyRequiredClasses;
}
public void stopAllServices(ServiceLifecycleActions<?> withActions) {
try {
stopServices(withActions, null);
} catch (Exception e) {
throw new RuntimeException("while stopping services", e);
}
}
public <T> T get(Class<T> serviceClass, ServiceLifecycleActions<?> withActions) {
final T instance = _injector.getInstance(serviceClass);
return startService(serviceClass, instance, withActions);
}
public boolean serviceIsStarted(Class<?> serviceClass) {
for (Object service : services) {
if (serviceClass.isInstance(service))
return true;
}
return false;
}
public boolean isRequired(Class<?> interfaceClass) {
return directlyRequiredClasses.contains(interfaceClass);
}
/**
* <p>Builds and returns a list of dependencies for an instance of the specified class. The list will include an
* instance of the class itself, as well as any instances that root instance requires, directly or indirectly,
* according to Guice constructor injection.</p>
*
* <p>The order of the resulting list is fully deterministic and guarantees that for any element N in the list,
* if N depends on another element M, then M will also be in the list and will have an index greater than N's.
* In other words, traversing the list in reverse order will guarantee that you see any class's dependency
* before you see it.</p>
*
* <p>Each instance will appear exactly once; in other words, if there is an element N in the list,
* there will be no element M such that {@code N == M} or such that
* {@code N.getClass() == M.getClass()}</p>
*
* <p>More specifically, the order of the list is generated by doing a depth-first traversal of the dependency
* graph, with each element's dependents visited in alphabetical order of their class names, and then removing
* duplicates by doing a reverse traversal of the list. By that last point we mean that if N and M are duplicates,
* and N.index > M.index, then we would keep N and discard M.</p>
*
* <p>This method returns a new list with each invocation; the caller is free to modify the returned list.</p>
* @param rootClass the root class for which to get dependencies
* @return a mutable list of dependency instances, including the instance specified by the root class, in an order
* such that any element in the list always precedes all of its dependencies
* @throws CircularDependencyException if a circular dependency is found
*/
public List<?> dependenciesFor(Class<?> rootClass) {
LinkedHashMap<Class<?>,Object> result = new LinkedHashMap<Class<?>,Object>(16, .75f, true);
Deque<Object> dependents = new ArrayDeque<Object>();
buildDependencies(rootClass, result, dependents);
assert dependents.isEmpty() : dependents;
return new ArrayList<Object>(result.values());
}
public void graph(String filename, Collection<Class<?>> roots) {
try {
StringWriter stringWriter = new StringWriter();
PrintWriter out = new PrintWriter(stringWriter);
Injector injector = Guice.createInjector(new GraphvizModule(), new GrapherModule());
GraphvizRenderer renderer = injector.getInstance(GraphvizRenderer.class);
renderer.setOut(out);
InjectorGrapher grapher = injector.getInstance(InjectorGrapher.class);
grapher.of(_injector);
grapher.rootedAt(roots.toArray(new Class<?>[roots.size()]));
grapher.graph();
out.flush();
out.close();
String dotText = stringWriter.toString();
dotText = dotText.replace("invis", "solid");
PrintWriter fileOut = new PrintWriter(uniqueFile(filename), "UTF-8");
fileOut.print(dotText);
fileOut.flush();
fileOut.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private File uniqueFile(String filename) {
File file = new File(filename);
if (file.exists()) {
int lastDot = filename.lastIndexOf('.');
final String prefix, suffix;
if (lastDot > 0) {
prefix = filename.substring(0, lastDot);
suffix = filename.substring(lastDot);
} else {
prefix = filename;
suffix = "";
}
for (int i=1; file.exists(); ++i) {
file = new File(prefix + i + suffix);
}
}
return file;
}
// public class methods
public static Guicer forServices(Collection<ServiceBinding> serviceBindings)
throws ClassNotFoundException
{
return forServices(null, null, serviceBindings, Collections.<String>emptyList(),
Collections.<Module>emptyList());
}
public static <M extends ServiceManagerBase> Guicer forServices(Class<M> serviceManagerInterfaceClass,
M serviceManager,
Collection<ServiceBinding> serviceBindings,
List<String> priorities,
Collection<? extends Module> modules)
throws ClassNotFoundException
{
ArgumentValidation.notNull("bindings", serviceBindings);
if (serviceManagerInterfaceClass != null) {
if (!serviceManagerInterfaceClass.isInstance(serviceManager)) {
throw new IllegalArgumentException(serviceManager + " is not a "
+ serviceManagerInterfaceClass);
}
}
return new Guicer(serviceManagerInterfaceClass, serviceManager,
serviceBindings, priorities, modules);
}
// private methods
private Guicer(Class<? extends ServiceManagerBase> serviceManagerInterfaceClass, ServiceManagerBase serviceManager,
Collection<ServiceBinding> serviceBindings, List<String> priorities,
Collection<? extends Module> modules)
throws ClassNotFoundException
{
this.serviceManagerInterfaceClass = serviceManagerInterfaceClass;
List<Class<?>> localDirectlyRequiredClasses = new ArrayList<Class<?>>();
List<ResolvedServiceBinding> resolvedServiceBindings = new ArrayList<ResolvedServiceBinding>();
for (ServiceBinding serviceBinding : serviceBindings) {
ResolvedServiceBinding resolvedServiceBinding = new ResolvedServiceBinding(serviceBinding);
resolvedServiceBindings.add(resolvedServiceBinding);
if (serviceBinding.isDirectlyRequired()) {
localDirectlyRequiredClasses.add(resolvedServiceBinding.serviceInterfaceClass());
}
}
Collections.sort(localDirectlyRequiredClasses, BY_CLASS_NAME);
// Pull to front in reverse order.
for (int i = priorities.size() - 1; i >= 0; i
Class<?> clazz = Class.forName(priorities.get(i));
if (localDirectlyRequiredClasses.remove(clazz)) {
localDirectlyRequiredClasses.add(0, clazz);
}
else {
throw new IllegalArgumentException("priority service " + priorities.get(i) + " is not a dependency");
}
}
directlyRequiredClasses = Collections.unmodifiableCollection(localDirectlyRequiredClasses);
this.services = Collections.synchronizedSet(new LinkedHashSet<Object>());
AbstractModule module = new ServiceBindingsModule(serviceManagerInterfaceClass, serviceManager,
resolvedServiceBindings);
List<Module> modulesList = new ArrayList<Module>(modules.size() + 1);
modulesList.add(module);
modulesList.addAll(modules);
_injector = Guice.createInjector(modulesList.toArray(new Module[modulesList.size()]));
}
private void buildDependencies(Class<?> forClass, LinkedHashMap<Class<?>,Object> results, Deque<Object> dependents) {
Object instance = _injector.getInstance(forClass);
if (dependents.contains(instance)) {
throw circularDependencyInjection(forClass, instance, dependents);
}
// Start building this object
dependents.addLast(instance);
Class<?> actualClass = instance.getClass();
Object oldInstance = results.put(actualClass, instance);
if (oldInstance != null) {
assert oldInstance == instance : oldInstance + " != " + instance;
}
// Build the dependency list
List<Class<?>> dependencyClasses = new ArrayList<Class<?>>();
for (Dependency<?> dependency : InjectionPoint.forConstructorOf(actualClass).getDependencies()) {
dependencyClasses.add(dependency.getKey().getTypeLiteral().getRawType());
}
for (InjectionPoint injectionPoint : InjectionPoint.forInstanceMethodsAndFields(actualClass)) {
for (Dependency<?> dependency : injectionPoint.getDependencies()) {
dependencyClasses.add(dependency.getKey().getTypeLiteral().getRawType());
}
}
for (InjectionPoint injectionPoint : InjectionPoint.forStaticMethodsAndFields(actualClass)) {
for (Dependency<?> dependency : injectionPoint.getDependencies()) {
dependencyClasses.add(dependency.getKey().getTypeLiteral().getRawType());
}
}
// This dependency is already handled.
dependencyClasses.remove(serviceManagerInterfaceClass);
// Sort it and recursively invoke
Collections.sort(dependencyClasses, BY_CLASS_NAME);
for (Class<?> dependencyClass : dependencyClasses) {
buildDependencies(dependencyClass, results, dependents);
}
// Done building the object; pop the deque and confirm the instance
Object removed = dependents.removeLast();
assert removed == instance : removed + " != " + instance;
}
private CircularDependencyException circularDependencyInjection(Class<?> forClass, Object instance, Deque<Object> dependents) {
String forClassName = forClass.getSimpleName();
List<String> classNames = new ArrayList<String>();
for (Object o : dependents) {
classNames.add(o.getClass().getSimpleName());
}
classNames.add(instance.getClass().getSimpleName());
return new CircularDependencyException (forClassName, classNames);
}
private <T,S> T startService(Class<T> serviceClass, T instance, ServiceLifecycleActions<S> withActions) {
// quick check; startServiceIfApplicable will do this too, but this way we can avoid finding dependencies
if (services.contains(instance)) {
return instance;
}
synchronized (services) {
for (Object dependency : reverse(dependenciesFor(serviceClass))) {
startServiceIfApplicable(dependency, withActions);
}
}
return instance;
}
private static <T> List<T> reverse(List<T> list) {
Collections.reverse(list);
return list;
}
private <T, S> void startServiceIfApplicable(T instance, ServiceLifecycleActions<S> withActions) {
if (services.contains(instance)) {
return;
}
if (withActions == null) {
services.add(instance);
return;
}
S service = withActions.castIfActionable(instance);
if (service != null) {
try {
withActions.onStart(service);
services.add(service);
} catch (Exception e) {
try {
stopServices(withActions, e);
} catch (Exception e1) {
e = e1;
}
throw new ProvisionException("While starting service " + instance.getClass(), e);
}
}
}
private void stopServices(ServiceLifecycleActions<?> withActions, Exception initialCause) throws Exception {
List<Throwable> exceptions = tryStopServices(withActions, initialCause);
if (!exceptions.isEmpty()) {
if (exceptions.size() == 1) {
throw Exceptions.throwAlways(exceptions, 0);
}
for (Throwable t : exceptions) {
t.printStackTrace();
}
Throwable cause = exceptions.get(0);
throw new Exception("Failure(s) while shutting down services: " + exceptions, cause);
}
}
private <S> List<Throwable> tryStopServices(ServiceLifecycleActions<S> withActions, Exception initialCause) {
ListIterator<?> reverseIter;
synchronized (services) {
reverseIter = new ArrayList<Object>(services).listIterator(services.size());
}
List<Throwable> exceptions = new ArrayList<Throwable>();
if (initialCause != null) {
exceptions.add(initialCause);
}
while (reverseIter.hasPrevious()) {
try {
Object serviceObject = reverseIter.previous();
services.remove(serviceObject);
if (withActions != null) {
S service = withActions.castIfActionable(serviceObject);
if (service != null) {
withActions.onShutdown(service);
}
}
} catch (Throwable t) {
exceptions.add(t);
}
}
// TODO because our dependency graph is created via Service.start() invocations, if service A uses service B
// in stop() but not start(), and service B has already been shut down, service B will be resurrected. Yuck.
// I don't know of a good way around this, other than by formalizing our dependency graph via constructor
// params (and thus removing ServiceManagerImpl.get() ). Until this is resolved, simplest is to just shrug
// our shoulders and not check
// synchronized (lock) {
// assert services.isEmpty() : services;
return exceptions;
}
// object state
private final Class<? extends ServiceManagerBase> serviceManagerInterfaceClass;
private final Collection<Class<?>> directlyRequiredClasses;
private final Set<Object> services;
private final Injector _injector;
// consts
private static final Comparator<? super Class<?>> BY_CLASS_NAME = new Comparator<Class<?>>() {
@Override
public int compare(Class<?> o1, Class<?> o2) {
return o1.getName().compareTo(o2.getName());
}
};
public List<Class<?>> servicesClassesInStartupOrder() {
List<Class<?>> result = new ArrayList<Class<?>>(services.size());
for (Object service : services) {
result.add(service.getClass());
}
return result;
}
// nested classes
private static final class ResolvedServiceBinding {
// ResolvedServiceBinding interface
public Class<?> serviceInterfaceClass() {
return serviceInterfaceClass;
}
public Class<?> serviceImplementationClass() {
return serviceImplementationClass;
}
public ResolvedServiceBinding(ServiceBinding serviceBinding) throws ClassNotFoundException {
ClassLoader loader = serviceBinding.getClassLoader();
this.serviceInterfaceClass = Class.forName(serviceBinding.getInterfaceName(), true, loader);
this.serviceImplementationClass = Class.forName(serviceBinding.getImplementingClassName(), true, loader);
if (!this.serviceInterfaceClass.isAssignableFrom(this.serviceImplementationClass)) {
throw new IllegalArgumentException(this.serviceInterfaceClass + " is not assignable from "
+ this.serviceImplementationClass);
}
}
// object state
private final Class<?> serviceInterfaceClass;
private final Class<?> serviceImplementationClass;
}
private static final class ServiceBindingsModule extends AbstractModule {
@Override
// we use unchecked, raw Class, relying on the invariant established by ResolvedServiceBinding's ctor
@SuppressWarnings("unchecked")
protected void configure() {
if (serviceManagerInterfaceClass != null)
bind((Class)serviceManagerInterfaceClass).toInstance(serviceManager);
for (ResolvedServiceBinding binding : bindings) {
Class unchecked = binding.serviceInterfaceClass();
bind(unchecked).to(binding.serviceImplementationClass()).in(Scopes.SINGLETON);
}
}
// ServiceBindingsModule interface
private ServiceBindingsModule(Class<? extends ServiceManagerBase> serviceManagerInterfaceClass, ServiceManagerBase serviceManager,
Collection<ResolvedServiceBinding> bindings)
{
this.serviceManagerInterfaceClass = serviceManagerInterfaceClass;
this.serviceManager = serviceManager;
this.bindings = bindings;
}
// object state
private final Class<? extends ServiceManagerBase> serviceManagerInterfaceClass;
private final ServiceManagerBase serviceManager;
private final Collection<ResolvedServiceBinding> bindings;
}
static interface ServiceLifecycleActions<T> {
void onStart(T service);
void onShutdown(T service);
/**
* Cast the given object to the actionable type if possible, or return {@code null} otherwise.
* @param object the object which may or may not be actionable
* @return the object reference, correctly casted; or null
*/
T castIfActionable(Object object);
}
}
|
package carve.webapp;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceProvider;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
public class GreetingCommand extends HystrixCommand<String> {
private static ServiceProvider<Object> serviceProvider;
public GreetingCommand() {
super(Setter.withGroupKey(
HystrixCommandGroupKey.Factory.asKey("greeting"))
.andCommandPropertiesDefaults(
HystrixCommandProperties.Setter()
.withCircuitBreakerRequestVolumeThreshold(5)));
}
static {
CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(
"localhost:2181", new RetryNTimes(5, 1000));
curatorFramework.start();
ServiceDiscovery<Object> serviceDiscovery = ServiceDiscoveryBuilder
.builder(Object.class).basePath("carve")
.client(curatorFramework).build();
try {
serviceDiscovery.start();
serviceProvider = serviceDiscovery.serviceProviderBuilder()
.serviceName("greeting").build();
serviceProvider.start();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Curator init failed");
}
}
@Override
protected String run() throws Exception {
String baseUri = serviceProvider.getInstance().buildUriSpec();
System.out.println("BaseUri: " + baseUri);
Client client = ClientBuilder.newClient();
String greeting = client
.target(baseUri + "/carve.greeting/v1/greeting/").request()
.get(String.class);
return greeting;
}
@Override
protected String getFallback() {
return "Fallback: hello";
}
}
|
package com.akiban.server.types3.common.funcs;
import com.akiban.server.types3.*;
import com.akiban.server.types3.common.types.StringAttribute;
import com.akiban.server.types3.pvalue.PValueSource;
import com.akiban.server.types3.pvalue.PValueTarget;
import com.akiban.server.types3.texpressions.TInputSetBuilder;
import com.akiban.server.types3.texpressions.TOverloadBase;
import java.util.List;
public abstract class Substring extends TOverloadBase {
public static TOverload[] create(TClass stringType, TClass numericType) {
TOverload twoArgs =
new Substring(stringType, numericType) {
@Override
protected void buildInputSets(TInputSetBuilder builder) {
builder.covers(stringType, 0);
builder.covers(numericType, 1);
}
@Override
protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output) {
String str = (String) inputs.get(0).getObject();
int from = adjustIndex(str, inputs.get(1).getInt32());
if (from == -1) {
output.putObject("");
} else {
output.putObject(getSubstring(str.length() - 1, from, str));
}
}
@Override
public TOverloadResult resultType() {
return TOverloadResult.custom(new TCustomOverloadResult() {
@Override
public TInstance resultInstance(List<TPreptimeValue> inputs, TPreptimeContext context) {
TPreptimeValue preptimeValue = inputs.get(0);
int stringLength = preptimeValue.instance().attribute(StringAttribute.LENGTH);
int stringCharsetId = preptimeValue.instance().attribute(StringAttribute.CHARSET);
final int offset, calculatedLength;
TPreptimeValue offsetValue = inputs.get(1);
if (offsetValue.value() == null) {
offset = 0; // assume string starts at beginning
} else {
offset = offsetValue.value().getInt32();
}
calculatedLength = calculateCharLength(stringLength, offset, Integer.MAX_VALUE);
return stringType.instance(calculatedLength, stringCharsetId);
}
});
}
};
TOverload threeArgs =
new Substring(stringType, numericType) {
@Override
protected void buildInputSets(TInputSetBuilder builder) {
builder.covers(stringType, 0);
builder.covers(numericType, 1, 2);
}
@Override
protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output) {
String str = (String) inputs.get(0).getObject();
int length = str.length();
int from = adjustIndex(str, inputs.get(1).getInt32());
if (from == -1) {
output.putObject("");
} else {
output.putObject(getSubstring(from + inputs.get(2).getInt32() - 1, from, str));
}
}
@Override
public TOverloadResult resultType() {
return TOverloadResult.custom(new TCustomOverloadResult() {
@Override
public TInstance resultInstance(List<TPreptimeValue> inputs, TPreptimeContext context) {
TPreptimeValue preptimeValue = inputs.get(0);
int stringLength = preptimeValue.instance().attribute(StringAttribute.LENGTH);
int stringCharsetId = preptimeValue.instance().attribute(StringAttribute.CHARSET);
final int offset, substringLength, calculatedLength;
TPreptimeValue offsetValue = inputs.get(1);
if (offsetValue.value() == null) {
offset = 0; // assume string starts at beginning
} else {
offset = offsetValue.value().getInt32();
}
TPreptimeValue substringLengthValue = inputs.get(2);
if (substringLengthValue.value() == null) {
substringLength = Integer.MAX_VALUE; // assume string is unbounded
} else {
substringLength = substringLengthValue.value().getInt32();
}
calculatedLength = calculateCharLength(stringLength, offset, substringLength);
return stringType.instance(calculatedLength, stringCharsetId);
}
});
}
};
return new TOverload[]{twoArgs, threeArgs};
}
protected final TClass stringType;
protected final TClass numericType;
private Substring(TClass stringType, TClass numericType) {
this.stringType = stringType;
this.numericType = numericType;
}
@Override
public String overloadName() {
return "SUBSTRING";
}
protected int adjustIndex(String str, int index) {
// String operand
if (str.equals("")) {
return -1;
}
// if from is negative or zero, start from the end, and adjust
// index by 1 since index in sql starts at 1 NOT 0
index += (index < 0 ? str.length() : -1);
// if from is still neg, return -1
if (index < 0) {
return -1;
}
return index;
}
protected String getSubstring(int to, int from, String str) {
// if to <= fr => return empty
if (to < from || from >= str.length()) {
return "";
}
to = (to > str.length() - 1 ? str.length() - 1 : to);
return str.substring(from, to + 1);
}
protected int calculateCharLength(int stringLength, int offset, int substringLength) {
if (stringLength < Math.abs(offset) || substringLength <= 0) {
return 0;
}
int ret = offset > 0 ? stringLength - offset + 1 : offset * -1;
return Math.min(ret, substringLength);
}
}
|
package ch.tkuhn.memetools;
import java.util.ArrayList;
import java.util.List;
public class DataEntry {
public static final String SEP = " ";
private String doi;
private String date;
private String text;
private List<String> citedText;
public DataEntry(String doi, String date, String text, List<String> citedText) {
this.doi = doi;
this.date = date;
this.text = text;
this.citedText = citedText;
}
public DataEntry(String doi, String date, String text) {
this(doi, date, text, new ArrayList<String>());
}
public DataEntry(String line) {
String[] splitline = line.split(" ");
if (splitline.length < 3) {
throw new RuntimeException("Invalid line: " + line);
}
date = splitline[0];
doi = splitline[1];
text = splitline[2];
citedText = new ArrayList<String>();
for (int i = 3 ; i < splitline.length ; i++) {
citedText.add(splitline[i]);
}
}
public String getDoi() {
return doi;
}
public String getDate() {
return date;
}
public int getYear() {
return Integer.parseInt(date.substring(0, 4));
}
public String getText() {
return text;
}
public List<String> getCitedText() {
return citedText;
}
public void addCitedText(String t) {
citedText.add(t);
}
public String getLine() {
String line = date + SEP + doi + SEP + text;
for (String c : citedText) {
line += SEP + c;
}
return line;
}
}
|
package com.yahoo.vespa.testrunner;
import ai.vespa.hosted.api.TestConfig;
import com.google.inject.Inject;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;
import com.yahoo.slime.SlimeUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Optional;
import java.util.SortedMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.stream.Stream;
import static com.yahoo.vespa.testrunner.TestRunner.Status.ERROR;
import static com.yahoo.vespa.testrunner.TestRunner.Status.FAILURE;
import static com.yahoo.vespa.testrunner.TestRunner.Status.RUNNING;
import static com.yahoo.vespa.testrunner.TestRunner.Status.SUCCESS;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* @author jonmv
*/
public class VespaCliTestRunner implements TestRunner {
private static final Logger logger = Logger.getLogger(VespaCliTestRunner.class.getName());
private final SortedMap<Long, LogRecord> log = new ConcurrentSkipListMap<>();
private final Path artifactsPath;
private AtomicReference<Status> status = new AtomicReference<>(Status.NOT_STARTED);
@Inject
public VespaCliTestRunner(VespaCliTestRunnerConfig config) {
this(config.artifactsPath().resolve("artifacts"));
}
VespaCliTestRunner(Path artifactsPath) {
this.artifactsPath = artifactsPath;
}
@Override
public Collection<LogRecord> getLog(long after) {
return log.tailMap(after + 1).values();
}
@Override
public Status getStatus() {
return status.get();
}
@Override
public CompletableFuture<?> test(Suite suite, byte[] config) {
if (status.getAndSet(RUNNING) == RUNNING)
throw new IllegalStateException("Tests already running, not supposed to be started now");
return CompletableFuture.runAsync(() -> runTests(suite, config));
}
@Override
public boolean isSupported() {
return getChildDirectory(artifactsPath, "tests").isPresent();
}
void runTests(Suite suite, byte[] config) {
Process process = null;
try {
process = testRunProcessBuilder(suite, toEndpointsConfig(config)).start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
in.lines().forEach(line -> {
if (line.length() > 1 << 13)
line = line.substring(0, 1 << 13) + " ... (this log entry was truncated due to size)";
log(Level.INFO, line, null);
});
status.set(process.waitFor() == 0 ? SUCCESS : process.waitFor() == 3 ? FAILURE : ERROR);
}
catch (Exception e) {
if (process != null)
process.destroyForcibly();
log(Level.SEVERE, "Failed running tests", e);
status.set(ERROR);
}
}
ProcessBuilder testRunProcessBuilder(Suite suite, String endpointsConfig) {
Path suitePath = getChildDirectory(artifactsPath, "tests")
.flatMap(testsPath -> getChildDirectory(testsPath, toSuiteDirectoryName(suite)))
.orElseThrow(() -> new IllegalStateException("No tests found, for suite '" + suite + "'"));
ProcessBuilder builder = new ProcessBuilder("vespa", "test", "--endpoints", endpointsConfig);
builder.redirectErrorStream(true);
builder.directory(suitePath.toFile());
return builder;
}
private static String toSuiteDirectoryName(Suite suite) {
switch (suite) {
case SYSTEM_TEST: return "system-test";
case STAGING_SETUP_TEST: return "staging-setup";
case STAGING_TEST: return "staging-test";
default: throw new IllegalArgumentException("Unsupported test suite '" + suite + "'");
}
}
private void log(Level level, String message, Throwable thrown) {
LogRecord record = new LogRecord(level, message);
record.setThrown(thrown);
logger.log(record);
log.put(record.getSequenceNumber(), record);
}
private static Optional<Path> getChildDirectory(Path parent, String name) {
try (Stream<Path> children = Files.list(parent)) {
return children.filter(Files::isDirectory)
.filter(path -> path.endsWith(name))
.findAny();
}
catch (IOException e) {
throw new UncheckedIOException("Failed to list files under " + parent, e);
}
}
static String toEndpointsConfig(byte[] testConfig) throws IOException {
TestConfig config = TestConfig.fromJson(testConfig);
Cursor root = new Slime().setObject();
Cursor endpointsArray = root.setArray("endpoints");
config.deployments().get(config.zone()).forEach((cluster, url) -> {
Cursor endpointObject = endpointsArray.addObject();
endpointObject.setString("cluster", cluster);
endpointObject.setString("url", url.toString());
});
return new String(SlimeUtils.toJsonBytes(root), UTF_8);
}
}
|
package com.ankurdave.part;
class ArtNode48 extends ArtNode {
public static int count;
public ArtNode48() {
super();
count++;
}
public ArtNode48(final ArtNode48 other) {
super(other);
System.arraycopy(other.keys, 0, keys, 0, 256);
// Copy the children. We have to look at all elements of `children`
// rather than just the first num_children elements because `children`
// may not be contiguous due to deletion
for (int i = 0; i < 48; i++) {
children[i] = other.children[i];
if (children[i] != null) {
children[i].refcount++;
}
}
count++;
}
public ArtNode48(final ArtNode16 other) {
this();
// ArtNode
this.num_children = other.num_children;
this.partial_len = other.partial_len;
System.arraycopy(other.partial, 0, this.partial, 0,
Math.min(MAX_PREFIX_LEN, this.partial_len));
// ArtNode48 from ArtNode16
for (int i = 0; i < this.num_children; i++) {
keys[to_uint(other.keys[i])] = (byte)(i + 1);
children[i] = other.children[i];
children[i].refcount++;
}
}
public ArtNode48(final ArtNode256 other) {
this();
assert(other.num_children <= 48);
// ArtNode
this.num_children = other.num_children;
this.partial_len = other.partial_len;
System.arraycopy(other.partial, 0, this.partial, 0,
Math.min(MAX_PREFIX_LEN, this.partial_len));
// ArtNode48 from ArtNode256
int pos = 0;
for (int i = 0; i < 256; i++) {
if (other.children[i] != null) {
keys[i] = (byte)(pos + 1);
children[pos] = other.children[i];
children[pos].refcount++;
pos++;
}
}
}
@Override public Node n_clone() {
return new ArtNode48(this);
}
@Override public ChildPtr find_child(byte c) {
int idx = to_uint(keys[to_uint(c)]);
if (idx != 0) return new ArrayChildPtr(children, idx - 1);
return null;
}
@Override public Leaf minimum() {
int idx = 0;
while (keys[idx] == 0) idx++;
Node child = children[to_uint(keys[idx]) - 1];
return Node.minimum(child);
}
@Override public void add_child(ChildPtr ref, byte c, Node child) {
if (this.num_children < 48) {
// Have to do a linear scan because deletion may create holes in
// children array
int pos = 0;
while (children[pos] != null) pos++;
this.children[pos] = child;
child.refcount++;
this.keys[to_uint(c)] = (byte)(pos + 1);
this.num_children++;
} else {
// Copy the node48 into a new node256
ArtNode256 result = new ArtNode256(this);
// Update the parent pointer to the node256
ref.change(result);
// Insert the element into the node256 instead
result.add_child(ref, c, child);
}
}
@Override public void remove_child(ChildPtr ref, byte c) {
// Delete the child, leaving a hole in children. We can't shift children
// because that would require decrementing many elements of keys
int pos = to_uint(keys[to_uint(c)]);
keys[to_uint(c)] = 0;
children[pos - 1].decrement_refcount();
children[pos - 1] = null;
num_children
if (num_children == 12) {
ArtNode16 result = new ArtNode16(this);
ref.change(result);
}
}
@Override public void iter(IterCallback cb) {
for (int i = 0; i < 256; i++) {
int idx = to_uint(keys[i]);
if (idx != 0) {
Node.iter(children[idx - 1], cb);
}
}
}
@Override public boolean exhausted(int c) {
for (int i = c; i < 256; i++) {
if (keys[i] != 0) {
return false;
}
}
return true;
}
@Override public int nextChildAtOrAfter(int c) {
int pos = c;
for (; pos < 256; pos++) {
if (keys[pos] != 0) {
break;
}
}
return pos;
}
@Override public Node childAt(int c) {
return children[to_uint(keys[c]) - 1];
}
@Override public int decrement_refcount() {
if (--this.refcount <= 0) {
int freed = 0;
for (int i = 0; i < this.num_children; i++) {
if (children[i] != null) {
freed += children[i].decrement_refcount();
}
}
count
// delete this;
return freed + 728;
// object size (8) + refcount (4) +
// num_children int (4) + partial_len int (4) +
// pointer to partial array (8) + partial array size (8+4+1*MAX_PREFIX_LEN)
// pointer to key array (8) + key array size (8+4+1*256) +
// pointer to children array (8) + children array size (8+4+8*48)
}
return 0;
}
byte[] keys = new byte[256];
Node[] children = new Node[48];
}
|
package nl.fontys.sofa.limo.view.topcomponent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.IntrospectionException;
import java.beans.PropertyVetoException;
import java.io.IOException;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.OverlayLayout;
import javax.swing.border.LineBorder;
import nl.fontys.sofa.limo.api.exception.ServiceNotFoundException;
import nl.fontys.sofa.limo.domain.component.SupplyChain;
import nl.fontys.sofa.limo.view.action.DeleteAction;
import nl.fontys.sofa.limo.view.chain.ChainGraphScene;
import nl.fontys.sofa.limo.view.chain.ChainGraphSceneImpl;
import nl.fontys.sofa.limo.view.chain.ChainPaletteFactory;
import nl.fontys.sofa.limo.view.chain.ChainToolbar;
import nl.fontys.sofa.limo.view.node.bean.AbstractBeanNode;
import nl.fontys.sofa.limo.view.util.LIMOResourceBundle;
import org.netbeans.spi.palette.PaletteController;
import org.openide.awt.ActionID;
import org.openide.awt.UndoRedo;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.util.lookup.Lookups;
import org.openide.util.lookup.ProxyLookup;
import org.openide.windows.TopComponent;
/**
* Top component which displays a GraphScene and Palette to build a chain with.
*/
@TopComponent.Description(
preferredID = "ChainBuilderTopComponent",
iconBase = "icons/gui/Link.png",
persistenceType = TopComponent.PERSISTENCE_NEVER
)
@TopComponent.Registration(
mode = "editor",
openAtStartup = false
)
@ActionID(
category = "Window",
id = "nl.fontys.sofa.limo.view.topcomponent.ChainBuilderTopComponent"
)
@NbBundle.Messages({
"CTL_ChainBuilderAction=New Supply Chain..",
"CTL_ChainBuilderTopComponent=New Supply Chain"
})
public final class ChainBuilderTopComponent extends TopComponent
implements DynamicExplorerManagerProvider {
private ExplorerManager em = new ExplorerManager();
private ChainGraphScene graphScene;
private InstanceContent ic = new InstanceContent();
SavableComponent savable;
private UndoRedo.Manager undoManager = new UndoRedo.Manager();
private PaletteController paletteController;
/**
* Constructor creates a new ChainBuilderTopComponent.
*
*/
public ChainBuilderTopComponent(String name) {
try {
paletteController = ChainPaletteFactory.createPalette();
DeleteAction.setPallete(paletteController);
} catch (ServiceNotFoundException ex) {
Exceptions.printStackTrace(ex);
}
initComponents();
initCustomComponents();
SupplyChain chain = graphScene.getSupplyChain();
chain.setName(name);
setName(name);
savable = new SavableComponent(graphScene.getChainBuilder(),ic,this);
Lookup paletteLookup = Lookups.singleton(paletteController);
Lookup nodeLookup = ExplorerUtils.createLookup(em, getActionMap());
Lookup graphLookup = Lookups.singleton(graphScene);
Lookup graphContentLookup = graphScene.getLookup();
Lookup instanceContent = new AbstractLookup(ic);
ProxyLookup pl = new ProxyLookup(graphContentLookup, paletteLookup, nodeLookup, graphLookup, instanceContent);
associateLookup(pl);
}
private void initCustomComponents() {
setLayout(new BorderLayout());
SupplyChain chain = new SupplyChain();
try {
ChainToolbar toolbar = new ChainToolbar();
add(toolbar, BorderLayout.NORTH);
graphScene = new ChainGraphSceneImpl(this, chain, undoManager, paletteController);
JPanel viewPanel = new JPanel(new BorderLayout());
JScrollPane scroll = new JScrollPane(
graphScene.createView(),
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
viewPanel.add(scroll, BorderLayout.CENTER);
JPanel satellitePanel = new JPanel();
satellitePanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.insets = new Insets(0, 0, 25, 25);
gbc.anchor = GridBagConstraints.SOUTHEAST;
JComponent view = graphScene.createSatelliteView();
JPanel holder = new JPanel(new BorderLayout());
holder.setBorder(new LineBorder(Color.LIGHT_GRAY, 1));
holder.add(view);
satellitePanel.add(holder, gbc);
satellitePanel.setOpaque(false);
JLayeredPane panel = new JLayeredPane();
panel.setLayout(new OverlayLayout(panel));
panel.add(viewPanel, JLayeredPane.DEFAULT_LAYER);
panel.add(satellitePanel, JLayeredPane.PALETTE_LAYER);
add(panel);
} catch (IOException | IntrospectionException ex) {
Exceptions.printStackTrace(ex);
}
}
@Override
public ExplorerManager getExplorerManager() {
return em;
}
@Override
public void setRootContext(AbstractBeanNode node) {
em.setRootContext(node);
try {
em.setSelectedNodes(new Node[]{node});
} catch (PropertyVetoException ex) {
Exceptions.printStackTrace(ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
// add custom code on component opening
}
@Override
public void componentClosed() {
}
@Override
public UndoRedo getUndoRedo() {
return undoManager;
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
p.setProperty("version", "1.0");
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
}
}
|
package com.bapcraft.bclotto;
import java.util.ArrayList;
import org.bukkit.plugin.java.JavaPlugin;
import com.bapcraft.bclotto.commands.CommandAddTicket;
import com.bapcraft.bclotto.commands.CommandCheckPot;
public class BCLotto extends JavaPlugin {
public static final String NAME_ADD_TICKET_COMMAND = "addbcticket";
public static final String NAME_CHECK_POT_COMMAND = "buycraftlottocheck";
public static BCLotto instance = null;
public Drawing activeDrawing = null;
public ArrayList<Drawing> previousDrawings = new ArrayList<Drawing>();
@Override
public void onEnable() {
instance = this;
this.getCommand(NAME_ADD_TICKET_COMMAND).setExecutor(new CommandAddTicket());
this.getCommand(NAME_CHECK_POT_COMMAND).setExecutor(new CommandCheckPot());
}
@Override
public void onDisable() {
instance = null;
}
}
|
package com.censoredsoftware.demigods.player;
import java.util.*;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import com.censoredsoftware.demigods.ability.Ability;
import com.censoredsoftware.demigods.battle.Participant;
import com.censoredsoftware.demigods.data.DataManager;
import com.censoredsoftware.demigods.deity.Deity;
import com.censoredsoftware.demigods.item.DItemStack;
import com.censoredsoftware.demigods.language.Symbol;
import com.censoredsoftware.demigods.location.DLocation;
import com.censoredsoftware.demigods.structure.Structure;
import com.censoredsoftware.demigods.util.Configs;
import com.censoredsoftware.demigods.util.Messages;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
public class DCharacter implements Participant, ConfigurationSerializable
{
private UUID id;
private String name;
private String player;
private boolean alive;
private double health;
private Integer hunger;
private Float experience;
private Integer level;
private Integer killCount;
private UUID location;
private UUID bedSpawn;
private String deity;
private Set<String> minorDeities;
private boolean active;
private boolean usable;
private UUID meta;
private UUID inventory;
private Set<String> potionEffects;
private Set<String> deaths;
public DCharacter()
{
deaths = Sets.newHashSet();
potionEffects = Sets.newHashSet();
minorDeities = Sets.newHashSet();
}
public DCharacter(UUID id, ConfigurationSection conf)
{
this.id = id;
name = conf.getString("name");
player = conf.getString("player");
if(conf.isBoolean("alive")) alive = conf.getBoolean("alive");
health = conf.getDouble("health");
hunger = conf.getInt("hunger");
experience = Float.valueOf(conf.getString("experience"));
level = conf.getInt("level");
killCount = conf.getInt("killCount");
location = UUID.fromString(conf.getString("location"));
if(conf.getString("bedSpawn") != null) bedSpawn = UUID.fromString(conf.getString("bedSpawn"));
deity = conf.getString("deity");
active = conf.getBoolean("active");
usable = conf.getBoolean("usable");
meta = UUID.fromString(conf.getString("meta"));
if(conf.isList("minorDeities")) minorDeities = Sets.newHashSet(conf.getStringList("minorDeities"));
if(conf.isString("inventory")) inventory = UUID.fromString(conf.getString("inventory"));
if(conf.isList("deaths")) deaths = Sets.newHashSet(conf.getStringList("deaths"));
if(conf.isList("potionEffects")) potionEffects = Sets.newHashSet(conf.getStringList("potionEffects"));
}
@Override
public Map<String, Object> serialize()
{
Map<String, Object> map = Maps.newHashMap();
map.put("name", name);
map.put("player", player);
map.put("alive", alive);
map.put("health", health);
map.put("hunger", hunger);
map.put("experience", experience);
map.put("level", level);
map.put("killCount", killCount);
map.put("location", location.toString());
if(bedSpawn != null) map.put("bedSpawn", bedSpawn.toString());
map.put("deity", deity);
if(minorDeities != null) map.put("minorDeities", Lists.newArrayList(minorDeities));
map.put("active", active);
map.put("usable", usable);
map.put("meta", meta.toString());
if(inventory != null) map.put("inventory", inventory.toString());
if(deaths != null) map.put("deaths", Lists.newArrayList(deaths));
if(potionEffects != null) map.put("potionEffects", Lists.newArrayList(potionEffects));
return map;
}
void generateId()
{
id = UUID.randomUUID();
}
void setName(String name)
{
this.name = name;
}
void setDeity(Deity deity)
{
this.deity = deity.getName();
}
void setMinorDeities(Set<String> set)
{
this.minorDeities = set;
}
public void addMinorDeity(Deity deity)
{
this.minorDeities.add(deity.getName());
}
public void removeMinorDeity(Deity deity)
{
this.minorDeities.remove(deity.getName());
}
void setPlayer(DPlayer player)
{
this.player = player.getPlayerName();
}
public void setActive(boolean option)
{
this.active = option;
Util.save(this);
}
public void saveInventory()
{
this.inventory = Util.createInventory(this).getId();
Util.save(this);
}
public void setAlive(boolean alive)
{
this.alive = alive;
Util.save(this);
}
public void setHealth(double health)
{
this.health = health;
}
public void setHunger(int hunger)
{
this.hunger = hunger;
}
public void setLevel(int level)
{
this.level = level;
}
public void setExperience(float exp)
{
this.experience = exp;
}
public void setLocation(Location location)
{
this.location = DLocation.Util.create(location).getId();
}
public void setBedSpawn(Location location)
{
this.bedSpawn = DLocation.Util.create(location).getId();
}
public void setMeta(Meta meta)
{
this.meta = meta.getId();
}
public void setUsable(boolean usable)
{
this.usable = usable;
}
public void setPotionEffects(Collection<PotionEffect> potions)
{
if(potions != null)
{
if(potionEffects == null) potionEffects = Sets.newHashSet();
for(PotionEffect potion : potions)
potionEffects.add((new SavedPotion(potion)).getId().toString());
}
}
public Set<PotionEffect> getPotionEffects()
{
if(potionEffects == null) potionEffects = Sets.newHashSet();
Set<PotionEffect> set = new HashSet<PotionEffect>();
for(String stringId : potionEffects)
{
try
{
PotionEffect potion = Util.getSavedPotion(UUID.fromString(stringId)).toPotionEffect();
if(potion != null)
{
DataManager.savedPotions.remove(UUID.fromString(stringId));
set.add(potion);
}
}
catch(Exception ignored)
{}
}
potionEffects.clear();
return set;
}
public Inventory getInventory()
{
if(Util.getInventory(inventory) == null) inventory = Util.createEmptyInventory().getId();
return Util.getInventory(inventory);
}
public Meta getMeta()
{
return Util.loadMeta(meta);
}
public OfflinePlayer getOfflinePlayer()
{
return Bukkit.getOfflinePlayer(player);
}
public String getName()
{
return name;
}
public boolean isActive()
{
return active;
}
public Location getLocation()
{
if(location == null) return null;
return DLocation.Util.load(location).toLocation();
}
public Location getBedSpawn()
{
if(bedSpawn == null) return null;
return DLocation.Util.load(bedSpawn).toLocation();
}
public Location getCurrentLocation()
{
if(getOfflinePlayer().isOnline()) return getOfflinePlayer().getPlayer().getLocation();
return getLocation();
}
@Override
public DCharacter getRelatedCharacter()
{
return this;
}
@Override
public LivingEntity getEntity()
{
return getOfflinePlayer().getPlayer();
}
public String getPlayer()
{
return player;
}
public Integer getLevel()
{
return level;
}
public boolean isAlive()
{
return alive;
}
public Double getHealth()
{
return health;
}
public Double getMaxHealth()
{
return getDeity().getMaxHealth();
}
public Integer getHunger()
{
return hunger;
}
public Float getExperience()
{
return experience;
}
public boolean isDeity(String deityName)
{
return getDeity().getName().equalsIgnoreCase(deityName);
}
public Deity getDeity()
{
return Deity.Util.getDeity(this.deity);
}
public Collection<Deity> getMinorDeities()
{
return Collections2.transform(minorDeities, new Function<String, Deity>()
{
@Override
public Deity apply(String deity)
{
return Deity.Util.getDeity(deity);
}
});
}
public String getAlliance()
{
return getDeity().getAlliance();
}
public int getKillCount()
{
return killCount;
}
public void setKillCount(int amount)
{
killCount = amount;
Util.save(this);
}
public void addKill()
{
killCount += 1;
Util.save(this);
}
public int getDeathCount()
{
return deaths.size();
}
public void addDeath()
{
if(deaths == null) deaths = Sets.newHashSet();
deaths.add(new Death(this).getId().toString());
Util.save(this);
}
public void addDeath(DCharacter attacker)
{
deaths.add(new Death(this, attacker).getId().toString());
Util.save(this);
}
public Collection<Death> getDeaths()
{
if(deaths == null) deaths = Sets.newHashSet();
return Collections2.transform(deaths, new Function<String, Death>()
{
@Override
public Death apply(String s)
{
try
{
return Death.Util.load(UUID.fromString(s));
}
catch(Exception ignored)
{}
return null;
}
});
}
public int getFavorRegen()
{
int favorRegenSkill = getMeta().getSkill(Skill.Type.FAVOR) != null ? 2 * getMeta().getSkill(Skill.Type.FAVOR).getLevel() : 0;
int regenRate = (int) Math.ceil(Configs.getSettingDouble("multipliers.favor") * getDeity().getFavorRegen() + favorRegenSkill);
if(regenRate < 30) regenRate = 30;
return regenRate;
}
@Override
public void setCanPvp(boolean pvp)
{
DPlayer.Util.getPlayer(getOfflinePlayer()).setCanPvp(pvp);
}
@Override
public Boolean canPvp()
{
return DPlayer.Util.getPlayer(getOfflinePlayer()).canPvp();
}
@Override
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
public boolean isUsable()
{
return usable;
}
public void updateUseable()
{
usable = Deity.Util.getDeity(this.deity) != null;
}
public UUID getId()
{
return id;
}
public void remove()
{
for(Structure structureSave : Structure.Util.getStructureWithFlag(Structure.Flag.DELETE_WITH_OWNER))
if(structureSave.hasOwner() && structureSave.getOwner().equals(getId())) structureSave.remove();
Util.deleteInventory(getInventory().getId());
Util.deleteMeta(getMeta().getId());
Util.delete(getId());
DPlayer.Util.getPlayer(getOfflinePlayer()).resetCurrent();
}
public void sendAllianceMessage(String message)
{
DemigodsChatEvent chatEvent = new DemigodsChatEvent(message, DCharacter.Util.getOnlineCharactersWithAlliance(getAlliance()));
Bukkit.getPluginManager().callEvent(chatEvent);
if(!chatEvent.isCancelled()) for(Player player : chatEvent.getRecipients())
player.sendMessage(message);
}
public void chatWithAlliance(String message)
{
sendAllianceMessage(ChatColor.DARK_AQUA + " " + Symbol.WRITING_HAND + " " + getDeity().getColor() + name + ChatColor.GRAY + ": " + ChatColor.RESET + message);
Messages.info("[" + getAlliance() + "]" + name + ": " + message);
}
public static class Inventory implements ConfigurationSerializable
{
private UUID id;
private UUID helmet;
private UUID chestplate;
private UUID leggings;
private UUID boots;
private String[] items;
public Inventory()
{}
public Inventory(UUID id, ConfigurationSection conf)
{
this.id = id;
if(conf.getString("helmet") != null) helmet = UUID.fromString(conf.getString("helmet"));
if(conf.getString("chestplate") != null) chestplate = UUID.fromString(conf.getString("chestplate"));
if(conf.getString("leggings") != null) leggings = UUID.fromString(conf.getString("leggings"));
if(conf.getString("boots") != null) boots = UUID.fromString(conf.getString("boots"));
if(conf.getStringList("items") != null)
{
List<String> stringItems = conf.getStringList("items");
items = new String[stringItems.size()];
for(int i = 0; i < stringItems.size(); i++)
items[i] = stringItems.get(i);
}
}
@Override
public Map<String, Object> serialize()
{
Map<String, Object> map = Maps.newHashMap();
if(helmet != null) map.put("helmet", helmet.toString());
if(chestplate != null) map.put("chestplate", chestplate.toString());
if(leggings != null) map.put("leggings", leggings.toString());
if(boots != null) map.put("boots", boots.toString());
if(items != null) map.put("items", Lists.newArrayList(items));
return map;
}
public void generateId()
{
id = UUID.randomUUID();
}
void setHelmet(ItemStack helmet)
{
this.helmet = DItemStack.Util.create(helmet).getId();
}
void setChestplate(ItemStack chestplate)
{
this.chestplate = DItemStack.Util.create(chestplate).getId();
}
void setLeggings(ItemStack leggings)
{
this.leggings = DItemStack.Util.create(leggings).getId();
}
void setBoots(ItemStack boots)
{
this.boots = DItemStack.Util.create(boots).getId();
}
void setItems(org.bukkit.inventory.Inventory inventory)
{
if(this.items == null) this.items = new String[36];
for(int i = 0; i < 35; i++)
{
if(inventory.getItem(i) == null) this.items[i] = DItemStack.Util.create(new ItemStack(Material.AIR)).getId().toString();
else this.items[i] = DItemStack.Util.create(inventory.getItem(i)).getId().toString();
}
}
public UUID getId()
{
return this.id;
}
public ItemStack getHelmet()
{
if(this.helmet == null) return null;
DItemStack item = DItemStack.Util.load(this.helmet);
if(item != null) return item.toItemStack();
return null;
}
public ItemStack getChestplate()
{
if(this.chestplate == null) return null;
DItemStack item = DItemStack.Util.load(this.chestplate);
if(item != null) return item.toItemStack();
return null;
}
public ItemStack getLeggings()
{
if(this.leggings == null) return null;
DItemStack item = DItemStack.Util.load(this.leggings);
if(item != null) return item.toItemStack();
return null;
}
public ItemStack getBoots()
{
if(this.boots == null) return null;
DItemStack item = DItemStack.Util.load(this.boots);
if(item != null) return item.toItemStack();
return null;
}
/**
* Applies this inventory to the given <code>player</code>.
*
* @param player the player for whom apply the inventory.
*/
public void setToPlayer(Player player)
{
// Define the inventory
PlayerInventory inventory = player.getInventory();
// Clear it all first
inventory.clear();
inventory.setHelmet(new ItemStack(Material.AIR));
inventory.setChestplate(new ItemStack(Material.AIR));
inventory.setLeggings(new ItemStack(Material.AIR));
inventory.setBoots(new ItemStack(Material.AIR));
// Set the armor contents
if(getHelmet() != null) inventory.setHelmet(getHelmet());
if(getChestplate() != null) inventory.setChestplate(getChestplate());
if(getLeggings() != null) inventory.setLeggings(getLeggings());
if(getBoots() != null) inventory.setBoots(getBoots());
if(this.items != null)
{
// Set items
for(int i = 0; i < 35; i++)
{
if(this.items[i] != null)
{
ItemStack itemStack = DItemStack.Util.load(UUID.fromString(this.items[i])).toItemStack();
if(itemStack != null) inventory.setItem(i, DItemStack.Util.load(UUID.fromString(this.items[i])).toItemStack());
}
}
}
// Delete
Util.deleteInventory(id);
}
}
public static class Meta implements ConfigurationSerializable
{
private UUID id;
private int favor;
private int maxFavor;
private int skillPoints;
private Set<String> notifications;
private Map<String, Object> binds;
private Map<String, Object> skillData;
private Map<String, Object> warps;
private Map<String, Object> invites;
public Meta()
{}
public Meta(UUID id, ConfigurationSection conf)
{
this.id = id;
favor = conf.getInt("favor");
maxFavor = conf.getInt("maxFavor");
skillPoints = conf.getInt("skillPoints");
notifications = Sets.newHashSet(conf.getStringList("notifications"));
if(conf.getConfigurationSection("skillData") != null) skillData = conf.getConfigurationSection("skillData").getValues(false);
if(conf.getConfigurationSection("binds") != null) binds = conf.getConfigurationSection("binds").getValues(false);
if(conf.getConfigurationSection("warps") != null) warps = conf.getConfigurationSection("warps").getValues(false);
if(conf.getConfigurationSection("invites") != null) invites = conf.getConfigurationSection("invites").getValues(false);
}
@Override
public Map<String, Object> serialize()
{
Map<String, Object> map = Maps.newHashMap();
map.put("favor", favor);
map.put("maxFavor", maxFavor);
map.put("skillPoints", skillPoints);
map.put("notifications", Lists.newArrayList(notifications));
map.put("binds", binds);
map.put("skillData", skillData);
map.put("warps", warps);
map.put("invites", invites);
return map;
}
public void generateId()
{
id = UUID.randomUUID();
}
void initialize()
{
this.notifications = Sets.newHashSet();
this.warps = Maps.newHashMap();
this.invites = Maps.newHashMap();
this.skillData = Maps.newHashMap();
this.binds = Maps.newHashMap();
}
public UUID getId()
{
return this.id;
}
public void setSkillPoints(int skillPoints)
{
this.skillPoints = skillPoints;
}
public int getSkillPoints()
{
return skillPoints;
}
public void addSkillPoints(int skillPoints)
{
setSkillPoints(getSkillPoints() + skillPoints);
}
public void subtractSkillPoints(int skillPoints)
{
setSkillPoints(getSkillPoints() - skillPoints);
}
public void addNotification(Notification notification)
{
getNotifications().add(notification.getId().toString());
Util.saveMeta(this);
}
public void removeNotification(Notification notification)
{
getNotifications().remove(notification.getId().toString());
Util.saveMeta(this);
}
public Set<String> getNotifications()
{
if(this.notifications == null) this.notifications = Sets.newHashSet();
return this.notifications;
}
public void clearNotifications()
{
notifications.clear();
}
public boolean hasNotifications()
{
return !this.notifications.isEmpty();
}
public void addWarp(String name, Location location)
{
warps.put(name.toLowerCase(), DLocation.Util.create(location).getId().toString());
Util.saveMeta(this);
}
public void removeWarp(String name)
{
getWarps().remove(name.toLowerCase());
Util.saveMeta(this);
}
public Map<String, Object> getWarps()
{
if(this.warps == null) this.warps = Maps.newHashMap();
return this.warps;
}
public void clearWarps()
{
getWarps().clear();
}
public boolean hasWarps()
{
return !this.warps.isEmpty();
}
public void addInvite(String name, Location location)
{
getInvites().put(name.toLowerCase(), DLocation.Util.create(location).getId().toString());
Util.saveMeta(this);
}
public void removeInvite(String name)
{
getInvites().remove(name.toLowerCase());
Util.saveMeta(this);
}
public Map<String, Object> getInvites()
{
if(this.invites == null) this.invites = Maps.newHashMap();
return this.invites;
}
public void clearInvites()
{
invites.clear();
}
public boolean hasInvites()
{
return !this.invites.isEmpty();
}
public void resetSkills()
{
getRawSkills().clear();
for(Skill.Type type : Skill.Type.values())
if(type.isDefault()) addSkill(Skill.Util.createSkill(type));
}
public void cleanSkills()
{
List<String> toRemove = Lists.newArrayList();
// Locate obselete skills
for(String skillName : getRawSkills().keySet())
{
try
{
// Attempt to find the value of the skillname
Skill.Type.valueOf(skillName.toUpperCase());
}
catch(Exception ignored)
{
// There was an error. Catch it and remove the skill.
toRemove.add(skillName);
}
}
// Remove the obsolete skills
for(String skillName : toRemove)
getRawSkills().remove(skillName);
}
public void addSkill(Skill skill)
{
if(!getRawSkills().containsKey(skill.getType().toString())) getRawSkills().put(skill.getType().toString(), skill.getId().toString());
Util.saveMeta(this);
}
public Skill getSkill(Skill.Type type)
{
if(getRawSkills().containsKey(type.toString())) return Skill.Util.loadSkill(UUID.fromString(getRawSkills().get(type.toString()).toString()));
return null;
}
public Map<String, Object> getRawSkills()
{
if(skillData == null) skillData = Maps.newHashMap();
return skillData;
}
public Collection<Skill> getSkills()
{
return Collections2.transform(getRawSkills().values(), new Function<Object, Skill>()
{
@Override
public Skill apply(Object obj)
{
return Skill.Util.loadSkill(UUID.fromString(obj.toString()));
}
});
}
public boolean checkBound(String abilityName, Material material)
{
return getBinds().containsKey(abilityName) && binds.get(abilityName).equals(material.name());
}
public boolean isBound(Ability ability)
{
return getBinds().containsKey(ability.getName());
}
public boolean isBound(Material material)
{
return getBinds().containsValue(material.name());
}
public void setBind(Ability ability, Material material)
{
getBinds().put(ability.getName(), material.name());
}
public Map<String, Object> getBinds()
{
if(binds == null) binds = Maps.newHashMap();
return this.binds;
}
public void removeBind(Ability ability)
{
getBinds().remove(ability.getName());
}
public void removeBind(Material material)
{
if(getBinds().containsValue(material.name()))
{
String toRemove = null;
for(Map.Entry<String, Object> entry : getBinds().entrySet())
{
toRemove = entry.getValue().equals(material.name()) ? entry.getKey() : null;
}
getBinds().remove(toRemove);
}
}
public int getAscensions()
{
return 1; // TODO
}
public Integer getFavor()
{
return favor;
}
public void setFavor(int amount)
{
favor = amount;
Util.saveMeta(this);
}
public void addFavor(int amount)
{
if((favor + amount) > maxFavor) favor = maxFavor;
else favor += amount;
Util.saveMeta(this);
}
public void subtractFavor(int amount)
{
if((favor - amount) < 0) favor = 0;
else favor -= amount;
Util.saveMeta(this);
}
public Integer getMaxFavor()
{
return maxFavor;
}
public void addMaxFavor(int amount)
{
if((maxFavor + amount) > Configs.getSettingInt("caps.favor")) maxFavor = Configs.getSettingInt("caps.favor");
else maxFavor += amount;
Util.saveMeta(this);
}
public void setMaxFavor(int amount)
{
if(amount < 0) maxFavor = 0;
if(amount > Configs.getSettingInt("caps.favor")) maxFavor = Configs.getSettingInt("caps.favor");
else maxFavor = amount;
Util.saveMeta(this);
}
public void subtractMaxFavor(int amount)
{
setMaxFavor(getMaxFavor() - amount);
}
@Override
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
}
public static class Util
{
public static void save(DCharacter character)
{
DataManager.characters.put(character.getId(), character);
}
public static void saveMeta(Meta meta)
{
DataManager.characterMetas.put(meta.getId(), meta);
}
public static void saveInventory(Inventory inventory)
{
DataManager.inventories.put(inventory.getId(), inventory);
}
public static void delete(UUID id)
{
DataManager.characters.remove(id);
}
public static void deleteMeta(UUID id)
{
DataManager.characterMetas.remove(id);
}
public static void deleteInventory(UUID id)
{
DataManager.inventories.remove(id);
}
public static void create(DPlayer player, String chosenDeity, String chosenName, boolean switchCharacter)
{
// Switch to new character
if(switchCharacter) player.switchCharacter(create(player, chosenName, chosenDeity));
}
public static DCharacter create(DPlayer player, String charName, String charDeity)
{
if(getCharacterByName(charName) == null)
{
// Create the Character
return create(player, charName, Deity.Util.getDeity(charDeity));
}
return null;
}
private static DCharacter create(final DPlayer player, final String charName, final Deity deity)
{
DCharacter character = new DCharacter();
character.generateId();
character.setAlive(true);
character.setPlayer(player);
character.setName(charName);
character.setDeity(deity);
character.setMinorDeities(new HashSet<String>(0));
character.setUsable(true);
character.setHealth(deity.getMaxHealth());
character.setHunger(20);
character.setExperience(0);
character.setLevel(0);
character.setKillCount(0);
character.setLocation(player.getOfflinePlayer().getPlayer().getLocation());
character.setMeta(Util.createMeta());
save(character);
return character;
}
public static Inventory createInventory(DCharacter character)
{
PlayerInventory inventory = character.getOfflinePlayer().getPlayer().getInventory();
Inventory charInventory = new Inventory();
charInventory.generateId();
if(inventory.getHelmet() != null) charInventory.setHelmet(inventory.getHelmet());
if(inventory.getChestplate() != null) charInventory.setChestplate(inventory.getChestplate());
if(inventory.getLeggings() != null) charInventory.setLeggings(inventory.getLeggings());
if(inventory.getBoots() != null) charInventory.setBoots(inventory.getBoots());
charInventory.setItems(inventory);
saveInventory(charInventory);
return charInventory;
}
public static Inventory createEmptyInventory()
{
Inventory charInventory = new Inventory();
charInventory.generateId();
charInventory.setHelmet(new ItemStack(Material.AIR));
charInventory.setChestplate(new ItemStack(Material.AIR));
charInventory.setLeggings(new ItemStack(Material.AIR));
charInventory.setBoots(new ItemStack(Material.AIR));
saveInventory(charInventory);
return charInventory;
}
public static Meta createMeta()
{
Meta charMeta = new Meta();
charMeta.initialize();
charMeta.generateId();
charMeta.setFavor(Configs.getSettingInt("character.defaults.favor"));
charMeta.setMaxFavor(Configs.getSettingInt("character.defaults.max_favor"));
charMeta.resetSkills();
saveMeta(charMeta);
return charMeta;
}
public static Set<DCharacter> loadAll()
{
return Sets.newHashSet(DataManager.characters.values());
}
public static DCharacter load(UUID id)
{
return DataManager.characters.get(id);
}
public static Meta loadMeta(UUID id)
{
return DataManager.characterMetas.get(id);
}
public static Inventory getInventory(UUID id)
{
try
{
return DataManager.inventories.get(id);
}
catch(Exception ignored)
{}
return null;
}
public static SavedPotion getSavedPotion(UUID id)
{
try
{
return DataManager.savedPotions.get(id);
}
catch(Exception ignored)
{}
return null;
}
public static void updateUsableCharacters()
{
for(DCharacter character : loadAll())
character.updateUseable();
}
public static DCharacter getCharacterByName(final String name)
{
try
{
return Iterators.find(loadAll().iterator(), new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter loaded)
{
return loaded.getName().equalsIgnoreCase(name);
}
});
}
catch(NoSuchElementException ignored)
{}
return null;
}
public static boolean charExists(String name)
{
return getCharacterByName(name) != null;
}
public static boolean isCooledDown(DCharacter player, String ability, boolean sendMsg)
{
if(DataManager.hasKeyTemp(player.getName(), ability + "_cooldown") && Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString()) > System.currentTimeMillis())
{
if(sendMsg) player.getOfflinePlayer().getPlayer().sendMessage(ChatColor.RED + ability + " has not cooled down!");
return false;
}
else return true;
}
public static void setCoolDown(DCharacter player, String ability, long cooldown)
{
DataManager.saveTemp(player.getName(), ability + "_cooldown", cooldown);
}
public static long getCoolDown(DCharacter player, String ability)
{
return Long.parseLong(DataManager.getValueTemp(player.getName(), ability + "_cooldown").toString());
}
public static Set<DCharacter> getAllActive()
{
return Sets.filter(loadAll(), new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isUsable() && character.isActive();
}
});
}
public static Set<DCharacter> getAllUsable()
{
return Sets.filter(loadAll(), new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isUsable();
}
});
}
/**
* Returns true if <code>char1</code> is allied with <code>char2</code> based
* on their current alliances.
*
* @param char1 the first character to check.
* @param char2 the second character to check.
* @return boolean
*/
public static boolean areAllied(DCharacter char1, DCharacter char2)
{
return char1.getAlliance().equalsIgnoreCase(char2.getAlliance());
}
public static Collection<DCharacter> getOnlineCharactersWithDeity(final String deity)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline() && character.getDeity().getName().equalsIgnoreCase(deity);
}
});
}
public static Collection<DCharacter> getOnlineCharactersWithAbility(final String abilityName)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
if(character.isActive() && character.getOfflinePlayer().isOnline())
{
for(Ability abilityToCheck : character.getDeity().getAbilities())
if(abilityToCheck.getName().equalsIgnoreCase(abilityName)) return true;
}
return false;
}
});
}
public static Collection<DCharacter> getOnlineCharactersWithAlliance(final String alliance)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline() && character.getAlliance().equalsIgnoreCase(alliance);
}
});
}
public static Collection<DCharacter> getOnlineCharactersWithoutAlliance(final String alliance)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline() && !character.getAlliance().equalsIgnoreCase(alliance);
}
});
}
public static Collection<DCharacter> getOnlineCharactersBelowAscension(final int ascention)
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline() && character.getMeta().getAscensions() < ascention;
}
});
}
public static Collection<DCharacter> getOnlineCharacters()
{
return getCharactersWithPredicate(new Predicate<DCharacter>()
{
@Override
public boolean apply(DCharacter character)
{
return character.isActive() && character.getOfflinePlayer().isOnline();
}
});
}
public static Collection<DCharacter> getCharactersWithPredicate(Predicate<DCharacter> predicate)
{
return Collections2.filter(getAllUsable(), predicate);
}
/**
* Updates favor for all online characters.
*/
public static void updateFavor()
{
for(Player player : Bukkit.getOnlinePlayers())
{
DCharacter character = DPlayer.Util.getPlayer(player).getCurrent();
if(character != null) character.getMeta().addFavor(character.getFavorRegen());
}
}
}
}
|
package org.jacpfx.vertx.rest.util;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.eventbus.Message;
import io.vertx.core.shareddata.Counter;
import io.vertx.core.shareddata.Lock;
import io.vertx.core.shareddata.SharedData;
import io.vertx.ext.web.RoutingContext;
import org.jacpfx.common.*;
import org.jacpfx.common.encoder.Encoder;
import org.jacpfx.vertx.rest.interfaces.ExecuteEventBusByteCallAsync;
import org.jacpfx.vertx.rest.response.basic.ExecuteRSBasicByteResponse;
import org.jacpfx.vertx.rest.response.blocking.ExecuteRSByteResponse;
import org.jacpfx.vertx.rest.response.blocking.ExecuteRSStringResponse;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
public class EventbusAsyncByteExecutionUtil {
public static ExecuteRSByteResponse mapToByteResponse(String _methodId, String _id, Object _message, DeliveryOptions _options,
ThrowableFunction<AsyncResult<Message<Object>>, byte[]> _byteFunction, Vertx _vertx, Throwable _t,
Consumer<Throwable> _errorMethodHandler, RoutingContext _context, Map<String, String> _headers,
ThrowableSupplier<byte[]> _byteSupplier, Encoder _encoder, Consumer<Throwable> _errorHandler,
Function<Throwable, byte[]> _errorHandlerByte, int _httpStatusCode, int _retryCount, long _timeout, long _delay, long _circuitBreakerTimeout) {
final DeliveryOptions deliveryOptions = Optional.ofNullable(_options).orElse(new DeliveryOptions());
final ExecuteEventBusByteCallAsync excecuteEventBusAndReply = (vertx, t, errorMethodHandler,
context, headers,
encoder, errorHandler, errorHandlerByte,
httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout) ->
sendMessageAndSupplyByteHandler(_methodId, _id, _message, _options,
_byteFunction, deliveryOptions, vertx, t, errorMethodHandler, context, headers,
encoder, errorHandler, errorHandlerByte, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout);
return new ExecuteRSByteResponse(_methodId, _vertx, _t, _errorMethodHandler, _context, _headers, _byteSupplier,
excecuteEventBusAndReply, _encoder, _errorHandler, _errorHandlerByte, _httpStatusCode, _retryCount, _timeout, _delay, _circuitBreakerTimeout);
}
private static void sendMessageAndSupplyByteHandler(String methodId, String id, Object message, DeliveryOptions options,
ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction, DeliveryOptions deliveryOptions,
Vertx vertx, Throwable t, Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers,
Encoder encoder, Consumer<Throwable> errorHandler, Function<Throwable, byte[]> onFailureRespond, int httpStatusCode,
int retryCount, long timeout, long delay, long circuitBreakerTimeout) {
if (circuitBreakerTimeout == 0l) {
executeDefaultState(methodId, id, message, byteFunction, deliveryOptions, vertx, t, errorMethodHandler, context,
headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, null);
} else {
executeStateful(methodId, id, message, byteFunction, deliveryOptions, vertx, t, errorMethodHandler, context, headers, encoder, errorHandler,
onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout);
}
}
private static void executeStateful(String methodId, String id, Object message, ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction,
DeliveryOptions deliveryOptions, Vertx vertx, Throwable t,
Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers, Encoder encoder, Consumer<Throwable> errorHandler,
Function<Throwable, byte[]> onFailureRespond, int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout) {
executeLocked(((lock, counter) ->
counter.get(counterHandler -> {
long currentVal = counterHandler.result();
if (currentVal == 0) {
executeInitialState(methodId, id, message, byteFunction, deliveryOptions, vertx, t, errorMethodHandler, context, headers, encoder,
errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, lock, counter);
} else if (currentVal > 0) {
executeDefaultState(methodId, id, message, byteFunction, deliveryOptions, vertx, t, errorMethodHandler, context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, lock);
} else {
executeErrorState(methodId, vertx, errorMethodHandler, context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, lock);
}
})), methodId, vertx, errorHandler, onFailureRespond, errorMethodHandler, context, headers, encoder, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout);
}
private static void executeErrorState(String methodId, Vertx vertx, Consumer<Throwable> errorMethodHandler, RoutingContext context,
Map<String, String> headers, Encoder encoder, Consumer<Throwable> errorHandler,
Function<Throwable, byte[]> onFailureRespond, int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout,
Lock lock) {
final Throwable cause = Future.failedFuture("circuit open").cause();
handleError(methodId, vertx, errorMethodHandler, context, headers,
encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount,
timeout, delay, circuitBreakerTimeout, lock, cause);
}
private static void executeInitialState(String methodId, String id, Object message, ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction,
DeliveryOptions deliveryOptions, Vertx vertx, Throwable t, Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers,
Encoder encoder, Consumer<Throwable> errorHandler, Function<Throwable, byte[]> onFailureRespond,
int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout, Lock lock, Counter counter) {
counter.addAndGet(Integer.valueOf(retryCount + 1).longValue(), rHandler -> {
executeDefaultState(methodId, id, message, byteFunction, deliveryOptions, vertx, t, errorMethodHandler, context,
headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, lock);
});
}
private static void executeDefaultState(String methodId, String id, Object message, ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction,
DeliveryOptions deliveryOptions, Vertx vertx, Throwable t, Consumer<Throwable> errorMethodHandler, RoutingContext context,
Map<String, String> headers, Encoder encoder, Consumer<Throwable> errorHandler, Function<Throwable, byte[]> onFailureRespond,
int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout, Lock lock) {
Optional.ofNullable(lock).ifPresent(lck -> lck.release());
vertx.
eventBus().
send(id, message, deliveryOptions,
event ->
createByteSupplierAndExecute(methodId, id, message, deliveryOptions, byteFunction,
vertx, t, errorMethodHandler,
context, headers, encoder,
errorHandler, onFailureRespond, httpStatusCode,
retryCount, timeout, delay, circuitBreakerTimeout, event));
}
private static void createByteSupplierAndExecute(String methodId, String id, Object message, DeliveryOptions deliveryOptions, ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction, Vertx vertx, Throwable t,
Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers, Encoder encoder,
Consumer<Throwable> errorHandler, Function<Throwable, byte[]> onFailureRespond, int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout, AsyncResult<Message<Object>> event) {
final ThrowableSupplier<byte[]> byteSupplier = createByteSupplier(methodId, id, message, deliveryOptions, byteFunction, vertx, t, errorMethodHandler,
context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, event);
if (circuitBreakerTimeout == 0l) {
statelessExecution(methodId, id, message, deliveryOptions, byteFunction, vertx, t, errorMethodHandler, context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, event, byteSupplier);
} else {
statefulExecution(methodId, id, message, byteFunction, deliveryOptions, vertx, t, errorMethodHandler, context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, event, byteSupplier);
}
}
private static void statefulExecution(String methodId, String id, Object message, ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction, DeliveryOptions deliveryOptions,
Vertx vertx, Throwable t, Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers, Encoder encoder, Consumer<Throwable> errorHandler,
Function<Throwable, byte[]> onFailureRespond, int httpStatusCode, int retryCount, long timeout,long delay, long circuitBreakerTimeout,
AsyncResult<Message<Object>> event, ThrowableSupplier<byte[]> byteSupplier) {
// TODO check if retry set... otherwise it makes no sense... throw exception
if (event.succeeded()) {
new ExecuteRSByteResponse(methodId, vertx, t, errorMethodHandler, context, headers, byteSupplier, null, encoder,
errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay,circuitBreakerTimeout).execute();
} else {
statefulErrorHandling(methodId, id, message, deliveryOptions, byteFunction,
vertx, errorMethodHandler, context, headers, encoder, errorHandler,
onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, event);
}
}
private static void statefulErrorHandling(String methodId, String id, Object message, DeliveryOptions options,
ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction, Vertx vertx,
Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers,
Encoder encoder, Consumer<Throwable> errorHandler, Function<Throwable, byte[]> onFailureRespond,
int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout, AsyncResult<Message<Object>> event) {
executeLocked((lock, counter) ->
counter.decrementAndGet(valHandler -> {
if (valHandler.succeeded()) {
long count = valHandler.result();
if (count <= 0) {
openCircuitAndHandleError(methodId, vertx, errorMethodHandler, context, headers, encoder, errorHandler,
onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, event, lock, counter);
} else {
lock.release();
retryByteOperation(methodId, id, message, options, byteFunction, vertx,
event.cause(), errorMethodHandler, context, headers, encoder, errorHandler,
onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout);
}
} else {
final Throwable cause = valHandler.cause();
handleError(methodId, vertx, errorMethodHandler, context, headers, encoder,
errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay,
circuitBreakerTimeout, lock, cause);
}
}), methodId, vertx, errorHandler, onFailureRespond, errorMethodHandler, context, headers, encoder, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout);
}
private static void openCircuitAndHandleError(String methodId, Vertx vertx, Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers, Encoder encoder,
Consumer<Throwable> errorHandler, Function<Throwable, byte[]> onFailureRespond, int httpStatusCode, int retryCount, long timeout,
long delay, long circuitBreakerTimeout, AsyncResult<Message<Object>> event, Lock lock, Counter counter) {
vertx.setTimer(circuitBreakerTimeout, timer -> counter.addAndGet(Integer.valueOf(retryCount + 1).longValue(), val -> {
}));
counter.addAndGet(-1l, val -> {
final Throwable cause = event.cause();
handleError(methodId, vertx, errorMethodHandler, context, headers,
encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount,
timeout, delay, circuitBreakerTimeout, lock, cause);
});
}
private static void statelessExecution(String methodId, String id, Object message, DeliveryOptions options, ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction, Vertx vertx, Throwable t, Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers, Encoder encoder, Consumer<Throwable> errorHandler, Function<Throwable, byte[]> onFailureRespond, int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout, AsyncResult<Message<Object>> event, ThrowableSupplier<byte[]> byteSupplier) {
if (!event.failed() || (event.failed() && retryCount <= 0)) {
new ExecuteRSByteResponse(methodId, vertx, t, errorMethodHandler, context, headers, byteSupplier, null, encoder, errorHandler,
onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout).execute();
} else if (event.failed() && retryCount > 0) {
retryByteOperation(methodId, id, message, options, byteFunction, vertx, t, errorMethodHandler, context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout);
}
}
private static void retryByteOperation(String methodId, String id, Object message, DeliveryOptions options,
ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction, Vertx vertx, Throwable t, Consumer<Throwable> errorMethodHandler,
RoutingContext context, Map<String, String> headers, Encoder encoder, Consumer<Throwable> errorHandler,
Function<Throwable, byte[]> errorHandlerByte, int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout) {
mapToByteResponse(methodId, id, message, options, byteFunction, vertx, t, errorMethodHandler,
context, headers, null, encoder, errorHandler, errorHandlerByte, httpStatusCode, retryCount - 1, timeout, delay, circuitBreakerTimeout).
execute();
}
private static ThrowableSupplier<byte[]> createByteSupplier(String methodId, String id, Object message, DeliveryOptions options, ThrowableFunction<AsyncResult<Message<Object>>, byte[]> byteFunction, Vertx vertx, Throwable t,
Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers, Encoder encoder,
Consumer<Throwable> errorHandler, Function<Throwable, byte[]> errorHandlerByte, int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout, AsyncResult<Message<Object>> event) {
return () -> {
byte[] resp = null;
if (event.failed()) {
if (retryCount > 0) {
retryByteOperation(methodId, id, message, options, byteFunction, vertx, t, errorMethodHandler, context, headers, encoder, errorHandler, errorHandlerByte, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout);
} else {
throw event.cause();
}
} else {
resp = byteFunction.apply(event);
}
return resp;
};
}
private static void executeLocked(LockedConsumer consumer, String _methodId, Vertx vertx, Consumer<Throwable> errorHandler,
Function<Throwable, byte[]> onFailureRespond, Consumer<Throwable> errorMethodHandler,
RoutingContext context, Map<String, String> headers, Encoder encoder,
int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout) {
final SharedData sharedData = vertx.sharedData();
sharedData.getLockWithTimeout(_methodId, 2000, lockHandler -> {
if (lockHandler.succeeded()) {
final Lock lock = lockHandler.result();
sharedData.getCounter(_methodId, resultHandler -> {
if (resultHandler.succeeded()) {
consumer.execute(lock, resultHandler.result());
} else {
final Throwable cause = resultHandler.cause();
handleError(_methodId, vertx, errorMethodHandler, context, headers, encoder, errorHandler,
onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, lock, cause);
}
});
} else {
final Throwable cause = lockHandler.cause();
handleError(_methodId, vertx, errorMethodHandler, context, headers, encoder, errorHandler,
onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout, null, cause);
}
});
}
private static void handleError(String methodId, Vertx vertx, Consumer<Throwable> errorMethodHandler, RoutingContext context, Map<String, String> headers, Encoder encoder, Consumer<Throwable> errorHandler,
Function<Throwable, byte[]> onFailureRespond, int httpStatusCode, int retryCount, long timeout, long delay, long circuitBreakerTimeout, Lock lock, Throwable cause) {
Optional.ofNullable(lock).ifPresent(lck -> lck.release());
ThrowableSupplier<byte[]> failConsumer = () -> {
throw cause;
};
new ExecuteRSByteResponse(methodId, vertx, cause, errorMethodHandler, context, headers, failConsumer, null,
encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount, timeout, delay, circuitBreakerTimeout).execute();
}
private interface LockedConsumer {
void execute(Lock lock, Counter counter);
}
}
|
package com.crawljax.util;
import java.util.Stack;
/**
* Class for making presenting HTML without changing it's structure.
*
* @author Danny
* @version $Id$
*/
public final class PrettyHTML {
private PrettyHTML() {
}
// private static final Logger LOGGER =
// Logger.getLogger(PrettyHTML.class.getName());
/**
* Pretty print HTML string.
*
* @param html
* The HTML string.
* @param strIndent
* The indentation string.
* @return The pretty HTML.
*/
public static String prettyHTML(String html, String strIndent) {
String[] elements = html.split("<");
String prettyHTML = "";
int indent = 0;
// preparsing for not closing elements
elements = fixElements(elements);
for (String element : elements) {
if (!element.equals("")) {
element = element.trim();
if (!element.startsWith("/")) {
// open element
prettyHTML += repeatString(strIndent, indent);
String[] temp = element.split(">");
prettyHTML += "<" + temp[0].trim() + ">\n";
// only indent if element is not a single element (like
// <img src='..' />)
if ((!temp[0].endsWith("/") || temp.length == 1)
&& !temp[0].startsWith("!
indent++;
}
// if there is text after the element, print it
if (temp.length > 1 && !temp[1].trim().equals("")) {
prettyHTML += repeatString(strIndent, indent);
prettyHTML += temp[1].trim() + "\n";
}
} else {
// close element
indent
prettyHTML += repeatString(strIndent, indent);
prettyHTML += "<" + element + "\n";
}
if (element.endsWith("/>")) {
indent
}
}
}
return prettyHTML;
}
/**
* @param html
* The HTML string.
* @return Pretty HTML.
*/
public static String prettyHTML(String html) {
return prettyHTML(html, "\t");
}
/**
* @param s
* @param number
* @return s repreated number of times
*/
private static String repeatString(String s, int number) {
String ret = "";
for (int i = 0; i < number; i++) {
ret += s;
}
return ret;
}
/**
* @param openElement
* @param closeElement
* @return wheter element has a seperate closing element
*/
private static boolean elementsRelated(String openElement, String closeElement) {
openElement = openElement.split(">")[0];
openElement = openElement.split(" ")[0];
closeElement = closeElement.split(">")[0];
return closeElement.startsWith("/" + openElement);
}
/**
* @param stack
* @param element
* @return whether the element is open
*/
private static boolean elementIsOpen(Stack<String> stack, String element) {
for (int i = stack.size() - 1; i >= 0; i
if (elementsRelated(stack.get(i), element)) {
return true;
}
}
return false;
}
/**
* @param element
* @return wheter the element is a single element (<foo ... />)
*/
private static boolean isSingleElement(String element) {
return element.indexOf("/>") != -1;
}
/**
* @param elements
* @return list with elements with added closing elements if needed
*/
private static String[] fixElements(String[] elements) {
Stack<String> stackElements = new Stack<String>();
Stack<Integer> stackIndexElements = new Stack<Integer>();
for (int i = 0; i < elements.length; i++) {
elements[i] = elements[i].trim();
String element = elements[i];
if (!element.equals("") && !element.startsWith("!--") && !element.endsWith("-->")) {
while (stackElements.size() > 0 && element.startsWith("/")
&& !elementsRelated(stackElements.peek(), element)) {
// found a close element which is not on top of stack,
// thus fix
if (elementIsOpen(stackElements, element)) {
// the element is open --> close element on top of
// stack
int index = stackIndexElements.peek();
if (!isSingleElement(elements[index])
&& elements[index].lastIndexOf(">") != -1) {
// close this element
elements[index] =
elements[index]
.substring(0, elements[index].lastIndexOf(">"))
+ "/"
+ elements[index].substring(elements[index]
.lastIndexOf(">"));
}
stackElements.pop();
stackIndexElements.pop();
} else {
// element is closing element while element is not
// open--> remove.
elements[i] = "";
element = "";
break;
}
}
if (!element.equals("")) {
// open element
if (!element.startsWith("/")) {
// only add to stack if has an open and close element
if (!isSingleElement(element)) {
stackElements.push(element);
stackIndexElements.push(i);
}
} else {
// close element, pop from stack if possible
if (stackElements.size() > 0) {
stackElements.pop();
stackIndexElements.pop();
}
}
}
}
}
return elements;
}
}
|
package edu.cornell.mannlib.vitro.webapp.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.vocabulary.XSD;
import com.ibm.icu.util.Calendar;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
import fedora.client.FedoraClient;
import fedora.common.Constants;
import fedora.server.management.FedoraAPIM;
import fedora.server.types.gen.Datastream;
/**
* Handles a request to change a datastream in a fedora repository.
* Some of this code is copied from N3MultiPartUpload.java
*
* @author bdc34
*
*/
public class FedoraDatastreamController extends VitroHttpServlet implements Constants{
private static String FEDORA_PROPERTIES = "/WEB-INF/fedora.properties";
private static String DEFAULT_DSID = "DS1";
private String fedoraUrl = null;
private String adminUser = null;
private String adminPassword = null;
private String pidNamespace = null;
private String configurationStatus = "<p>Fedora configuration not yet loaded</p>";
private boolean configured = false;
private boolean connected = false;
private static final int DEFAULT_MAX_SIZE = 1024 * 1024 * 50;//Shoudl this be changed to 1 GB to be consistent
private static final String DEFAULT_BASE_DIR = "/usr/local/vitrofiles";
private static String baseDirectoryForFiles = DEFAULT_BASE_DIR;
private static int maxFileSize = DEFAULT_MAX_SIZE;
protected String contentTypeProperty = VitroVocabulary.CONTENT_TYPE;
protected String fileSizeProperty = VitroVocabulary.FILE_SIZE;
protected String fileNameProperty = VitroVocabulary.FILE_NAME;
protected String fileLocationProperty = VitroVocabulary.FILE_LOCATION;
protected String fileLabelProperty = RDFS.label.getURI();
protected String checksumNodeProperty = "";//Object property linking file to check sum node object
protected String checksumNodeDateTimeProperty = "";
protected String checksumNodeValueProperty = "";
protected String checksumDataProperty = ""; //is there a vitro equivalent?
protected String deleteNs = "";
protected String individualPrefix = "";
protected String fedoraNs = VitroVocabulary.VITRO_FEDORA;
/**
* The get will present a form to the user.
*/
public void doGet( HttpServletRequest req, HttpServletResponse res )
throws IOException, ServletException {
try {
super.doGet(req, res);
log.debug("In doGet");
VitroRequest vreq = new VitroRequest(req);
OntModel sessionOntModel = (OntModel)vreq.getSession().getAttribute("jenaOntModel");
synchronized (FedoraDatastreamController.class) {
if( fedoraUrl == null ){
setup( sessionOntModel, getServletContext() );
if( fedoraUrl == null )
throw new FdcException("Connection to the file repository is " +
"not setup correctly. Could not read fedora.properties file");
}else{
if( !canConnectToFedoraServer() ){
fedoraUrl = null;
throw new FdcException("Could not connect to Fedora.");
}
}
}
FedoraClient fedora;
try { fedora = new FedoraClient(fedoraUrl,adminUser,adminPassword); }
catch (MalformedURLException e) {
throw new FdcException("Malformed URL for fedora Repository location: " + fedoraUrl);
}
FedoraAPIM apim;
try { apim = fedora.getAPIM(); } catch (Exception e) {
throw new FdcException("could not create fedora APIM:" + e.getMessage());
}
//check if logged in
//get URI for file individual
if( req.getParameter("uri") == null || "".equals(req.getParameter("uri")))
throw new FdcException("No file uri specified in request");
boolean isDelete = (req.getParameter("delete") != null && "true".equals(req.getParameter("delete")));
String fileUri = req.getParameter("uri");
//check if file individual has a fedora:PID for a data stream
IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao();
Individual entity = iwDao.getIndividualByURI(fileUri);
if( entity == null )
throw new FdcException( "No entity found in system for file uri " + fileUri);
//System.out.println("Entity == null:" + (entity == null));
//get the fedora PID
//System.out.println("entity data property " + entity.getDataPropertyMap().get(VitroVocabulary.FEDORA_PID));
if( entity.getDataPropertyMap().get(VitroVocabulary.FEDORA_PID ) == null )
throw new FdcException( "No fedora:pid found in system for file uri " + fileUri);
List<DataPropertyStatement> stmts = entity.getDataPropertyMap().get(VitroVocabulary.FEDORA_PID).getDataPropertyStatements();
if( stmts == null || stmts.size() == 0)
throw new FdcException( "No fedora:pid found in system for file uri " + fileUri);
String pid = null;
for(DataPropertyStatement stmt : stmts){
if( stmt.getData() != null && stmt.getData().length() > 0){
pid = stmt.getData();
break;
}
}
//System.out.println("pid is " + pid + " and comparison is " + (pid == null));
if( pid == null )
throw new FdcException( "No fedora:pid found in system for file uri " + fileUri);
req.setAttribute("pid", pid);
req.setAttribute("fileUri", fileUri);
//get current file name to use on form
req.setAttribute("fileName", entity.getName());
if(isDelete)
{
//Execute a 'deletion', i.e. unlink dataset and file, without removing file
//Also save deletion as a deleteEvent entity which can later be queried
String datasetUri = null;
//Get dataset uri by getting the fromDataSet property
edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty fromDataSet = entity.getObjectPropertyMap().get(fedoraNs + "fromDataSet");
if(fromDataSet != null)
{
List<ObjectPropertyStatement> fromDsStmts = fromDataSet.getObjectPropertyStatements();
if(fromDsStmts.size() > 0) {
datasetUri = fromDsStmts.get(0).getObjectURI();
//System.out.println("object uri should be " + datasetUri);
} else {
//System.out.println("No matching dataset uri could be found");
}
} else {
//System.out.println("From dataset is null");
}
req.setAttribute("dataseturi", datasetUri);
boolean success = deleteFile(req, entity, iwDao, sessionOntModel);
req.setAttribute("deletesuccess", (success)?"success":"error");
req.setAttribute("bodyJsp", "/edit/fileDeleteConfirm.jsp");
RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
rd.forward(req, res);
}
else{
//check if the data stream exists in the fedora repository
Datastream ds = apim.getDatastream(pid,DEFAULT_DSID,null);
if( ds == null )
throw new FdcException("There was no datastream in the " +
"repository for " + pid + " " + DEFAULT_DSID);
req.setAttribute("dsid", DEFAULT_DSID);
//forward to form
req.setAttribute("bodyJsp","/fileupload/datastreamModification.jsp");
RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
rd.forward(req, res);
}
}catch(FdcException ex){
req.setAttribute("errors", ex.getMessage());
RequestDispatcher rd = req.getRequestDispatcher("/edit/fileUploadError.jsp");
rd.forward(req, res);
return;
}
}
public void doPost(HttpServletRequest rawRequest, HttpServletResponse res)
throws ServletException,IOException {
try{
FileUploadServletRequest req = FileUploadServletRequest.parseRequest(rawRequest, maxFileSize);
if (req.hasFileUploadException()) {
throw new FdcException("Size limit exceeded: " + req.getFileUploadException().getLocalizedMessage());
}
if (!req.isMultipart()) {
throw new FdcException("Must POST a multipart encoded request");
}
//check if fedora is on line
OntModel sessionOntModel = (OntModel)req.getSession().getAttribute("jenaOntModel");
synchronized (FedoraDatastreamController.class) {
if( fedoraUrl == null ){
setup( sessionOntModel, getServletContext() );
if( fedoraUrl == null )
throw new FdcException("Connection to the file repository is " +
"not setup correctly. Could not read fedora.properties file");
}else{
if( !canConnectToFedoraServer() ){
fedoraUrl = null;
throw new FdcException("Could not connect to Fedora.");
}
}
}
FedoraClient fedora;
try { fedora = new FedoraClient(fedoraUrl,adminUser,adminPassword); }
catch (MalformedURLException e) {
throw new FdcException("Malformed URL for fedora Repository location: " + fedoraUrl);
}
FedoraAPIM apim;
try { apim = fedora.getAPIM(); } catch (Exception e) {
throw new FdcException("could not create fedora APIM:" + e.getMessage());
}
//get the parameters from the request
String pId=req.getParameter("pid");
String dsId=req.getParameter("dsid");
String fileUri=req.getParameter("fileUri");
boolean useNewName=false;
if( "true".equals(req.getParameter("useNewName"))){
useNewName = true;
}
if( pId == null || pId.length() == 0 )
throw new FdcException("Your form submission did not contain " +
"enough information to complete your request.(Missing pid parameter)");
if( dsId == null || dsId.length() == 0 )
throw new FdcException("Your form submission did not contain " +
"enough information to complete your request.(Missing dsid parameter)");
if( fileUri == null || fileUri.length() == 0 )
throw new FdcException("Your form submission did not contain " +
"enough information to complete your request.(Missing fileUri parameter)");
FileItem fileRes = req.getFileItem("fileRes");
if( fileRes == null )
throw new FdcException("Your form submission did not contain " +
"enough information to complete your request.(Missing fileRes)");
//check if file individual has a fedora:PID for a data stream
VitroRequest vreq = new VitroRequest(req);
IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao();
Individual fileEntity = iwDao.getIndividualByURI(fileUri);
//check if logged in
//TODO: check if logged in
//check if user is allowed to edit datastream
//TODO:check if can edit datastream
//check if digital object and data stream exist in fedora
Datastream ds = apim.getDatastream(pId,dsId,null);
if( ds == null )
throw new FdcException("There was no datastream in the " +
"repository for " + pId + " " + DEFAULT_DSID);
//upload to temp holding area
String originalName = fileRes.getName();
String name = originalName.replaceAll("[,+\\\\/$%^&*
name = name.replace("..", "_");
name = name.trim().toLowerCase();
String saveLocation = baseDirectoryForFiles + File.separator + name;
String savedName = name;
int next = 0;
boolean foundUnusedName = false;
while (!foundUnusedName) {
File test = new File(saveLocation);
if (test.exists()) {
next++;
savedName = name + '(' + next + ')';
saveLocation = baseDirectoryForFiles + File.separator + savedName;
} else {
foundUnusedName = true;
}
}
File uploadedFile = new File(saveLocation);
try {
fileRes.write(uploadedFile);
} catch (Exception ex) {
log.error("Unable to save POSTed file. " + ex.getMessage());
throw new FdcException("Unable to save file to the disk. "
+ ex.getMessage());
}
//upload to temp area on fedora
File file = new File(saveLocation);
String uploadFileUri = fedora.uploadFile( file );
// System.out.println("Fedora upload temp = upload file uri is " + uploadFileUri);
String md5 = md5hashForFile( file );
md5 = md5.toLowerCase();
//make change to data stream on fedora
apim.modifyDatastreamByReference(pId, dsId,
null, null,
fileRes.getContentType(), null,
uploadFileUri,
"MD5", null,
null, false);
String checksum =
apim.compareDatastreamChecksum(pId,dsId,null);
//update properties like checksum, file size, and content type
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
DataPropertyStatement dps = null;
DataProperty contentType = wdf.getDataPropertyDao().getDataPropertyByURI(this.contentTypeProperty);
if(contentType != null)
{
wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, contentType);
dps = new DataPropertyStatementImpl();
dps.setIndividualURI(fileEntity.getURI());
dps.setDatapropURI(contentType.getURI());
dps.setData(fileRes.getContentType());
wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
}
DataProperty fileSize = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileSizeProperty);
if(fileSize != null)
{
wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileSize);
dps = new DataPropertyStatementImpl();
dps.setIndividualURI(fileEntity.getURI());
dps.setDatapropURI(fileSize.getURI());
dps.setData(Long.toString(fileRes.getSize()));
wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
//System.out.println("Updated file size with " + fileRes.getSize());
}
DataProperty checksumDp = wdf.getDataPropertyDao().getDataPropertyByURI(this.checksumDataProperty);
if(checksumDp != null)
{
//System.out.println("Checksum data property is also not null");
wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, checksumDp);
dps = new DataPropertyStatementImpl();
dps.setIndividualURI(fileEntity.getURI());
dps.setDatapropURI(checksumDp.getURI());
dps.setData(checksum);
wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
}
//I'm leaving if statement out for now as the above properties are obviously being replaced as well
//if( "true".equals(useNewName)){
//Do we need to encapuslate in this if OR is this path always for replacing a file
//TODO: Put in check to see if file name has changed and only execute these statements if file name has changed
DataProperty fileNameProperty = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileNameProperty);
if(fileNameProperty != null) {
wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileNameProperty);
dps = new DataPropertyStatementImpl();
dps.setIndividualURI(fileEntity.getURI());
dps.setDatapropURI(fileNameProperty.getURI());
dps.setData(originalName); //This follows the pattern of the original file upload - the name returned from the uploaded file object
wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
//System.out.println("File name property is not null = " + fileNameProperty.getURI() + " updating to " + originalName);
} else {
//System.out.println("file name property is null");
}
//Need to also update the check sum node - how would we do that
//Find checksum node related to this particular file uri, then go ahead and update two specific fields
List<ObjectPropertyStatement >csNodeStatements = fileEntity.getObjectPropertyMap().get(this.checksumNodeProperty).getObjectPropertyStatements();
if(csNodeStatements.size() == 0) {
System.out.println("No object property statements correspond to this property");
} else {
ObjectPropertyStatement cnodeStatement = csNodeStatements.get(0);
String cnodeUri = cnodeStatement.getObjectURI();
//System.out.println("Checksum node uri is " + cnodeUri);
Individual checksumNodeObject = iwDao.getIndividualByURI(cnodeUri);
DataProperty checksumDateTime = wdf.getDataPropertyDao().getDataPropertyByURI(this.checksumNodeDateTimeProperty);
if(checksumDateTime != null) {
String newDatetime = sessionOntModel.createTypedLiteral(new DateTime()).getString();
//Review how to update date time
wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(checksumNodeObject, checksumDateTime);
dps = new DataPropertyStatementImpl();
dps.setIndividualURI(checksumNodeObject.getURI());
dps.setDatapropURI(checksumDateTime.getURI());
dps.setData(newDatetime);
wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
}
DataProperty checksumNodeValue = wdf.getDataPropertyDao().getDataPropertyByURI(this.checksumDataProperty);
if(checksumNodeValue != null) {
wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(checksumNodeObject, checksumNodeValue);
dps = new DataPropertyStatementImpl();
dps.setIndividualURI(checksumNodeObject.getURI());
dps.setDatapropURI(checksumNodeValue.getURI());
dps.setData(checksum); //Same as fileName above - change if needed
wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
}
}
//Assumes original entity name is equal to the location - as occurs with regular file upload
String originalEntityName = fileEntity.getName();
if(originalEntityName != originalName) {
//System.out.println("Setting file entity to name of uploaded file");
fileEntity.setName(originalName);
} else {
//System.out.println("Conditional for file entity name and uploaded name is saying same");
}
iwDao.updateIndividual(fileEntity);
req.setAttribute("fileUri", fileUri);
req.setAttribute("originalFileName", fileEntity.getName());
req.setAttribute("checksum", checksum);
if( "true".equals(useNewName)){
req.setAttribute("useNewName", "true");
req.setAttribute("newFileName", originalName);
}else{
req.setAttribute("newFileName", fileEntity.getName());
}
//forward to form
req.setAttribute("bodyJsp","/fileupload/datastreamModificationSuccess.jsp");
RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
rd.forward(req, res);
}catch(FdcException ex){
rawRequest.setAttribute("errors", ex.getMessage());
RequestDispatcher rd = rawRequest.getRequestDispatcher("/edit/fileUploadError.jsp");
rd.forward(rawRequest, res);
return;
}
}
//Delete method
public boolean deleteFile(HttpServletRequest req, Individual entity, IndividualDao iwDao, OntModel sessionOntModel) {
boolean success = false;
String fileUri = entity.getURI();
//Create uri based on milliseconds etc.?
Calendar c = Calendar.getInstance();
long timeMs = c.getTimeInMillis();
//Cuirrent date
SimpleDateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String formattedDeleteDate = dateTime.format(c.getTime());
String deleteEventName = "deleteEvent" + timeMs;
//System.out.println("Delete event name is " +deleteEventName + " - delete time is " + formattedDeleteDate);
//Get current user
String userURI = LoginStatusBean.getBean(req).getUserURI();
//System.out.println("Current logged in user uri is " + userURI);
//Update model
sessionOntModel.enterCriticalSection(true);
try {
//Dataset Uri
String datasetUri = (String) req.getAttribute("dataseturi");
//System.out.println("Dataset uri is " + datasetUri);
//Remove the actual relationships: dsr:hasFile and fedora:fromDataSet
ObjectProperty hasFileProperty = sessionOntModel.getObjectProperty(fedoraNs + "hasFile");
ObjectProperty fromDatasetProperty = sessionOntModel.getObjectProperty(fedoraNs + "fromDataSet");
if(hasFileProperty != null) {
//System.out.println("Has file property does exist");
sessionOntModel.remove(sessionOntModel.createStatement(sessionOntModel.getResource(datasetUri), hasFileProperty, sessionOntModel.getResource(fileUri)));
} else{
//System.out.println("Has file property does not exist");
}
if(fromDatasetProperty != null) {
//System.out.println("From dataset property exists ");
sessionOntModel.remove(sessionOntModel.createStatement(sessionOntModel.getResource(fileUri), fromDatasetProperty, sessionOntModel.getResource(datasetUri)));
} else{
//System.out.println("From dataset property does not exist");
}
//Create delete event entity and update with the correct information
//Type of Event
Resource deleteEventType = sessionOntModel.createResource(deleteNs + "DeleteEvent");
//Individual event
Resource eventIndividual = sessionOntModel.createResource(individualPrefix + deleteEventName);
//Event is of type DeleteEvent
Statement rType = sessionOntModel.createStatement(eventIndividual, com.hp.hpl.jena.vocabulary.RDF.type, deleteEventType);
sessionOntModel.add(rType);
//Add properties to individual - deleteDateTime, deletedBy, forDataSet, forFile
DatatypeProperty dateTimeProp = sessionOntModel.createDatatypeProperty(deleteNs + "deleteDateTime");
dateTimeProp.setRange(XSD.dateTime);
ObjectProperty deletedByProp = sessionOntModel.createObjectProperty(deleteNs + "deletedBy");
ObjectProperty forDatasetProp = sessionOntModel.createObjectProperty(deleteNs + "forDataset");
ObjectProperty forFileProp = sessionOntModel.createObjectProperty(deleteNs + "forFile");
//Need to make sure date time property is set to correct xsd:DateTime
//XSDDateTime now = new XSDDateTime(java.util.Calendar.getInstance());
eventIndividual.addProperty(dateTimeProp, sessionOntModel.createTypedLiteral(formattedDeleteDate, XSDDatatype.XSDdateTime));
//eventIndividual.addProperty(dateTimeProp, sessionOntModel.createTypedLiteral(now, XSDDatatype.XSDdateTime));
eventIndividual.addProperty(deletedByProp, sessionOntModel.getResource(userURI));
if(datasetUri != null){
//System.out.println("Dataset uri is " + datasetUri);
eventIndividual.addProperty(forDatasetProp, sessionOntModel.getResource(datasetUri));
}
eventIndividual.addProperty(forFileProp, sessionOntModel.getResource(fileUri));
success = true;
} finally {
sessionOntModel.leaveCriticalSection();
}
return success;
}
public void init() throws ServletException {
super.init();
baseDirectoryForFiles = ConfigurationProperties.getProperty(
"n3.baseDirectoryForFiles", DEFAULT_BASE_DIR);
String maxSize = ConfigurationProperties.getProperty("n3.maxSize", Long
.toString(DEFAULT_MAX_SIZE));
try {
maxFileSize = Integer.parseInt(maxSize);
} catch (NumberFormatException nfe) {
log.error(nfe);
maxFileSize = DEFAULT_MAX_SIZE;
}
}
public void setup(OntModel model, ServletContext context) {
this.configurationStatus = "";
StringBuffer status = new StringBuffer("");
if( connected && configured )
return;
Properties props = new Properties();
String path = context.getRealPath(FEDORA_PROPERTIES);
try{
InputStream in = new FileInputStream(new File( path ));
props.load( in );
fedoraUrl = props.getProperty("fedoraUrl");
adminUser = props.getProperty("adminUser");
adminPassword = props.getProperty("adminPassword");
pidNamespace = props.getProperty("pidNamespace");
if( fedoraUrl == null || adminUser == null || adminPassword == null ){
if( fedoraUrl == null ){
log.error("'fedoraUrl' not found in properties file");
status.append("<p>'fedoraUrl' not found in properties file.</p>\n");
}
if( adminUser == null ) {
log.error("'adminUser' was not found in properties file, the " +
"user name of the fedora admin is needed to access the " +
"fedora API-M services.");
status.append("<p>'adminUser' was not found in properties file, the " +
"user name of the fedora admin is needed to access the " +
"fedora API-M services.</p>\n");
}
if( adminPassword == null ){
log.error("'adminPassword' was not found in properties file, the " +
"admin password is needed to access the fedora API-M services.");
status.append("<p>'adminPassword' was not found in properties file, the " +
"admin password is needed to access the fedora API-M services.</p>\n");
}
if( pidNamespace == null ){
log.error("'pidNamespace' was not found in properties file, the " +
"PID namespace indicates which namespace to use when creating " +
"new fedor digital objects.");
status.append("<p>'pidNamespace' was not found in properties file, the " +
"PID namespace indicates which namespace to use when creating " +
"new fedor digital objects.</p>\n");
}
fedoraUrl = null; adminUser = null; adminPassword = null;
configured = false;
} else {
configured = true;
}
}catch(FileNotFoundException e) {
log.error("No fedora.properties file found,"+
"it should be located at " + path);
status.append("<h1>Fedora configuration failed.</h1>\n");
status.append("<p>No fedora.properties file found,"+
"it should be located at " + path + "</p>\n");
configured = false;
return;
}catch(Exception ex){
status.append("<p>Fedora configuration failed.</p>\n");
status.append("<p>Exception while loading" + path + "</p>\n");
status.append("<p>" + ex.getMessage() + "</p>\n");
log.error("could not load fedora properties", ex);
fedoraUrl = null; adminUser = null; adminPassword = null;
configured = false;
return;
}
status.append(RELOAD_MSG);
this.configurationStatus += status.toString();
// else{
// status.append("<h2>Fedora configuration file ").append(path).append(" was loaded</h2>");
// status.append("<p>fedoraUrl: ").append(fedoraUrl).append("</p>\n");
// checkFedoraServer();
}
private boolean canConnectToFedoraServer( ){
try{
FedoraClient fc = new FedoraClient(fedoraUrl,adminUser, adminPassword);
String fedoraVersion = fc.getServerVersion();
if( fedoraVersion != null && fedoraVersion.length() > 0 ){
configurationStatus += "<p>Fedora server is live and is running " +
"fedora version " + fedoraVersion + "</p>\n";
connected = true;
return true;
} else {
configurationStatus += "<p>Unable to reach fedora server</p>\n";
connected = false;
return false;
}
}catch (Exception e) {
configurationStatus += "<p>There was an error while checking the " +
"fedora server version</p>\n<p>"+ e.getMessage() + "</p>\n";
connected = false;
return false;
}
}
public boolean isConfigured(){ return configured; }
public boolean isConnected(){ return connected; }
private class FdcException extends Exception {
public FdcException(String message) {
super(message);
}
};
private static final String RELOAD_MSG =
"<p>The fedora configuartion file will be reloaded if " +
"you edit the properties file and check the status.</p>\n";
public static String md5hashForFile(File file){
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er =
MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0)
md5er.update(buffer, 0, read);
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null)
return null;
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1);
}
return strDigest;
} catch (Exception e) {
return null;
}
}
private static final Log log = LogFactory.getLog(FedoraDatastreamController.class.getName());
}
|
package com.example;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.math3.analysis.interpolation.LoessInterpolator;
import java.io.File;
import java.io.FileOutputStream;
public class STLDecomposition {
private static final double LOESS_BANDWIDTH = 0.75; // same as R implementation
private static final int LOESS_ROBUSTNESS_ITERATIONS = 4; // same as R implementation
private final Config config;
/**
* Constructs a configuration of STL function that can de-trend data.
*
* <p>
* Robert B. Cleveland et al., "STL: A Seasonal-Trend Decomposition Procedure based on Loess,"
* in Journal of Official Statistics Vol. 6 No. 1, 1990, pp. 3-73
* </p>
*
* <p>
* The three spans (n_s, n_t, and n_l) must be at least three and odd.
* </p>
*
* <p>
* n.b. The Java Loess implementation only does linear local polynomial
* regression, but R supports linear (degree=1), quadratic (degree=2), and
* a strange degree=0 option.
* </p>
*/
public STLDecomposition(Config config) {
config.check();
this.config = config;
}
public static class Config {
/** The number of observations in each cycle of the seasonal component, n_p */
private int numberOfObservations;
/** The number of passes through the inner loop, n_i */
private int numberOfInnerLoopPasses = 1;
/** The number of robustness iterations of the outer loop, n_o */
private int numberOfRobustnessIterations = 1;
/** The smoothing parameter for the low pass filter, n_l */
private int lowPassFilterSmoothing = 3; // TODO: How to use?
/** The smoothing parameter for the trend component, n_t */
private int trendComponentSmoothing = 3; // TODO: How to use?
/** The smoothing parameter for the seasonal component, n_s */
private int seasonalComponentSmoothing = 3; // TODO: How to use?
public Config() {}
public int getNumberOfObservations() {
return numberOfObservations;
}
public void setNumberOfObservations(int numberOfObservations) {
this.numberOfObservations = numberOfObservations;
}
public int getNumberOfInnerLoopPasses() {
return numberOfInnerLoopPasses;
}
public void setNumberOfInnerLoopPasses(int numberOfInnerLoopPasses) {
this.numberOfInnerLoopPasses = numberOfInnerLoopPasses;
}
public int getNumberOfRobustnessIterations() {
return numberOfRobustnessIterations;
}
public void setNumberOfRobustnessIterations(int numberOfRobustnessIterations) {
this.numberOfRobustnessIterations = numberOfRobustnessIterations;
}
public int getLowPassFilterSmoothing() {
return lowPassFilterSmoothing;
}
public void setLowPassFilterSmoothing(int lowPassFilterSmoothing) {
this.lowPassFilterSmoothing = lowPassFilterSmoothing;
}
public int getTrendComponentSmoothing() {
return trendComponentSmoothing;
}
public void setTrendComponentSmoothing(int trendComponentSmoothing) {
this.trendComponentSmoothing = trendComponentSmoothing;
}
public int getSeasonalComponentSmoothing() {
return seasonalComponentSmoothing;
}
public void setSeasonalComponentSmoothing(int seasonalComponentSmoothing) {
this.seasonalComponentSmoothing = seasonalComponentSmoothing;
}
public void check() {
checkPeriodicity(numberOfObservations);
checkSmoothing("lowPassFilterSmoothing", lowPassFilterSmoothing);
checkSmoothing("trendComponentSmoothing", trendComponentSmoothing);
checkSmoothing("seasonalComponentSmoothing", seasonalComponentSmoothing);
}
private int checkPeriodicity(int numberOfObservations) {
if (numberOfObservations < 2) {
throw new IllegalArgumentException("Periodicity (numberOfObservations) must be >= 2");
}
return numberOfObservations;
}
private void checkSmoothing(String name, int value) {
if (value < 3) {
throw new IllegalArgumentException(name + " must be at least 3: is " + value);
}
if (value % 2 == 0) {
throw new IllegalArgumentException(name + " must be odd: is " + value);
}
}
}
public STLResult decompose(long[] times, double[] series) {
double[] trend = new double[series.length];
double[] seasonal = new double[series.length];
double[] remainder = new double[series.length];
for (int l = 0; l < config.getNumberOfRobustnessIterations(); l++) {
for (int k = 0; k < config.getNumberOfInnerLoopPasses(); k++) {
// Step 1: Detrending
double[] detrend = new double[series.length];
for (int i = 0; i < series.length; i++) {
detrend[i] = series[i] - trend[i];
}
// Get cycle sub-series with padding on either side
int numberOfObservations = config.getNumberOfObservations();
int cycleSubseriesLength = series.length / numberOfObservations;
double[][] cycleSubseries = new double[numberOfObservations][cycleSubseriesLength + 2];
double[][] cycleTimes = new double[numberOfObservations][cycleSubseriesLength + 2];
for (int i = 0; i < series.length; i += numberOfObservations) {
for (int j = 0; j < numberOfObservations; j++) {
int cycleIdx = i / numberOfObservations;
cycleSubseries[j][cycleIdx + 1] = detrend[i + j];
cycleTimes[j][cycleIdx + 1] = i + j;
}
}
// Beginning / end times
for (int i = 0; i < numberOfObservations; i++) {
cycleTimes[i][0] = cycleTimes[i][1] - numberOfObservations;
cycleTimes[i][cycleTimes[i].length - 1] = cycleTimes[i][cycleTimes[i].length - 2] + numberOfObservations;
}
// Step 2: Cycle-subseries Smoothing
for (int i = 0; i < cycleSubseries.length; i++) {
double[] smoothed = loessSmooth(cycleTimes[i], cycleSubseries[i]);
cycleSubseries[i] = smoothed;
}
// Combine smoothed series into one
double[] combinedSmoothed = new double[series.length + 2 * numberOfObservations];
for (int i = 0; i < cycleSubseriesLength + 2; i++) {
for (int j = 0; j < numberOfObservations; j++) {
combinedSmoothed[i * numberOfObservations + j] = cycleSubseries[j][i];
}
}
// Step 3: Low-Pass Filtering of Smoothed Cycle-Subseries
double[] filtered = lowPassFilter(combinedSmoothed);
// Step 4: Detrending of Smoothed Cycle-Subseries
for (int i = 0; i < seasonal.length; i++) {
seasonal[i] = combinedSmoothed[i + numberOfObservations] - filtered[i + numberOfObservations];
}
// Step 5: Deseasonalizing
for (int i = 0; i < series.length; i++) {
trend[i] = series[i] - seasonal[i];
}
// Step 6: Trend Smoothing
trend = loessSmooth(trend);
}
// Calculate remainder
for (int i = 0; i < series.length; i++) {
remainder[i] = series[i] - trend[i] - seasonal[i];
}
}
return new STLResult(times, series, trend, seasonal, remainder);
}
private double[] lowPassFilter(double[] series) {
// Apply moving average of length n_p, twice
series = movingAverage(series, config.getNumberOfObservations());
series = movingAverage(series, config.getNumberOfObservations());
// TODO: Is it always moving average with length of three?
// Apply moving average of length 3
series = movingAverage(series, 3);
// Loess smoothing with d = 1, q = n_l
series = loessSmooth(series);
return series;
}
private double[] loessSmooth(double[] series) {
double[] times = new double[series.length];
for (int i = 0; i < series.length; i++) {
times[i] = i;
}
return loessSmooth(times, series);
}
private double[] loessSmooth(double[] times, double[] series) {
return new LoessInterpolator(LOESS_BANDWIDTH, LOESS_ROBUSTNESS_ITERATIONS).smooth(times, series);
}
private double[] movingAverage(double[] series, int window) {
double[] movingAverage = new double[series.length];
// Initialize
double average = 0;
for (int i = 0; i < window; i++) {
average += series[i] / window;
movingAverage[i] = average;
}
for (int i = window; i < series.length; i++) {
average -= series[i - window] / window;
average += series[i] / window;
movingAverage[i] = average;
}
return movingAverage;
}
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode tree = objectMapper.readTree(new File(args[0]));
int n = tree.get("ts").size();
long[] tsLong = new long[n];
double[] ts = new double[n];
double[] ys = new double[n];
for (int i = 0; i < n; i++) {
tsLong[i] = tree.get("ts").get(i).asLong();
ts[i] = tree.get("ts").get(i).asDouble();
ys[i] = tree.get("ys").get(i).asDouble();
}
STLDecomposition.Config config = new STLDecomposition.Config();
config.setNumberOfObservations(12);
STLDecomposition stl = new STLDecomposition(config);
STLResult res = stl.decompose(tsLong, ys);
objectMapper.writerWithDefaultPrettyPrinter().writeValue(new FileOutputStream(args[1]), res);
}
}
|
package com.github.rnewson.couchdb.lucene;
import static com.github.rnewson.couchdb.lucene.ServletUtils.getBooleanParameter;
import static com.github.rnewson.couchdb.lucene.ServletUtils.getIntParameter;
import static com.github.rnewson.couchdb.lucene.ServletUtils.getParameter;
import static java.lang.Math.max;
import static java.lang.Math.min;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FieldDoc;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.search.WildcardQuery;
import com.github.rnewson.couchdb.lucene.LuceneGateway.SearcherCallback;
import com.github.rnewson.couchdb.lucene.util.Analyzers;
import com.github.rnewson.couchdb.lucene.util.StopWatch;
/**
* Perform queries against local indexes.
*
* @author rnewson
*
*/
public final class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final State state;
SearchServlet(final State state) {
this.state = state;
}
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("q") == null) {
resp.sendError(400, "Missing q attribute.");
return;
}
final ViewSignature sig = state.locator.lookup(req);
if (sig == null) {
resp.sendError(400, "Unknown index.");
return;
}
final boolean debug = getBooleanParameter(req, "debug");
final boolean rewrite_query = getBooleanParameter(req, "rewrite_query");
final String body = state.lucene.withSearcher(sig, new SearcherCallback<String>() {
public String callback(final IndexSearcher searcher, final String etag) throws IOException {
// Check for 304 - Not Modified.
if (!debug && etag.equals(req.getHeader("If-None-Match"))) {
resp.setStatus(304);
return null;
}
// Parse query.
final Query q = toQuery(req);
if (q == null) {
resp.sendError(400, "Bad query syntax.");
return null;
}
final JSONObject json = new JSONObject();
json.put("q", q.toString());
if (debug) {
json.put("plan", toPlan(q));
}
json.put("etag", etag);
if (rewrite_query) {
final Query rewritten_q = q.rewrite(searcher.getIndexReader());
json.put("rewritten_q", rewritten_q.toString());
final JSONObject freqs = new JSONObject();
final Set<Term> terms = new HashSet<Term>();
rewritten_q.extractTerms(terms);
for (final Object term : terms) {
final int freq = searcher.docFreq((Term) term);
freqs.put(term, freq);
}
json.put("freqs", freqs);
} else {
// Perform the search.
final TopDocs td;
final StopWatch stopWatch = new StopWatch();
final boolean include_docs = getBooleanParameter(req, "include_docs");
final int limit = getIntParameter(req, "limit", 25);
final Sort sort = toSort(req.getParameter("sort"));
final int skip = getIntParameter(req, "skip", 0);
if (sort == null) {
td = searcher.search(q, null, skip + limit);
} else {
td = searcher.search(q, null, skip + limit, sort);
}
stopWatch.lap("search");
// Fetch matches (if any).
final int max = max(0, min(td.totalHits - skip, limit));
final JSONArray rows = new JSONArray();
final String[] fetch_ids = new String[max];
for (int i = skip; i < skip + max; i++) {
final Document doc = searcher.doc(td.scoreDocs[i].doc);
final JSONObject row = new JSONObject();
final JSONObject fields = new JSONObject();
// Include stored fields.
for (Object f : doc.getFields()) {
Field fld = (Field) f;
if (!fld.isStored())
continue;
String name = fld.name();
String value = fld.stringValue();
if (value != null) {
if ("_id".equals(name)) {
row.put("id", value);
} else {
if (!fields.has(name)) {
fields.put(name, value);
} else {
final Object obj = fields.get(name);
if (obj instanceof String) {
final JSONArray arr = new JSONArray();
arr.add((String) obj);
arr.add(value);
fields.put(name, arr);
} else {
assert obj instanceof JSONArray;
((JSONArray) obj).add(value);
}
}
}
}
}
if (!Float.isNaN(td.scoreDocs[i].score)) {
row.put("score", td.scoreDocs[i].score);
}
// Include sort order (if any).
if (td instanceof TopFieldDocs) {
final FieldDoc fd = (FieldDoc) ((TopFieldDocs) td).scoreDocs[i];
row.put("sort_order", fd.fields);
}
// Fetch document (if requested).
if (include_docs) {
fetch_ids[i - skip] = doc.get("_id");
}
if (fields.size() > 0) {
row.put("fields", fields);
}
rows.add(row);
}
// Fetch documents (if requested).
if (include_docs && fetch_ids.length > 0) {
final JSONArray fetched_docs = state.couch.getDocs(sig.getDatabaseName(), fetch_ids).getJSONArray("rows");
for (int i = 0; i < max; i++) {
rows.getJSONObject(i).put("doc", fetched_docs.getJSONObject(i).getJSONObject("doc"));
}
}
stopWatch.lap("fetch");
json.put("skip", skip);
json.put("limit", limit);
json.put("total_rows", td.totalHits);
json.put("search_duration", stopWatch.getElapsed("search"));
json.put("fetch_duration", stopWatch.getElapsed("fetch"));
// Include sort info (if requested).
if (td instanceof TopFieldDocs) {
json.put("sort_order", SearchServlet.toString(((TopFieldDocs) td).fields));
}
json.put("rows", rows);
}
Utils.setResponseContentTypeAndEncoding(req, resp);
// Cache-related headers.
resp.setHeader("ETag", etag);
resp.setHeader("Cache-Control", "must-revalidate");
// Format response body.
final String callback = req.getParameter("callback");
if (callback != null) {
return String.format("%s(%s)", callback, json);
} else {
return json.toString(debug ? 2 : 0);
}
}
});
// Write response if we have one.
if (body != null) {
final Writer writer = resp.getWriter();
try {
writer.write(body);
} finally {
writer.close();
}
}
}
private static Query toQuery(final HttpServletRequest req) {
// Parse query.
final Analyzer analyzer = Analyzers.getAnalyzer(getParameter(req, "analyzer", "standard"));
final QueryParser parser = new QueryParser(Constants.DEFAULT_FIELD, analyzer);
try {
return fixup(parser.parse(req.getParameter("q")));
} catch (final ParseException e) {
return null;
}
}
private static Query fixup(final Query query) {
if (query instanceof BooleanQuery) {
final BooleanQuery booleanQuery = (BooleanQuery) query;
for (final BooleanClause clause : booleanQuery.getClauses()) {
clause.setQuery(fixup(clause.getQuery()));
}
} else if (query instanceof TermRangeQuery) {
final TermRangeQuery termRangeQuery = (TermRangeQuery) query;
final String field = termRangeQuery.getField();
final Object lower = fixup(termRangeQuery.getLowerTerm());
final Object upper = fixup(termRangeQuery.getUpperTerm());
final boolean includesLower = termRangeQuery.includesLower();
final boolean includesUpper = termRangeQuery.includesUpper();
// Sanity check.
if (lower.getClass() != upper.getClass()) {
return null;
}
if (lower instanceof String) {
return termRangeQuery;
}
if (lower instanceof Float) {
return NumericRangeQuery.newFloatRange(field, 4, (Float) lower, (Float) upper, includesLower, includesUpper);
}
if (lower instanceof Double) {
return NumericRangeQuery.newDoubleRange(field, 8, (Double) lower, (Double) upper, includesLower, includesUpper);
}
if (lower instanceof Long) {
return NumericRangeQuery.newLongRange(field, 8, (Long) lower, (Long) upper, includesLower, includesUpper);
}
if (lower instanceof Integer) {
return NumericRangeQuery.newIntRange(field, 4, (Integer) lower, (Integer) upper, includesLower, includesUpper);
}
}
return query;
}
private static Object fixup(final String value) {
if (value.matches("\\d+\\.\\d+f"))
return Float.parseFloat(value);
if (value.matches("\\d+\\.\\d+"))
return Double.parseDouble(value);
if (value.matches("\\d+[lL]"))
return Long.parseLong(value.substring(0, value.length() - 1));
if (value.matches("\\d+"))
return Integer.parseInt(value);
return String.class;
}
private static Sort toSort(final String sort) {
if (sort == null) {
return null;
} else {
final String[] split = sort.split(",");
final SortField[] sort_fields = new SortField[split.length];
for (int i = 0; i < split.length; i++) {
String tmp = split[i];
final boolean reverse = tmp.charAt(0) == '\\';
// Strip sort order character.
if (tmp.charAt(0) == '\\' || tmp.charAt(0) == '/') {
tmp = tmp.substring(1);
}
final boolean has_type = tmp.indexOf(':') != -1;
if (!has_type) {
sort_fields[i] = new SortField(tmp, SortField.STRING, reverse);
} else {
final String field = tmp.substring(0, tmp.indexOf(':'));
final String type = tmp.substring(tmp.indexOf(':') + 1);
int type_int = SortField.STRING;
if ("int".equals(type)) {
type_int = SortField.INT;
} else if ("float".equals(type)) {
type_int = SortField.FLOAT;
} else if ("double".equals(type)) {
type_int = SortField.DOUBLE;
} else if ("long".equals(type)) {
type_int = SortField.LONG;
} else if ("date".equals(type)) {
type_int = SortField.LONG;
} else if ("string".equals(type)) {
type_int = SortField.STRING;
}
sort_fields[i] = new SortField(field, type_int, reverse);
}
}
return new Sort(sort_fields);
}
}
private static String toString(final SortField[] sortFields) {
final JSONArray result = new JSONArray();
for (final SortField field : sortFields) {
final JSONObject col = new JSONObject();
col.element("field", field.getField());
col.element("reverse", field.getReverse());
final String type;
switch (field.getType()) {
case SortField.DOC:
type = "doc";
break;
case SortField.SCORE:
type = "score";
break;
case SortField.INT:
type = "int";
break;
case SortField.LONG:
type = "long";
break;
case SortField.BYTE:
type = "byte";
break;
case SortField.CUSTOM:
type = "custom";
break;
case SortField.DOUBLE:
type = "double";
break;
case SortField.FLOAT:
type = "float";
break;
case SortField.SHORT:
type = "short";
break;
case SortField.STRING:
type = "string";
break;
default:
type = "unknown";
break;
}
col.element("type", type);
result.add(col);
}
return result.toString();
}
/**
* Produces a string representation of the query classes used for a query.
*
* @param query
* @return
*/
private String toPlan(final Query query) {
final StringBuilder builder = new StringBuilder(300);
toPlan(builder, query);
return builder.toString();
}
private void toPlan(final StringBuilder builder, final Query query) {
builder.append(query.getClass().getSimpleName());
builder.append("(");
if (query instanceof TermQuery) {
planTermQuery(builder, (TermQuery) query);
} else if (query instanceof BooleanQuery) {
planBooleanQuery(builder, (BooleanQuery) query);
} else if (query instanceof TermRangeQuery) {
planTermRangeQuery(builder, (TermRangeQuery) query);
} else if (query instanceof PrefixQuery) {
planPrefixQuery(builder, (PrefixQuery) query);
} else if (query instanceof WildcardQuery) {
planWildcardQuery(builder, (WildcardQuery) query);
} else if (query instanceof FuzzyQuery) {
planFuzzyQuery(builder, (FuzzyQuery) query);
} else if (query instanceof NumericRangeQuery) {
planNumericRangeQuery(builder, (NumericRangeQuery) query);
}
builder.append(",boost=" + query.getBoost() + ")");
}
private void planNumericRangeQuery(final StringBuilder builder, final NumericRangeQuery query) {
builder.append(query.getMin());
builder.append(" TO ");
builder.append(query.getMax());
builder.append(" AS ");
builder.append(query.getMin().getClass().getSimpleName());
}
private void planFuzzyQuery(final StringBuilder builder, final FuzzyQuery query) {
builder.append(query.getTerm());
builder.append(",prefixLength=");
builder.append(query.getPrefixLength());
builder.append(",minSimilarity=");
builder.append(query.getMinSimilarity());
}
private void planWildcardQuery(final StringBuilder builder, final WildcardQuery query) {
builder.append(query.getTerm());
}
private void planPrefixQuery(final StringBuilder builder, final PrefixQuery query) {
builder.append(query.getPrefix());
}
private void planTermRangeQuery(final StringBuilder builder, final TermRangeQuery query) {
builder.append(query.getLowerTerm());
builder.append(" TO ");
builder.append(query.getUpperTerm());
}
private void planBooleanQuery(final StringBuilder builder, final BooleanQuery query) {
for (final BooleanClause clause : query.getClauses()) {
builder.append(clause.getOccur());
toPlan(builder, clause.getQuery());
}
}
private void planTermQuery(final StringBuilder builder, final TermQuery query) {
builder.append(query.getTerm());
}
}
|
package com.expression.parser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.expression.parser.exception.CalculatorException;
import com.expression.parser.function.Complex;
import com.expression.parser.function.ComplexFunction;
import com.expression.parser.function.FunctionX;
import com.expression.parser.function.FunctionXs;
import com.expression.parser.util.ParserResult;
import com.expression.parser.util.Point;
/**
* The Class Parser.
*/
public class Parser {
/**
* Eval
*
* This a parser eval. The real parser of a function is within the Fuction
*
* FunctionX: functions with one var. Example 1+2*x --> it is more optimized
*
* FunctionXs: functions with several vars. Example: 1+2*x+3*y...
*
* ComplexFunction: Complex functions with several vars: one var or n vars. Example: 1+x+y +j
*
* @param function the function: 1+2*x+j...
* @param values the values x=10, y=20
*
* @return the parser result: complex or real value
*/
public static ParserResult eval(final String function, final Point... values) {
final ParserResult result = new ParserResult();
FunctionX f_x = null;
FunctionXs f_xs = null;
ComplexFunction complexFunction = null;
if ((function != null) && !function.isEmpty()) {
if (Parser.pointIsComplex(values) || function.toLowerCase().contains("j")) { // Complex
complexFunction = new ComplexFunction(function);
final List<Complex> valuesList = pointToComplexValue(values);
final List<String> varsList = pointToVar(values);
try {
result.setComplexValue(complexFunction.getValue(valuesList, varsList));
} catch (final CalculatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
if (values != null) {
if (values.length == 1) {
f_x = new FunctionX(function);
if ((values[0].getStringValue() != null && !values[0].getStringValue().isEmpty())) {
final ParserResult evaluatedValue = Parser.eval(values[0].getStringValue());
result.setValue(f_x.getF_xo(evaluatedValue.getValue()));
} else {
result.setValue(f_x.getF_xo(values[0].getValue()));
}
} else if (values.length > 1) {
f_xs = new FunctionXs(function);
final List<Double> valuesList = pointToValue(values);
final List<String> varsList = pointToVar(values);
result.setValue(f_xs.getValue(valuesList, varsList));
}
} else {
f_x = new FunctionX(function);
result.setValue(f_x.getF_xo(0));
}
}
catch (final CalculatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
/**
* Eval.
*
* @param function the function
* @param vars the vars
* @param values the values
* @return the double
*/
public static double eval(final String function, final String[] vars, final Double[] values) {
double result = 0;
FunctionX f_x = null;
FunctionXs f_xs = null;
if ((function != null) && !function.equals("")) {
try {
if ((((vars == null) || (vars.length < 1)) && (values == null)) || (values.length < 1)) {
f_x = new FunctionX(function);
result = f_x.getF_xo(0);
} else if ((values != null) && (values.length == 1)) {
f_x = new FunctionX(function);
result = f_x.getF_xo(values[0]);
} else if ((vars != null) && (vars.length > 1) && (values != null) && (values.length > 1)) {
f_xs = new FunctionXs(function);
final List<Double> valuesList = Arrays.asList(values);
final List<String> varsList = Arrays.asList(vars);
result = f_xs.getValue(valuesList, varsList);
}
} catch (final CalculatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
/**
* Eval.
*
* @param function the function
* @return the parser result
*/
public static ParserResult eval(final String function) {
ParserResult result = new ParserResult();
FunctionX f_x = null;
if ((function != null) && !function.equals("")) {
try {
if ((function.toLowerCase().contains("j") || function.toLowerCase().contains("i"))
&& !function.toLowerCase().contains("x")) {
result = eval(function, new Point("x", new Complex(1, 0)));
} else if (!function.toLowerCase().contains("x")) {
f_x = new FunctionX(function);
result.setValue(f_x.getF_xo(0));
} else {
throw new CalculatorException("function is not well defined");
}
} catch (final CalculatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
/**
* PointToValue.
*
* @param values the values
* @return the list
*/
private static List<Double> pointToValue(final Point... values) {
final List<Double> result = new ArrayList<Double>();
for (int i = 0; i < values.length; i++) {
if ((values[i].getStringValue() != null && !values[i].getStringValue().isEmpty())) {
final ParserResult evaluatedValue = Parser.eval(values[i].getStringValue());
result.add(evaluatedValue.getValue());
} else {
result.add(values[i].getValue());
}
}
return result;
}
/**
* PointToComplexValue.
*
* @param values the values
* @return the list
*/
private static List<Complex> pointToComplexValue(final Point... values) {
final List<Complex> result = new ArrayList<Complex>();
for (int i = 0; i < values.length; i++) {
if (values[i].isComplex() && (values[i].getStringValue() == null || values[i].getStringValue().isEmpty())) {
result.add(values[i].getComplexValue());
} else if ((values[i].getStringValue() != null && !values[i].getStringValue().isEmpty())) {
final ParserResult evaluatedValue = Parser.eval(values[i].getStringValue());
if (evaluatedValue.isComplex()) {
result.add(evaluatedValue.getComplexValue());
} else {
result.add(new Complex(evaluatedValue.getValue(), 0));
}
} else {
result.add(new Complex(values[i].getValue(), 0));
}
}
return result;
}
/**
* pointIsComplex.
*
* @param values the values
* @return true, if successful
*/
private static boolean pointIsComplex(final Point... values) {
boolean result = false;
for (int i = 0; i < values.length; i++) {
if (values[i].isComplex() && (values[i].getStringValue() == null || values[i].getStringValue().isEmpty())) {
result = true;
break;
} else {
if (values[i].getStringValue() != null && !values[i].getStringValue().isEmpty()) {
final ParserResult evaluatedValue = Parser.eval(values[i].getStringValue());
if (evaluatedValue.isComplex()) {
result = true;
break;
}
}
}
}
return result;
}
/**
* PointToVar.
*
* @param values the values
* @return the list
*/
private static List<String> pointToVar(final Point... values) {
final List<String> result = new ArrayList<String>();
for (int i = 0; i < values.length; i++) {
result.add(values[i].getVar());
}
return result;
}
}
|
package com.github.sbugat.rundeckmonitor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JOptionPane;
import org.rundeck.api.RundeckApiException.RundeckApiLoginException;
import org.rundeck.api.RundeckApiException.RundeckApiTokenException;
import org.rundeck.api.RundeckClient;
import org.rundeck.api.domain.RundeckExecution;
import org.rundeck.api.domain.RundeckExecution.ExecutionStatus;
import org.rundeck.api.domain.RundeckProject;
import org.rundeck.api.query.ExecutionQuery;
import org.rundeck.api.util.PagedResults;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import com.github.sbugat.rundeckmonitor.configuration.InvalidPropertyException;
import com.github.sbugat.rundeckmonitor.configuration.MissingPropertyException;
import com.github.sbugat.rundeckmonitor.configuration.RundeckMonitorConfiguration;
import com.github.sbugat.rundeckmonitor.configuration.UnknownProjectException;
import com.github.sbugat.rundeckmonitor.tools.EnvironmentTools;
import com.github.sbugat.rundeckmonitor.tools.RundeckClientTools;
import com.github.sbugat.rundeckmonitor.tools.SystemTools;
import com.github.sbugat.rundeckmonitor.wizard.InterfaceType;
import com.github.sbugat.rundeckmonitor.wizard.RundeckMonitorConfigurationWizard;
/**
* Primary and main class of the Rundeck Monitor.
*
* @author Sylvain Bugat
*
*/
public class RundeckMonitor implements Runnable {
/**SLF4J XLogger.*/
private static final XLogger LOG = XLoggerFactory.getXLogger( RundeckMonitor.class );
private final VersionChecker versionChecker;
/**Configuration of the rundeck monitor with default values if some properties are missing or are empty.*/
private final RundeckMonitorConfiguration rundeckMonitorConfiguration;
/**Time zone difference between local machine and rundeck server to correctly detect late execution.*/
private long dateDelta;
/**Rundeck client API used to interact with rundeck rest API.*/
private RundeckClient rundeckClient;
/**Tray icon and his menu for updating jobs and state displayed.*/
private final RundeckMonitorTrayIcon rundeckMonitorTrayIcon;
/**Current state (failed job/long process/disconnected) of the rundeck monitor.*/
private final RundeckMonitorState rundeckMonitorState = new RundeckMonitorState();
/**Set for all known late execution identifiers.*/
private Set<Long> knownLateExecutionIds = new LinkedHashSet<>();
/**Set for all known failed execution identifiers.*/
private Set<Long> knownFailedExecutionIds = new LinkedHashSet<>();
/**
* Initialize the rundeck monitor, load configuration and try to connect to the configured rundeck.
*
* @throws IOException in case of loading configuration error
* @throws InvalidPropertyException in case of loading configuration property error
* @throws MissingPropertyException in case of loading configuration property error
* @throws UnknownProjectException in case of unknown RunDeck project
*/
public RundeckMonitor( final RundeckMonitorConfiguration rundeckMonitorConfigurationArg, final VersionChecker versionCheckerArg ) throws IOException, MissingPropertyException, InvalidPropertyException, UnknownProjectException {
LOG.entry();
versionChecker = versionCheckerArg;
rundeckMonitorConfiguration = rundeckMonitorConfigurationArg;
//Configuration checking and initialize a new Rundeck client
initRundeckClient();
//Initialize the tray icon
if( EnvironmentTools.isWindows() && InterfaceType.SWING.name().equals( rundeckMonitorConfiguration.getInterfaceType() ) ) {
rundeckMonitorTrayIcon = new RundeckMonitorSwingTrayIcon( rundeckMonitorConfiguration, rundeckMonitorState );
}
else {
rundeckMonitorTrayIcon = new RundeckMonitorAWTTrayIcon( rundeckMonitorConfiguration, rundeckMonitorState );
}
try {
//Initialize and update the rundeck monitor failed/late jobs
updateRundeckHistory( true );
//Clean any temporary downloaded jar
versionChecker.cleanOldAndTemporaryJar();
}
catch(final Exception e) {
rundeckMonitorTrayIcon.disposeTrayIcon();
LOG.exit( e );
throw e;
}
LOG.exit();
}
public void reloadConfiguration() throws IOException, MissingPropertyException, InvalidPropertyException, UnknownProjectException {
//Configuration checking
rundeckMonitorConfiguration.loadConfigurationPropertieFile();
//Configuration checking and initialize a new Rundeck client
initRundeckClient();
//Time-zone delta between srundeck server and the computer where rundeck monitor is running
dateDelta = rundeckClient.getSystemInfo().getDate().getTime() - new Date().getTime();
//Reinit monitor state
rundeckMonitorState.setFailedJobs( false );
rundeckMonitorState.setLateJobs( false );
rundeckMonitorState.setDisconnected( false );
//Initialize and update the rundeck monitor failed/late jobs
updateRundeckHistory( true );
LOG.exit();
}
/**
* Check the configuration and initialize a new rundeck client.
*
* @throws MissingPropertyException when check configuration
* @throws InvalidPropertyException when check configuration
* @throws UnknownProjectException if the configured project is unknown
*/
private void initRundeckClient() throws MissingPropertyException, InvalidPropertyException, UnknownProjectException {
//Configuration checking
rundeckMonitorConfiguration.verifyConfiguration();
//Initialize the rundeck client with the API version
rundeckClient = RundeckClientTools.buildRundeckClient( rundeckMonitorConfiguration, false );
//Check if the configured project exists
boolean existingProject = false;
for( final RundeckProject rundeckProject: rundeckClient.getProjects() ) {
if( rundeckMonitorConfiguration.getRundeckProject().equals( rundeckProject.getName() ) ) {
existingProject = true;
break;
}
}
if( ! existingProject ) {
final UnknownProjectException exception = new UnknownProjectException( rundeckMonitorConfiguration.getRundeckProject() );
LOG.error( "Error unknown project: {}", rundeckMonitorConfiguration.getRundeckProject() ); //$NON-NLS-1$
LOG.exit( exception );
throw exception;
}
//Time-zone delta between srundeck server and the computer where rundeck monitor is running
dateDelta = rundeckClient.getSystemInfo().getDate().getTime() - new Date().getTime();
}
private boolean checkNewConfiguration( final Date lastConfigurationUpdateDate ) {
LOG.entry( lastConfigurationUpdateDate );
Date lastConfigurationDate = lastConfigurationUpdateDate;
if( RundeckMonitorConfiguration.propertiesFileUpdated( lastConfigurationDate ) ) {
//Wait until configuration is reloaded or exit
while( true ) {
if( RundeckMonitorConfiguration.propertiesFileUpdated( lastConfigurationDate ) ) {
//reload the configuration
try {
reloadConfiguration();
rundeckMonitorTrayIcon.reloadConfiguration();
//Set the tray icon as reconnected
rundeckMonitorState.setDisconnected( false );
rundeckMonitorTrayIcon.updateTrayIcon();
LOG.exit( true );
return true;
}
catch( final IOException | MissingPropertyException | InvalidPropertyException | UnknownProjectException | RuntimeException e) {
//Set the tray icon as disconnected
rundeckMonitorState.setDisconnected( true );
rundeckMonitorTrayIcon.updateTrayIcon();
if( handleStartupException( e, false ) ) {
new RundeckMonitorConfigurationWizard( rundeckMonitorConfiguration, true );
lastConfigurationDate = new Date();
}
//Dispose tray icon and exit
else {
rundeckMonitorTrayIcon.disposeTrayIcon();
SystemTools.exit( SystemTools.EXIT_CODE_ERROR );
}
}
}
//Wait 1s
try {
Thread.sleep( 1000 );
}
catch ( final InterruptedException e) {
//Nothing to do
LOG.error( "Waiting interrupted", e ); //$NON-NLS-1$
}
}
}
LOG.exit( false );
return false;
}
/**
* RundeckMonitor background process method executing the main loop.
*/
public void run() {
LOG.entry();
Date lastConfigurationUpdateDate = new Date();
while( true ){
try {
if( checkNewConfiguration( lastConfigurationUpdateDate ) ) {
lastConfigurationUpdateDate = new Date();
}
//Update the tray icon menu
updateRundeckHistory( false );
if( versionChecker.isversionCheckerDisabled() ) {
rundeckMonitorConfiguration.disableVersionChecker();
rundeckMonitorConfiguration.saveMonitorConfigurationPropertieFile();
versionChecker.resetVersionCheckerDisabled();
}
//If download finished
if( versionChecker.isDownloadDone() && versionChecker.restart() ) {
//Restart, remove the tray icon and exit
rundeckMonitorTrayIcon.disposeTrayIcon();
SystemTools.exit( SystemTools.EXIT_CODE_OK );
}
try {
Thread.sleep( rundeckMonitorConfiguration.getRefreshDelay() * 1000l );
}
catch ( final Exception e ) {
//Nothing to do
LOG.error( "Waiting interrupted", e ); //$NON-NLS-1$
}
}
//If an exception is catch, consider the monitor as disconnected
catch ( final IOException | RuntimeException e ) {
rundeckMonitorState.setDisconnected( true );
rundeckMonitorTrayIcon.updateTrayIcon();
try {
Thread.sleep( rundeckMonitorConfiguration.getRefreshDelay() * 1000l );
}
catch ( final InterruptedException e1) {
//Nothing to do
LOG.error( "Waiting interrupted", e1 ); //$NON-NLS-1$
}
}
}
}
/**
* Call Rundeck rest API and update the monitor state and displayed jobs if there are new failed/late jobs.
*
* @param init boolean to indicate if it's the first call to this method for the monitor initialization
*/
private void updateRundeckHistory( final boolean init ) {
LOG.entry( init );
//call Rundeck rest API
final ExecutionQuery executionQuery = ExecutionQuery.builder().project( rundeckMonitorConfiguration.getRundeckProject() ).status( ExecutionStatus.FAILED ).build();
final PagedResults<RundeckExecution> lastFailedJobs = rundeckClient.getExecutions( executionQuery, Long.valueOf( rundeckMonitorConfiguration.getFailedJobNumber() ), null );
final List<RundeckExecution> currentExecutions = rundeckClient.getRunningExecutions( rundeckMonitorConfiguration.getRundeckProject() );
//Rundeck calls are OK
rundeckMonitorState.setDisconnected( false );
final Date currentTime = new Date();
final List<JobExecutionInfo> listJobExecutionInfo = new ArrayList<>();
boolean lateExecutionFound = false;
//Scan runnings jobs to detect if they are late
for( final RundeckExecution rundeckExecution : currentExecutions ) {
if( currentTime.getTime() - rundeckExecution.getStartedAt().getTime() + dateDelta > rundeckMonitorConfiguration.getLateThreshold() * 1000l ) {
lateExecutionFound = true;
final boolean newLongExecution = ! knownLateExecutionIds.contains( rundeckExecution.getId() );
if( newLongExecution ) {
knownLateExecutionIds.add( rundeckExecution.getId() );
}
final String jobName;
if( null != rundeckExecution.getJob() ) {
jobName = rundeckExecution.getJob().getName();
}
else {
jobName = rundeckExecution.getDescription();
}
listJobExecutionInfo.add( new JobExecutionInfo( rundeckExecution.getId(), rundeckExecution.getStartedAt(), jobName, true, newLongExecution ) );
}
}
rundeckMonitorState.setLateJobs( lateExecutionFound );
//Add all lasts failed jobs to the list
for( final RundeckExecution rundeckExecution : lastFailedJobs.getResults() ) {
final boolean newFailedJob = ! knownFailedExecutionIds.contains( rundeckExecution.getId() );
if( newFailedJob ) {
rundeckMonitorState.setFailedJobs( true );
knownFailedExecutionIds.add( rundeckExecution.getId() );
}
final String jobName;
if( null != rundeckExecution.getJob() ) {
jobName = rundeckExecution.getJob().getName();
}
else {
jobName = rundeckExecution.getDescription();
}
listJobExecutionInfo.add( new JobExecutionInfo( rundeckExecution.getId(), rundeckExecution.getStartedAt(), jobName, false, newFailedJob && ! init ) );
}
//Display failed/late jobs on the trayIcon menu
rundeckMonitorTrayIcon.updateExecutionIdsList( listJobExecutionInfo );
if( init ) {
rundeckMonitorState.setFailedJobs( false );
}
//Update the tray icon color
rundeckMonitorTrayIcon.updateTrayIcon();
LOG.exit();
}
/**
* Rundeck launcher exception handler, display an error message based on the argument exception.
*
* @param exception exception to analyze
* @param initialization indicate if the tray icon is not loaded yet
* @return true if the wizard needs to be launched
*/
private static boolean handleStartupException( final Exception exception, final boolean initialization ) {
LOG.entry( exception, initialization );
final String errorMessage;
//Loading properties exceptions
if( MissingPropertyException.class.isInstance( exception ) ) {
errorMessage = "Missing mandatory property," + System.lineSeparator() + "check and change this parameter value:" + System.lineSeparator() + '"' + (( MissingPropertyException ) exception).getProperty() + "\"."; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
else if( InvalidPropertyException.class.isInstance( exception ) ) {
errorMessage = "Invalid property value:" + System.lineSeparator() + "check and change this parameter value:" + System.lineSeparator() + '"' + (( InvalidPropertyException ) exception).getProperty() + '=' + (( InvalidPropertyException ) exception).getPropertyValue() + "\"."; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
//Unknown rundeck project exception
else if( UnknownProjectException.class.isInstance( exception ) ) {
errorMessage = "Unknown rundeck project:" + System.lineSeparator() + "check and change this parameter value:" + System.lineSeparator() + '"' + RundeckMonitorConfiguration.RUNDECK_MONITOR_PROPERTY_PROJECT + '=' + (( UnknownProjectException ) exception).getProjectName() + "\"."; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
//Property file not found
else if( FileNotFoundException.class.isInstance( exception ) ) {
errorMessage = "Property file not found:" + RundeckMonitorConfiguration.RUNDECK_MONITOR_PROPERTIES_FILE + "check this file."; //$NON-NLS-1$ //$NON-NLS-2$
}
//Loading configuration file I/O exception
else if( IOException.class.isInstance( exception ) ) {
errorMessage = "Error loading property file:" + RundeckMonitorConfiguration.RUNDECK_MONITOR_PROPERTIES_FILE + "check access rights of this file."; //$NON-NLS-1$ //$NON-NLS-2$
}
//Authentication exceptions
else if( RundeckApiTokenException.class.isInstance( exception ) ) {
errorMessage = "Invalid authentication token," + System.lineSeparator() + "check and change this parameter value:" + System.lineSeparator() + '"' + RundeckMonitorConfiguration.RUNDECK_MONITOR_PROPERTY_API_KEY + "\"."; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
else if( RundeckApiLoginException.class.isInstance( exception ) ) {
errorMessage = "Invalid login/password," + System.lineSeparator() + "check and change these parameters values:" + System.lineSeparator() + '"' + RundeckMonitorConfiguration.RUNDECK_MONITOR_PROPERTY_LOGIN + '"' + System.lineSeparator() + '"' + RundeckMonitorConfiguration.RUNDECK_MONITOR_PROPERTY_PASSWORD + "\"."; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
else {
final StringWriter stringWriter = new StringWriter();
exception.printStackTrace( new PrintWriter( stringWriter ) );
errorMessage = exception.getMessage() + System.lineSeparator() + stringWriter.toString();
}
//Show a dialog with edit configuration option
final Object[] options = { "Exit", "Edit configuration" }; //$NON-NLS-1$ //$NON-NLS-2$
final int errorUserReturn;
if( initialization ) {
errorUserReturn = JOptionPane.showOptionDialog( null, errorMessage, "RundeckMonitor initialization error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[ 0 ] ); //$NON-NLS-1$
}
else {
errorUserReturn = JOptionPane.showOptionDialog( null, errorMessage, "RundeckMonitor reload configuration error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[ 0 ] ); //$NON-NLS-1$
}
if( JOptionPane.NO_OPTION == errorUserReturn ) {
LOG.exit( true );
return true;
}
LOG.exit( false );
return false;
}
/**
* RundeckMonitor main method.
*
* @param args program arguments: none is expected and used
*/
public static void main( final String[] args ) {
LOG.entry( ( Object[] ) args );
//Launch the configuration wizard if there is no configuration file
if( ! RundeckMonitorConfiguration.propertiesFileExists() ) {
LOG.info( "Launching configuration wizard" ); //$NON-NLS-1$
new RundeckMonitorConfigurationWizard( new RundeckMonitorConfiguration(), true );
}
//Wait until the configuration file is created
while( ! RundeckMonitorConfiguration.propertiesFileExists() ) {
try {
Thread.sleep( 1000 );
}
catch( final InterruptedException e ) {
LOG.error( "Waiting interrupted", e ); //$NON-NLS-1$
}
}
//Initialization of the version checker
final VersionChecker versionChecker = new VersionChecker( "Sylvain-Bugat", "RundeckMonitor", "rundeck-monitor", "-jar-with-dependencies" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
//Clean any temporary downloaded jar
versionChecker.cleanOldAndTemporaryJar();
while( true ) {
final RundeckMonitorConfiguration rundeckMonitorConfiguration = new RundeckMonitorConfiguration();
try {
//Configuration loading
rundeckMonitorConfiguration.loadConfigurationPropertieFile();
//Start the main thread
new Thread( new RundeckMonitor( rundeckMonitorConfiguration, versionChecker ) ).start();
if( rundeckMonitorConfiguration.isVersionCheckerEnabled() ) {
//Start the version checker thread
LOG.info( "Launching version checker" ); //$NON-NLS-1$
new Thread( versionChecker ).start();
}
//Monitor and Version started without exception, end the launch thread
return;
}
catch ( final IOException | MissingPropertyException | InvalidPropertyException | UnknownProjectException | RuntimeException e ) {
if( ! handleStartupException( e, true ) ) {
SystemTools.exit( SystemTools.EXIT_CODE_ERROR );
}
}
//Date the current time and launch the configuration wizard
final Date systemDate = new Date();
new RundeckMonitorConfigurationWizard( rundeckMonitorConfiguration, true );
//Wait until the configuration file is updated
boolean configurationFileUpdated = false;
while( ! configurationFileUpdated ) {
try {
Thread.sleep( 1000 );
}
catch( final InterruptedException e ) {
LOG.error( "Waiting interrupted", e ); //$NON-NLS-1$
}
configurationFileUpdated = RundeckMonitorConfiguration.propertiesFileUpdated( systemDate );
}
}
}
}
|
package com.gengo.client;
import java.awt.image.BufferedImage;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.gengo.client.enums.HttpMethod;
import com.gengo.client.enums.Rating;
import com.gengo.client.enums.RejectReason;
import com.gengo.client.exceptions.GengoException;
import com.gengo.client.payloads.Approval;
import com.gengo.client.payloads.FileJob;
import com.gengo.client.payloads.Payload;
import com.gengo.client.payloads.Rejection;
import com.gengo.client.payloads.Revision;
import com.gengo.client.payloads.TranslationJob;
import com.gengo.client.payloads.Payloads;
public class GengoClient extends JsonHttpApi
{
private static final String STANDARD_BASE_URL = "http://api.gengo.com/v2/";
private static final String SANDBOX_BASE_URL = "http://api.sandbox.gengo.com/v2/";
/** Strings used to represent TRUE and FALSE in requests */
public static final String MYGENGO_TRUE = "1";
public static final String MYGENGO_FALSE = "0";
private String baseUrl = STANDARD_BASE_URL;
/**
* Initialize the client.
* @param publicKey your Gengo.com public API key
* @param privateKey your Gengo.com private API key
*/
public GengoClient(String publicKey, String privateKey)
{
this(publicKey, privateKey, false);
}
/**
* Initialize the client with the option to use the sandbox.
* @param publicKey your Gengo.com public API key
* @param privateKey your Gengo.com private API key
* @param useSandbox true to use the sandbox, false to use the live service
*/
public GengoClient(String publicKey, String privateKey, boolean useSandbox)
{
super(publicKey, privateKey);
setUseSandbox(useSandbox);
}
/**
* @return true iff the client is using the sandbox
*/
public boolean getUseSandbox()
{
return SANDBOX_BASE_URL.equals(baseUrl);
}
/**
* Set the client to use the sandbox or the live service.
* @param use true iff the client should use the sandbox
*/
public void setUseSandbox(boolean use)
{
baseUrl = use ? SANDBOX_BASE_URL : STANDARD_BASE_URL;
}
/**
* Set a custom base URL. For development testing purposes only.
* @param baseUrl a custom API base URL
*/
public void setBaseUrl(String baseUrl)
{
this.baseUrl = baseUrl;
}
/**
* Get account statistics.
* @return the response from the server
* @throws GengoException
*/
public JSONObject getAccountStats() throws GengoException
{
String url = baseUrl + "account/stats";
return call(url, HttpMethod.GET);
}
/**
* Get account balance.
* @return the response from the server
* @throws GengoException
*/
public JSONObject getAccountBalance() throws GengoException
{
String url = baseUrl + "account/balance";
return call(url, HttpMethod.GET);
}
/**
* Get preferred translators in array by langs and tier
* @return the response from the server
* @throws GengoException
*/
public JSONObject getAccountPreferredTranslators() throws GengoException
{
String url = baseUrl + "account/preferred_translators";
return call(url, HttpMethod.GET);
}
/**
* Submit multiple jobs for translation.
* @param jobs TranslationJob payload objects
* @param processAsGroup true iff the jobs should be processed as a group
* @return the response from the server
* @throws GengoException
*/
public JSONObject postTranslationJobs(List<TranslationJob> jobs, boolean processAsGroup)
throws GengoException
{
try
{
String url = baseUrl + "translate/jobs";
JSONObject data = new JSONObject();
/* We can safely cast our list of jobs into a list of the payload base type */
@SuppressWarnings({ "rawtypes", "unchecked" })
List<Payload> p = (List)jobs;
data.put("jobs", (new Payloads(p)).toJSONArray());
data.put("as_group", processAsGroup ? MYGENGO_TRUE : MYGENGO_FALSE);
JSONObject rsp = call(url, HttpMethod.POST, data);
return rsp;
}
catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Request revisions for a job.
* @param id The job ID
* @param comments Comments for the translator
* @return the response from the server
* @throws GengoException
*/
public JSONObject reviseTranslationJob(int id, String comments)
throws GengoException
{
try
{
String url = baseUrl + "translate/job/" + id;
JSONObject data = new JSONObject();
data.put("action", "revise");
data.put("comment", comments);
return call(url, HttpMethod.PUT, data);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Approve a translation.
* @param id The job ID
* @param rating A rating for the translation
* @param commentsForTranslator Comments for the translator
* @param commentsForGengo Comments for Gengo
* @param feedbackIsPublic true iff the feedback can be shared publicly
* @return the response from the server
* @throws GengoException
*/
public JSONObject approveTranslationJob(int id, Rating rating,
String commentsForTranslator, String commentsForGengo,
boolean feedbackIsPublic) throws GengoException
{
try
{
String url = baseUrl + "translate/job/" + id;
JSONObject data = new JSONObject();
data.put("action", "approve");
if (commentsForTranslator != null) {
data.put("for_translator", commentsForTranslator);
}
if (commentsForGengo != null) {
data.put("for_gengo", commentsForGengo);
}
if (rating != null) {
data.put("rating", rating.toString());
}
data.put("public", feedbackIsPublic ? MYGENGO_TRUE : MYGENGO_FALSE);
return call(url, HttpMethod.PUT, data);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
public JSONObject approveTranslationJob(int id, Rating rating,
String commentsForTranslator, String commentsForGengo) throws GengoException
{
return approveTranslationJob(id, rating, commentsForTranslator, commentsForGengo, false);
}
/**
* Reject a translation.
* @param id the job ID
* @param reason reason for rejection
* @param comments comments for Gengo
* @param captcha the captcha image text
* @param requeue true iff the job should be passed on to another translator
* @return the response from the server
* @throws GengoException
*/
public JSONObject rejectTranslationJob(int id, RejectReason reason,
String comments, String captcha, boolean requeue)
throws GengoException
{
try
{
String url = baseUrl + "translate/job/" + id;
JSONObject data = new JSONObject();
data.put("action", "reject");
data.put("reason", reason.toString().toLowerCase());
data.put("comment", comments);
data.put("captcha", captcha);
data.put("follow_up", requeue ? "requeue" : "cancel");
return call(url, HttpMethod.PUT, data);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Get a translation job
* @param id the job id
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJob(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id;
return call(url, HttpMethod.GET);
}
/**
* Get all translation jobs
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobs() throws GengoException
{
String url = baseUrl + "translate/jobs/";
return call(url, HttpMethod.GET);
}
/**
* Get selected translation jobs
* @param ids a list of job ids to retrieve
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobs(List<Integer> ids) throws GengoException
{
String url = baseUrl + "translate/jobs/";
url += join(ids, ",");
return call(url, HttpMethod.GET);
}
/**
* Post a comment for a translation job
* @param id the ID of the job to comment on
* @param comment the comment
* @return the response from the server
* @throws GengoException
*/
public JSONObject postTranslationJobComment(int id, String comment)
throws GengoException
{
try
{
String url = baseUrl + "translate/job/" + id + "/comment";
JSONObject data = new JSONObject();
data.put("body", comment);
return call(url, HttpMethod.POST, data);
}
catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Get comments for a translation job
* @param id the job ID
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobComments(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id + "/comments/";
return call(url, HttpMethod.GET);
}
/**
* Get feedback for a translation job
* @param id the job ID
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobFeedback(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id + "/feedback";
return call(url, HttpMethod.GET);
}
/**
* Get all revisions for a translation job
* @param id the job ID
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobRevisions(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id + "/revisions";
return call(url, HttpMethod.GET);
}
/**
* Get a specific revision for a translation job
* @param id the job ID
* @param revisionId the ID of the revision to retrieve
* @return the response from the server
* @throws GengoException
*/
public JSONObject getTranslationJobRevision(int id, int revisionId)
throws GengoException
{
String url = baseUrl + "translate/job/" + id + "/revision/"
+ revisionId;
return call(url, HttpMethod.GET);
}
/**
* Cancel a translation job. It can only be deleted if it has not been started by a translator.
* @param id the job ID
* @return the response from the server
* @throws GengoException
*/
public JSONObject deleteTranslationJob(int id) throws GengoException
{
String url = baseUrl + "translate/job/" + id;
return call(url, HttpMethod.DELETE);
}
/**
* Get a list of supported languages and their language codes.
* @return the response from the server
* @throws GengoException
*/
public JSONObject getServiceLanguages() throws GengoException
{
String url = baseUrl + "translate/service/languages";
return call(url, HttpMethod.GET);
}
/**
* Get a list of supported language pairs, tiers, and credit prices.
* @return the response from the server
* @throws GengoException
*/
public JSONObject getServiceLanguagePairs() throws GengoException
{
String url = baseUrl + "translate/service/language_pairs";
return call(url, HttpMethod.GET);
}
/**
* Get a list of supported language pairs, tiers and credit prices for a specific source language.
* @param sourceLanguageCode the language code for the source language
* @return the response from the server
* @throws GengoException
*/
public JSONObject getServiceLanguagePairs(String sourceLanguageCode) throws GengoException
{
try
{
String url = baseUrl + "translate/service/language_pairs";
JSONObject data = new JSONObject();
data.put("lc_src", sourceLanguageCode);
return call(url, HttpMethod.GET, data);
}
catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Get a quote for translation jobs.
* @param jobs Translation job objects to be quoted for
* @return the response from the server
* @throws GengoException
*/
public JSONObject determineTranslationCost(Payloads jobs) throws GengoException
{
try
{
String url = baseUrl + "translate/service/quote/";
JSONObject data = new JSONObject();
data.put("jobs", jobs.toJSONArray());
return call(url, HttpMethod.POST, data);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Get translation jobs which were previously submitted together by their order id.
*
* @param orderId
* @return the response from the server
* @throws GengoException
*/
public JSONObject getOrderJobs(int orderId) throws GengoException
{
String url = baseUrl + "translate/order/";
url += orderId;
return call(url, HttpMethod.GET);
}
/**
* Get a quote for file jobs.
* @param jobs Translation job objects to be quoted
* @param filePaths map of file keys to filesystem paths
* @return the response from the server
* @throws GengoException
*/
public JSONObject determineTranslationCostFiles(List<FileJob> jobs, Map<String, String> filePaths) throws GengoException
{
try
{
JSONObject theJobs = new JSONObject();
for (int i = 0; i < jobs.size(); i++) {
theJobs.put(String.format("job_%s", i), jobs.get(i).toJSONObject());
}
String url = baseUrl + "translate/service/quote/file";
JSONObject data = new JSONObject();
data.put("jobs", theJobs);
return httpPostFileUpload(url, data, filePaths);
} catch (JSONException x)
{
throw new GengoException(x.getMessage(), x);
}
}
/**
* Utility function.
*/
private String join(Iterable<? extends Object> pColl, String separator)
{
Iterator<? extends Object> oIter;
if (pColl == null || (!(oIter = pColl.iterator()).hasNext()))
{
return "";
}
StringBuffer oBuilder = new StringBuffer(String.valueOf(oIter.next()));
while (oIter.hasNext())
{
oBuilder.append(separator).append(oIter.next());
}
return oBuilder.toString();
}
}
|
package com.github.stephanenicolas.mimic;
import java.lang.reflect.Modifier;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import javax.inject.Inject;
import de.icongmbh.oss.maven.plugin.javassist.ClassTransformer;
/**
* Post processes all classes annotated with {@link Mimic}.
*
* @author SNI
*
*/
public class MimicProcessor extends ClassTransformer {
@Inject
private MimicCreator mimic;
@Override
protected boolean filter(CtClass candidateClass) throws Exception {
// no support for non-static inner classes in javassist.
if (candidateClass.getDeclaringClass() != null
&& (candidateClass.getModifiers() & Modifier.STATIC) != 0) {
return false;
}
return candidateClass.hasAnnotation(Mimic.class);
}
@Override
protected void applyTransformations(final CtClass classToTransform) throws ClassNotFoundException, NotFoundException,
CannotCompileException, MimicException {
// Actually you must test if it exists, but it's just an example...
getLogger().debug("Analysing " + classToTransform);
Mimic mimicAnnnotation = (Mimic) classToTransform
.getAnnotation(Mimic.class);
Class<?> srcClass = mimicAnnnotation.sourceClass();
CtClass src = ClassPool.getDefault().get(srcClass.getName());
if (mimicAnnnotation.isMimicingInterfaces()
&& mimicAnnnotation.isMimicingFields()
&& mimicAnnnotation.isMimicingConstructors()
&& mimicAnnnotation.isMimicingMethods()) {
mimic.mimicClass(src, classToTransform);
} else {
if (mimicAnnnotation.isMimicingInterfaces()) {
mimic.mimicInterfaces(src, classToTransform);
}
if (mimicAnnnotation.isMimicingFields()) {
mimic.mimicFields(src, classToTransform);
}
if (mimicAnnnotation.isMimicingConstructors()) {
mimic.mimicConstructors(src, classToTransform);
}
if (mimicAnnnotation.isMimicingMethods()) {
mimic.mimicMethods(src, classToTransform);
}
}
getLogger().debug(
"Class " + classToTransform.getName() + " now mimics "
+ src.getName());
}
}
|
package org.deephacks.westty.cluster;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.HashSet;
import javax.enterprise.inject.Alternative;
import org.deephacks.westty.properties.WesttyProperties;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.hazelcast.config.Config;
import com.hazelcast.config.Join;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.nio.Address;
@Alternative
public class WesttyClusterProperties extends WesttyProperties {
public static final String CLUSTER_IDS = "westty.cluster.ids";
public static final String CLUSTER_PORT = "westty.cluster.port";
public static final int CLUSTER_DEFAUL_PORT = NetworkConfig.DEFAULT_PORT;
public WesttyClusterProperties(WesttyProperties properties) {
super(properties);
}
public Collection<WesttyServerId> getClusterIds() {
String prop = getProperty(CLUSTER_IDS);
if (Strings.isNullOrEmpty(prop)) {
return ImmutableList.of(new WesttyServerId(getPrivateIp(), CLUSTER_DEFAUL_PORT));
}
Collection<WesttyServerId> ips = new HashSet<>();
for (String address : prop.split(",")) {
String[] split = address.trim().split(":");
String host = split[0];
String port = split[1];
ips.add(new WesttyServerId(host, Integer.parseInt(port)));
}
return ips;
}
public void setClusterIds(Collection<WesttyServerId> ids) {
StringBuilder sb = new StringBuilder();
WesttyServerId[] list = ids.toArray(new WesttyServerId[0]);
for (int i = 0; i < list.length; i++) {
sb.append(list[i].host.trim()).append(":");
sb.append(list[i].port);
if ((i + 1) < list.length) {
sb.append(",");
}
}
setProperty(CLUSTER_IDS, sb.toString());
}
public int getClusterPort() {
String value = getProperty(CLUSTER_PORT);
if (!Strings.isNullOrEmpty(value)) {
return Integer.parseInt(value);
}
return CLUSTER_DEFAUL_PORT;
}
public void setClusterPort(int port) {
setProperty(CLUSTER_PORT, new Integer(port).toString());
}
public Config getConfig() {
Config cfg = new Config();
cfg.setProperty("hazelcast.logging.type", "slf4j");
NetworkConfig network = cfg.getNetworkConfig();
network.setPort(getClusterPort());
network.setPortAutoIncrement(false);
Join join = network.getJoin();
join.getMulticastConfig().setEnabled(false);
Collection<WesttyServerId> ids = getClusterIds();
for (WesttyServerId ip : ids) {
try {
join.getTcpIpConfig().addAddress(new Address(ip.host, ip.port)).setEnabled(true);
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
String ip = getPrivateIp();
network.getInterfaces().setEnabled(true).addInterface(ip);
return cfg;
}
}
|
package com.google.devrel.training.conference;
import com.google.api.server.spi.Constant;
/**
* Contains the client IDs and scopes for allowed clients consuming the conference API.
*/
public class Constants {
public static final String WEB_CLIENT_ID = "";
public static final String ANDROID_CLIENT_ID = "";
public static final String IOS_CLIENT_ID = "replace this with your iOS client ID";
public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID;
public static final String EMAIL_SCOPE = Constant.API_EMAIL_SCOPE;
public static final String API_EXPLORER_CLIENT_ID = Constant.API_EXPLORER_CLIENT_ID;
public static final String MEMCACHE_ANNOUNCEMENTS_KEY = "RECENT_ANNOUNCEMENTS";
}
|
package com.growthbeat.model;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.growthbeat.Context;
public class Account extends Model {
private String id;
private String name;
private PlanGrade planGrade;
private Date created;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreated() {
return created;
}
public PlanGrade getPlanGrade() {
return planGrade;
}
public void setPlanGrade(PlanGrade planGrade) {
this.planGrade = planGrade;
}
public void setCreated(Date created) {
this.created = created;
}
public static Account findById(String id, Context context) {
return get(context, String.format("1/accounts/%s", id), new HashMap<String, Object>(), Account.class);
}
public static Account create(String name, Context context) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", name);
return post(context, "1/accounts", params, Account.class);
}
public static void deleteById(String id, Context context) {
delete(context, String.format("1/accounts/%s", id), new HashMap<String, Object>(), Void.class);
}
public enum PlanGrade {
micro, small, medium, large, extra
}
}
|
package com.hankcs.hanlp.dependency;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.collection.trie.DoubleArrayTrie;
import com.hankcs.hanlp.collection.trie.ITrie;
import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLSentence;
import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLWord;
import com.hankcs.hanlp.corpus.io.ByteArray;
import com.hankcs.hanlp.corpus.io.IOUtil;
import com.hankcs.hanlp.dependency.common.POSUtil;
import com.hankcs.hanlp.model.bigram.BigramDependencyModel;
import com.hankcs.hanlp.model.crf.CRFModel;
import com.hankcs.hanlp.model.crf.FeatureFunction;
import com.hankcs.hanlp.model.crf.Table;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.NLPTokenizer;
import com.hankcs.hanlp.utility.GlobalObjectPool;
import com.hankcs.hanlp.utility.Predefine;
import com.hankcs.hanlp.utility.TextUtility;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import static com.hankcs.hanlp.utility.Predefine.logger;
/**
*
*
* @deprecated CRFCRFn
* nn
* CRFCRFCRF
* data
* {@link com.hankcs.hanlp.dependency.nnparser.NeuralNetworkDependencyParser}
*
* @author hankcs
*/
public class CRFDependencyParser extends AbstractDependencyParser
{
CRFModel crfModel;
public CRFDependencyParser(String modelPath)
{
crfModel = GlobalObjectPool.get(modelPath);
if (crfModel != null) return;
long start = System.currentTimeMillis();
if (load(modelPath))
{
logger.info("" + modelPath + " " + (System.currentTimeMillis() - start) + " ms");
GlobalObjectPool.put(modelPath, crfModel);
}
else
{
logger.info("" + modelPath + " " + (System.currentTimeMillis() - start) + " ms");
}
}
public CRFDependencyParser()
{
this(HanLP.Config.CRFDependencyModelPath);
}
/**
*
*
* @param termList
* @return CoNLL
*/
public static CoNLLSentence compute(List<Term> termList)
{
return new CRFDependencyParser().parse(termList);
}
/**
*
*
* @param sentence
* @return CoNLL
*/
public static CoNLLSentence compute(String sentence)
{
return new CRFDependencyParser().parse(sentence);
}
boolean load(String path)
{
if (loadDat(path + Predefine.BIN_EXT)) return true;
crfModel = CRFModel.loadTxt(path, new CRFModelForDependency(new DoubleArrayTrie<FeatureFunction>())); // CRF
return crfModel != null;
}
boolean loadDat(String path)
{
ByteArray byteArray = ByteArray.createByteArray(path);
if (byteArray == null) return false;
crfModel = new CRFModelForDependency(new DoubleArrayTrie<FeatureFunction>());
return crfModel.load(byteArray);
}
boolean saveDat(String path)
{
try
{
DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(path));
crfModel.save(out);
out.close();
}
catch (Exception e)
{
logger.warning("" + path + "" + TextUtility.exceptionToString(e));
return false;
}
return true;
}
@Override
public CoNLLSentence parse(List<Term> termList)
{
Table table = new Table();
table.v = new String[termList.size()][4];
Iterator<Term> iterator = termList.iterator();
for (String[] line : table.v)
{
Term term = iterator.next();
line[0] = term.word;
line[2] = POSUtil.compilePOS(term.nature);
line[1] = line[2].substring(0, 1);
}
crfModel.tag(table);
if (HanLP.Config.DEBUG)
{
System.out.println(table);
}
CoNLLWord[] coNLLWordArray = new CoNLLWord[table.size()];
for (int i = 0; i < coNLLWordArray.length; i++)
{
coNLLWordArray[i] = new CoNLLWord(i + 1, table.v[i][0], table.v[i][2], table.v[i][1]);
}
int i = 0;
for (String[] line : table.v)
{
CRFModelForDependency.DTag dTag = new CRFModelForDependency.DTag(line[3]);
if (dTag.pos.endsWith("ROOT"))
{
coNLLWordArray[i].HEAD = CoNLLWord.ROOT;
}
else
{
int index = convertOffset2Index(dTag, table, i);
if (index == -1)
coNLLWordArray[i].HEAD = CoNLLWord.NULL;
else coNLLWordArray[i].HEAD = coNLLWordArray[index];
}
++i;
}
for (i = 0; i < coNLLWordArray.length; i++)
{
coNLLWordArray[i].DEPREL = BigramDependencyModel.get(coNLLWordArray[i].NAME, coNLLWordArray[i].POSTAG, coNLLWordArray[i].HEAD.NAME, coNLLWordArray[i].HEAD.POSTAG);
}
return new CoNLLSentence(coNLLWordArray);
}
static int convertOffset2Index(CRFModelForDependency.DTag dTag, Table table, int current)
{
int posCount = 0;
if (dTag.offset > 0)
{
for (int i = current + 1; i < table.size(); ++i)
{
if (table.v[i][1].equals(dTag.pos)) ++posCount;
if (posCount == dTag.offset) return i;
}
}
else
{
for (int i = current - 1; i >= 0; --i)
{
if (table.v[i][1].equals(dTag.pos)) ++posCount;
if (posCount == -dTag.offset) return i;
}
}
return -1;
}
static class CRFModelForDependency extends CRFModel
{
public CRFModelForDependency(ITrie<FeatureFunction> featureFunctionTrie)
{
super(featureFunctionTrie);
}
/**
* tag
*/
static class DTag
{
int offset;
String pos;
public DTag(String tag)
{
String[] args = tag.split("_", 2);
if (args[0].charAt(0) == '+') args[0] = args[0].substring(1);
offset = Integer.parseInt(args[0]);
pos = args[1];
}
@Override
public String toString()
{
return (offset > 0 ? "+" : "") + offset + "_" + pos;
}
}
DTag[] id2dtag;
@Override
public boolean load(ByteArray byteArray)
{
if (!super.load(byteArray)) return false;
initId2dtagArray();
return true;
}
private void initId2dtagArray()
{
id2dtag = new DTag[id2tag.length];
for (int i = 0; i < id2tag.length; i++)
{
id2dtag[i] = new DTag(id2tag[i]);
}
}
@Override
protected void onLoadTxtFinished()
{
super.onLoadTxtFinished();
initId2dtagArray();
}
boolean isLegal(int tagId, int current, Table table)
{
DTag tag = id2dtag[tagId];
if ("ROOT".equals(tag.pos))
{
for (int i = 0; i < current; ++i)
{
if (table.v[i][3].endsWith("ROOT")) return false;
}
return true;
}
else
{
int posCount = 0;
if (tag.offset > 0)
{
for (int i = current + 1; i < table.size(); ++i)
{
if (table.v[i][1].equals(tag.pos)) ++posCount;
if (posCount == tag.offset) return true;
}
return false;
}
else
{
for (int i = current - 1; i >= 0; --i)
{
if (table.v[i][1].equals(tag.pos)) ++posCount;
if (posCount == -tag.offset) return true;
}
return false;
}
}
}
@Override
public void tag(Table table)
{
int size = table.size();
double bestScore = Double.MIN_VALUE;
int bestTag = 0;
int tagSize = id2tag.length;
LinkedList<double[]> scoreList = computeScoreList(table, 0);
for (int i = 0; i < tagSize; ++i)
{
for (int j = 0; j < tagSize; ++j)
{
if (!isLegal(j, 0, table)) continue;
double curScore = computeScore(scoreList, j);
if (matrix != null)
{
curScore += matrix[i][j];
}
if (curScore > bestScore)
{
bestScore = curScore;
bestTag = j;
}
}
}
table.setLast(0, id2tag[bestTag]);
int preTag = bestTag;
for (int i = 1; i < size; ++i)
{
scoreList = computeScoreList(table, i);
bestScore = Double.MIN_VALUE;
for (int j = 0; j < tagSize; ++j)
{
if (!isLegal(j, i, table)) continue;
double curScore = computeScore(scoreList, j);
if (matrix != null)
{
curScore += matrix[preTag][j];
}
if (curScore > bestScore)
{
bestScore = curScore;
bestTag = j;
}
}
table.setLast(i, id2tag[bestTag]);
preTag = bestTag;
}
}
}
}
|
package com.hexidec.ekit.component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import javax.swing.event.DocumentEvent;
import javax.swing.event.UndoableEditEvent;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;
import javax.swing.text.Element;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.StyleSheet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import br.gov.lexml.swing.editorhtml.util.DocumentUtil;
@SuppressWarnings("serial")
public class ExtendedHTMLDocument extends HTMLDocument {
private static final Log log = LogFactory.getLog(ExtendedHTMLDocument.class);
private boolean inlineEdit;
private List<HTMLDocumentBehavior> behaviors = new ArrayList<HTMLDocumentBehavior>();
private static final List<Tag> acceptedCommonTags = Arrays.asList(
new Tag[] { Tag.HTML, Tag.HEAD, Tag.STYLE, Tag.BODY });
private static final List<Tag> tableTags = new ArrayList<Tag>();
private static final List<Tag> acceptedInlineTags = new ArrayList<Tag>();
private static final List<Tag> acceptedTags = new ArrayList<Tag>();
private static final Map<Tag, List<Attribute>> acceptedAttributes = new HashMap<Tag, List<Attribute>>();
private static final List<String> acceptedBlockCssProperties = Arrays.asList(
new String[] {"text-indent", "margin-left"});
private static final List<String> acceptedInlineCssProperties = Arrays.asList(
new String[] {"font-weight", "font-style"});
private static final List<String> acceptedInlineTagsAsString = new ArrayList<String>();
private boolean edicaoControlada;
private int tableDepth;
private boolean dirty;
static {
// Table Tags
tableTags.addAll(Arrays.asList(
new Tag[] {Tag.TABLE, Tag.TR, Tag.TD}));
// Inline tags
acceptedInlineTags.addAll(acceptedCommonTags);
acceptedInlineTags.addAll(Arrays.asList(
new Tag[] {Tag.B, Tag.I, Tag.U, Tag.FONT, Tag.SUB, Tag.SUP, Tag.SPAN}));
// All tags
acceptedTags.addAll(acceptedInlineTags);
acceptedTags.addAll(Arrays.asList(
new Tag[] {Tag.P, Tag.BR, Tag.UL, Tag.LI}));
acceptedTags.addAll(tableTags);
// Accepted attributes
acceptedAttributes.put(Tag.STYLE, Arrays.asList(new Attribute[] {Attribute.TYPE}));
acceptedAttributes.put(Tag.FONT, Arrays.asList(new Attribute[] {Attribute.STYLE}));
acceptedAttributes.put(Tag.SPAN, Arrays.asList(new Attribute[] {Attribute.CLASS, Attribute.STYLE}));
acceptedAttributes.put(Tag.P, Arrays.asList(new Attribute[] {Attribute.CLASS, Attribute.STYLE, Attribute.ALIGN}));
acceptedAttributes.put(Tag.TD, Arrays.asList(new Attribute[] {Attribute.ALIGN}));
// Inline tags as String
for(Tag t: acceptedInlineTags) {
acceptedInlineTagsAsString.add(t.toString());
}
}
private DocumentFilterChainManager filters = new DocumentFilterChainManager();
public ExtendedHTMLDocument(AbstractDocument.Content c, StyleSheet styles) {
super(c, styles);
setup();
}
public ExtendedHTMLDocument(StyleSheet styles) {
super(styles);
setup();
}
public ExtendedHTMLDocument() {
setup();
}
private void setup() {
setDocumentFilter(filters);
}
public boolean isEdicaoControlada() {
return edicaoControlada;
}
public void setEdicaoControlada(boolean edicaoControlada) {
this.edicaoControlada = edicaoControlada;
}
public boolean isDirty() {
return dirty;
}
public void resetDirty() {
dirty = false;
}
public void addFilter(ExtendedHTMLDocumentFilter filter) {
filters.addFilter(filter);
}
public void replaceAttributes(Element e, AttributeSet a, Tag tag) {
if ((e != null) && (a != null)) {
try {
writeLock();
int start = e.getStartOffset();
DefaultDocumentEvent changes = new DefaultDocumentEvent(start,
e.getEndOffset() - start,
DocumentEvent.EventType.CHANGE);
AttributeSet sCopy = a.copyAttributes();
changes.addEdit(new AttributeUndoableEdit(e, sCopy, false));
MutableAttributeSet attr = (MutableAttributeSet) e
.getAttributes();
Enumeration aNames = attr.getAttributeNames();
Object value;
Object aName;
while (aNames.hasMoreElements()) {
aName = aNames.nextElement();
value = attr.getAttribute(aName);
if (value != null
&& !value.toString().equalsIgnoreCase(
tag.toString())) {
attr.removeAttribute(aName);
}
}
attr.addAttributes(a);
changes.end();
fireChangedUpdate(changes);
fireUndoableEditUpdate(new UndoableEditEvent(this, changes));
} finally {
writeUnlock();
}
}
}
@Override
public void setParagraphAttributes(int offset, int length, AttributeSet s,
boolean replace) {
for (HTMLDocumentBehavior b : behaviors) {
s = b.beforeSetParagraphAttributes(this, offset, length, s, replace);
}
try {
writeLock();
// Make sure we send out a change for the length of the paragraph.
int end = Math.min(offset + length, getLength());
Element e = getParagraphElement(offset);
offset = e.getStartOffset();
e = getParagraphElement(end);
length = Math.max(0, e.getEndOffset() - offset);
DefaultDocumentEvent changes = new DefaultDocumentEvent(offset,
length, DocumentEvent.EventType.CHANGE);
AttributeSet sCopy = s.copyAttributes();
int lastEnd = Integer.MAX_VALUE;
for (int pos = offset; pos <= end; pos = lastEnd) {
Element paragraph = getParagraphElement(pos);
if (lastEnd == paragraph.getEndOffset()) {
lastEnd++;
} else {
lastEnd = paragraph.getEndOffset();
}
MutableAttributeSet attr = (MutableAttributeSet) paragraph
.getAttributes();
changes.addEdit(new AttributeUndoableEdit(paragraph, sCopy,
replace));
if (replace) {
attr.removeAttributes(attr);
}
DocumentUtil.copyAllAttributesRemovingMarked(attr, s);
}
changes.end();
fireChangedUpdate(changes);
fireUndoableEditUpdate(new UndoableEditEvent(this, changes));
} finally {
writeUnlock();
}
}
@Override
public ParserCallback getReader(int pos) {
return new ParserCallbackWrapper(super.getReader(pos));
}
@Override
public ParserCallback getReader(int pos, int popDepth, int pushDepth,
Tag insertTag) {
return new ParserCallbackWrapper(super.getReader(pos, popDepth,
pushDepth, insertTag));
}
public boolean isInlineEdit() {
return inlineEdit;
}
public void setInlineEdit(boolean inlineEdit) {
this.inlineEdit = inlineEdit;
}
public List<HTMLDocumentBehavior> getBehaviors() {
return behaviors;
}
public void addBehavior(HTMLDocumentBehavior b) {
behaviors.add(b);
}
public String filterRead(String str, int pos) {
beforeRead(pos);
for(HTMLDocumentBehavior b: behaviors) {
str = b.filterRead(str, this, pos);
}
return str;
}
private void beforeRead(int pos) {
dirty = true;
tableDepth = DocumentUtil.getElementByTag(this, pos, Tag.TABLE) == null? 0: 1;
}
private class ParserCallbackWrapper extends ParserCallback {
private ParserCallback reader;
public ParserCallbackWrapper(ParserCallback reader) {
this.reader = reader;
}
public void flush() throws BadLocationException {
reader.flush();
}
public void handleText(char[] data, int pos) {
// log.debug("handleText: " + new String(data));
// Corrige problema de colar caractere 0 no final
if(!(data.length == 1 && data[0] == 0)) {
reader.handleText(data, pos);
}
}
public void handleComment(char[] data, int pos) {
reader.handleComment(data, pos);
}
public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
if(t == Tag.TABLE) {
tableDepth++;
}
if(isAccepted(t)) {
a = filterAttributeSet(t, a);
if(t == Tag.TABLE) {
a.addAttribute(Attribute.WIDTH, "100%");
}
else if(t == Tag.TD) {
a.addAttribute(Attribute.VALIGN, "top");
}
reader.handleStartTag(t, a, pos);
}
}
public void handleEndTag(Tag t, int pos) {
if(t == Tag.TABLE) {
tableDepth
}
if(isAccepted(t)) {
reader.handleEndTag(t, pos);
}
}
public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
if(isAccepted(t)) {
a = filterAttributeSet(t, a);
reader.handleSimpleTag(t, a, pos);
}
}
public void handleError(String errorMsg, int pos) {
reader.handleError(errorMsg, pos);
}
public void handleEndOfLineString(String eol) {
reader.handleEndOfLineString(eol);
}
private boolean isAccepted(Tag t) {
if(tableTags.contains(t) && tableDepth > 1) {
return false;
}
return inlineEdit? acceptedInlineTags.contains(t): acceptedTags.contains(t);
}
private MutableAttributeSet filterAttributeSet(Tag t, MutableAttributeSet a) {
for(Object aName: Collections.list((Enumeration<Object>)a.getAttributeNames())) {
List<Attribute> lAttr = acceptedAttributes.get(t);
if(lAttr == null || !lAttr.contains(aName)) {
a.removeAttribute(aName);
}
else {
if(aName == HTML.Attribute.STYLE) {
//System.out.println(">> " + aName + ": " + a.getAttribute(aName));
if(t.isBlock()) {
a.addAttribute(aName, DocumentUtil.ensureAcceptedCssProperties(
(String) a.getAttribute(aName), acceptedBlockCssProperties));
}
else {
a.addAttribute(aName, DocumentUtil.ensureAcceptedCssProperties(
(String) a.getAttribute(aName), acceptedInlineCssProperties));
}
}
}
}
return a;
}
}
private class DocumentFilterChainManager extends DocumentFilter {
private List<ExtendedHTMLDocumentFilter> filters =
new ArrayList<ExtendedHTMLDocumentFilter>();
public void addFilter(ExtendedHTMLDocumentFilter filter) {
if(!filters.contains(filter)) {
filters.add(filter);
}
}
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
replace(fb, offset, 0, string, attr);
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
replace(fb, offset, length, "", null);
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
dirty = true;
if (inlineEdit) text = text.replaceAll("(\\r|\\n)", " ");
new DocumentFilterChain(filters).replace(fb, offset, length, text, attrs);
edicaoControlada = false;
}
}
public static class DocumentFilterChain {
private Queue<ExtendedHTMLDocumentFilter> filters;
private DocumentFilterChain(List<ExtendedHTMLDocumentFilter> filters) {
this.filters = new LinkedList<ExtendedHTMLDocumentFilter>(filters);
}
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
ExtendedHTMLDocumentFilter filter = filters.poll();
if(filter != null) {
filter.replace(fb, offset, length, text, attrs, this);
}
else {
// log.info("fb.replace(" + offset + ", " + length + ", \"" + text + "\", " + attrs + ")");
fb.replace(offset, length, text, attrs);
}
}
}
public static abstract class ExtendedHTMLDocumentFilter {
public abstract void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs, DocumentFilterChain chain)
throws BadLocationException;
}
public static List<String> getAcceptedInlineTags() {
return acceptedInlineTagsAsString;
}
}
|
package org.wyona.yanel.core.util;
import org.apache.log4j.Category;
import org.wyona.commons.io.Path;
import org.wyona.yarep.core.Node;
import org.wyona.yarep.core.NodeType;
import org.wyona.yarep.core.Repository;
import org.wyona.yarep.core.RepositoryException;
public class YarepUtil {
private static Category log = Category.getInstance(YarepUtil.class);
/**
* Creates the node named by this abstract pathname, including any necessary but nonexistent parent nodes (similar to java.io.File.mkdirs()).
*/
public static Node addNodes(Repository repo, String path, int nodeType) throws RepositoryException {
if (repo.existsNode(path)) {
return repo.getNode(path);
} else {
Path parentPath = new Path(path).getParent();
if (parentPath != null) {
Node parentNode = null;
if (repo.existsNode(parentPath.toString())) {
parentNode = repo.getNode(parentPath.toString());
} else {
parentNode = addNodes(repo, parentPath.toString(), org.wyona.yarep.core.NodeType.COLLECTION);
}
return parentNode.addNode(new Path(path).getName().toString(), nodeType);
} else {
throw new RepositoryException("Root node does not have a parent!");
}
}
}
}
|
package org.csstudio.platform.libs.yamcs.ws;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.protostuff.JsonIOUtil;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.csstudio.platform.libs.yamcs.YamcsConnectionProperties;
import org.yamcs.protostuff.NamedObjectList;
/**
* Netty-implementation of a Yamcs web socket client.
* Extracted out of YamcsDataSource, since instances of that DS
* appear to be created for every parameter separately :-/
* Needs more research. would've thought everything under
* same schema shares a datasource, but alas.
*
* TODO get this completely clean of any payload information. Should be more generic. therefore
* transfer actual differentiating logic to the OutgoingEvent extensions.
*/
public class WebSocketClient {
private static final Logger log = Logger.getLogger(WebSocketClient.class.getName());
private WebSocketClientCallbackListener callback;
private EventLoopGroup group = new NioEventLoopGroup();
private URI uri;
private Channel nettyChannel;
private String userAgent;
private AtomicBoolean connected = new AtomicBoolean(false);
private AtomicBoolean enableReconnection = new AtomicBoolean(true);
private AtomicInteger seqId = new AtomicInteger(1);
// Stores ws subscriptions to be sent to the server once ws-connection is established
private BlockingQueue<OutgoingEvent> pendingOutgoingEvents = new LinkedBlockingQueue<>();
// Sends outgoing subscriptions to the web socket
//private ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
// Keeps track of sent subscriptions, so that we can do a resend when we get
// an InvalidException on some of them :-(
private ConcurrentHashMap<Integer, NamedObjectList> upstreamSubscriptionsBySeqId = new ConcurrentHashMap<>();
// TODO we should actually wait for the ACK to arrive, before sending the next request
public WebSocketClient(YamcsConnectionProperties yprops, WebSocketClientCallbackListener callback) {
this.uri = yprops.webSocketURI();
this.callback = callback;
new Thread(() -> {
try {
OutgoingEvent evt;
while((evt = pendingOutgoingEvents.take()) != null) {
// We now have at least one event to handle
Thread.sleep(500); // Wait for more events, before going into synchronized block
synchronized(pendingOutgoingEvents) {
while(pendingOutgoingEvents.peek() != null
&& evt.canMergeWith(pendingOutgoingEvents.peek())) {
OutgoingEvent otherEvt = pendingOutgoingEvents.poll();
evt = evt.mergeWith(otherEvt); // This is to counter bursts.
}
}
// Good, send the merged result
if (evt instanceof ParameterSubscribeEvent) {
doParameterSubscribe(((ParameterSubscribeEvent) evt).getIdList());
} else if (evt instanceof ParameterUnsubscribeEvent) {
doParameterUnsubscribe(((ParameterUnsubscribeEvent) evt).getIdList());
} else if (evt instanceof SubscribeAllCommandHistoryRequest) {
doSubscribeAllCommandHistory();
}
}
} catch(InterruptedException e) {
log.log(Level.SEVERE, "OOPS, got interrupted", e);
}
}).start();
}
/**
* Formatted as app/version. No spaces.
*/
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public void connect() {
enableReconnection.set(true);
createBootstrap();
}
void setConnected(boolean connected) {
this.connected.set(connected);
}
public boolean isConnected() {
return connected.get();
}
private void createBootstrap() {
HttpHeaders header = new DefaultHttpHeaders();
if (userAgent != null) {
header.add(HttpHeaders.Names.USER_AGENT, userAgent);
}
WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(
uri, WebSocketVersion.V13, null, false, header);
WebSocketClientHandler webSocketHandler = new WebSocketClientHandler(handshaker, this, callback);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
new HttpClientCodec(),
new HttpObjectAggregator(8192),
//new WebSocketClientCompressionHandler(),
webSocketHandler);
}
});
log.info("WebSocket Client connecting");
try {
ChannelFuture future = bootstrap.connect(uri.getHost(), uri.getPort()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
// Set-up reconnection attempts every second during initial set-up.
log.info("reconnect..");
group.schedule(() -> createBootstrap(), 1L, TimeUnit.SECONDS);
}
}
});
future.sync();
nettyChannel = future.sync().channel();
} catch (InterruptedException e) {
System.out.println("interrupted while trying to connect");
e.printStackTrace();
}
}
/**
* Adds said event to the queue. As soon as the web socket
* is established, queue will be iterated and if possible, similar events will be merged.
*/
public void sendRequest(OutgoingEvent request) {
// sync, because the consumer will try to merge multiple outgoing events of the same type
// using multiple operations on the queue.
synchronized(pendingOutgoingEvents) {
pendingOutgoingEvents.offer(request);
}
}
private void doParameterSubscribe(NamedObjectList idList) { // TODO we could probably refactor this into ParameterSubscribeEvent
ByteArrayOutputStream barray = new ByteArrayOutputStream();
try {
JsonIOUtil.writeTo(barray, idList, idList.cachedSchema(), false);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("will send subscribe of .. " + barray.toString());
int id = seqId.incrementAndGet();
upstreamSubscriptionsBySeqId.put(id, idList);
nettyChannel.writeAndFlush(new TextWebSocketFrame(
new StringBuilder("[").append(WSConstants.PROTOCOL_VERSION)
.append(",").append(WSConstants.MESSAGE_TYPE_REQUEST)
.append(",").append(id)
.append(",")
.append("{\"request\":\"subscribe\",\"data\":")
.append(barray.toString()).append("}]").toString()));
}
private void doParameterUnsubscribe(NamedObjectList idList) { // TODO we could probably refactor this into ParameterSubscribeEvent
ByteArrayOutputStream barray = new ByteArrayOutputStream();
try {
JsonIOUtil.writeTo(barray, idList, idList.cachedSchema(), false);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("will send unsubscribe of .. " + barray.toString());
int id = seqId.incrementAndGet();
//upstreamSubscriptionsBySeqId.put(id, idList);
nettyChannel.writeAndFlush(new TextWebSocketFrame(
new StringBuilder("[").append(WSConstants.PROTOCOL_VERSION)
.append(",").append(WSConstants.MESSAGE_TYPE_REQUEST)
.append(",").append(id)
.append(",")
.append("{\"request\":\"unsubscribe\",\"data\":")
.append(barray.toString()).append("}]").toString()));
}
private void doSubscribeAllCommandHistory() {
System.out.println("will send subscribe-all cmdhist");
int id = seqId.incrementAndGet();
nettyChannel.writeAndFlush(new TextWebSocketFrame(
new StringBuilder("[").append(WSConstants.PROTOCOL_VERSION)
.append(",").append(WSConstants.MESSAGE_TYPE_REQUEST)
.append(",").append(id)
.append(",")
.append("{\"cmdhistory\":\"subscribe\"}]").toString()));
}
NamedObjectList getUpstreamSubscription(int seqId) {
return upstreamSubscriptionsBySeqId.get(seqId);
}
void ackSubscription(int seqId) {
upstreamSubscriptionsBySeqId.remove(seqId);
}
boolean isReconnectionEnabled() {
return enableReconnection.get();
}
public void disconnect() {
if (connected.compareAndSet(true, false)) {
enableReconnection.set(false);
log.info("WebSocket Client sending close");
nettyChannel.writeAndFlush(new CloseWebSocketFrame());
// WebSocketClientHandler will close the channel when the server responds to the CloseWebSocketFrame
nettyChannel.closeFuture().awaitUninterruptibly();
} else {
log.fine("Close requested, but connection was already closed");
}
}
public void shutdown() {
//exec.shutdown();
group.shutdownGracefully();
}
}
|
package com.jaamsim.input;
import java.awt.FileDialog;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.jaamsim.ui.ExceptionBox;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.ui.LogBox;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.FileEntity;
import com.sandwell.JavaSimulation.FileInput;
import com.sandwell.JavaSimulation.Group;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.Input.ParseContext;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.Palette;
import com.sandwell.JavaSimulation.Simulation;
import com.sandwell.JavaSimulation.StringVector;
import com.sandwell.JavaSimulation.Util;
import com.sandwell.JavaSimulation3D.GUIFrame;
public class InputAgent {
private static final String addedRecordMarker = "\" *** Added Records ***";
private static int numErrors = 0;
private static int numWarnings = 0;
private static FileEntity logFile;
private static double lastTimeForTrace;
private static String configFileName; // absolute file path and file name for the present configuration file
private static boolean batchRun;
private static boolean sessionEdited;
private static boolean addedRecordFound; // TRUE if the "added records" marker is found in the configuration file
private static boolean recordEdits;
private static final String INP_ERR_DEFINEUSED = "The name: %s has already been used and is a %s";
private static String reportDirectory;
static {
addedRecordFound = false;
sessionEdited = false;
batchRun = false;
configFileName = null;
reportDirectory = "";
lastTimeForTrace = -1.0d;
}
public static void clear() {
logFile = null;
numErrors = 0;
numWarnings = 0;
addedRecordFound = false;
sessionEdited = false;
configFileName = null;
reportDirectory = "";
lastTimeForTrace = -1.0d;
}
public static String getReportDirectory() {
return reportDirectory;
}
public static void setReportDirectory(String dir) {
reportDirectory = Util.getAbsoluteFilePath(dir);
if (!reportDirectory.substring(reportDirectory.length() - 1).equals("\\"))
reportDirectory = reportDirectory + "\\";
// Create the report directory if it does not already exist
// This code should probably be added to FileEntity someday to
// create necessary folders on demand.
File f = new File(reportDirectory);
f.mkdirs();
}
public static void setConfigFileName(String name) {
configFileName = name;
}
public static String getConfigFileName() {
return configFileName;
}
/**
* if ( fileFullName = "C:\Projects\A01.cfg" ), returns "A01.cfg"
* if ( fileFullName = "A01.cfg" ), returns "A01.cfg"
*/
private static String shortName(String fileFullName) {
int idx = Math.max(fileFullName.lastIndexOf('\\'), fileFullName.lastIndexOf('/'));
// if idx is -1, we return the entire string
return fileFullName.substring(idx + 1);
}
public static String getRunName() {
String runName;
if( InputAgent.getConfigFileName() == null ) {
runName = "";
}
else {
String shortName = shortName(InputAgent.getConfigFileName());
int index = shortName.indexOf( "." );
if( index > -1 ) {
runName = shortName.substring( 0, index );
}
else {
runName = shortName;
}
}
return runName;
}
public static boolean hasAddedRecords() {
return addedRecordFound;
}
public static boolean recordEdits() {
return recordEdits;
}
public static void setRecordEdits(boolean b) {
recordEdits = b;
}
public static boolean isSessionEdited() {
return sessionEdited;
}
public static void setBatch(boolean batch) {
batchRun = batch;
}
public static boolean getBatch() {
return batchRun;
}
/**
* returns true if the first and last tokens are matched braces
**/
public static boolean enclosedByBraces(ArrayList<String> tokens) {
if(tokens.size() < 2 || tokens.indexOf("{") < 0) // no braces
return false;
int level =1;
int i = 1;
for(String each: tokens.subList(1, tokens.size())) {
if(each.equals("{")) {
level++;
}
if(each.equals("}")) {
level
// Matching close brace found
if(level == 0)
break;
}
i++;
}
if(level == 0 && i == tokens.size()-1) {
return true;
}
return false;
}
private static int getBraceDepth(ArrayList<String> tokens, int startingBraceDepth, int startingIndex) {
int braceDepth = startingBraceDepth;
for (int i = startingIndex; i < tokens.size(); i++) {
String token = tokens.get(i);
if (token.equals("{"))
braceDepth++;
if (token.equals("}"))
braceDepth
if (braceDepth < 0) {
InputAgent.logBadInput(tokens, "Extra closing braces found");
tokens.clear();
}
if (braceDepth > 2) {
InputAgent.logBadInput(tokens, "Maximum brace depth (2) exceeded");
tokens.clear();
}
}
return braceDepth;
}
private static URI resRoot;
private static URI resPath;
private static final String res = "/resources/";
static {
try {
// locate the resource folder, and create
resRoot = InputAgent.class.getResource(res).toURI();
}
catch (URISyntaxException e) {}
resPath = URI.create(resRoot.toString());
}
private static void rethrowWrapped(Exception ex) {
StringBuilder causedStack = new StringBuilder();
for (StackTraceElement elm : ex.getStackTrace())
causedStack.append(elm.toString()).append("\n");
throw new InputErrorException("Caught exception: %s", ex.getMessage() + "\n" + causedStack.toString());
}
public static final void readResource(String res) {
if (res == null)
return;
try {
readStream(resRoot.toString(), resPath, res);
GUIFrame.instance().setProgressText(null);
}
catch (URISyntaxException ex) {
rethrowWrapped(ex);
}
}
public static final boolean readStream(String root, URI path, String file) throws URISyntaxException {
String shortName = file.substring(file.lastIndexOf('/') + 1, file.length());
GUIFrame.instance().setProgressText(shortName);
URI resolved = getFileURI(path, file, root);
String resolvedPath = resolved.getSchemeSpecificPart();
String currentDir = resolvedPath.substring(0, resolvedPath.lastIndexOf('/') + 1);
String oldRoot = FileEntity.getRootDirectory();
FileEntity.setRootDirectory(currentDir);
URL url = null;
try {
url = resolved.normalize().toURL();
}
catch (MalformedURLException e) {
rethrowWrapped(e);
}
if (url == null) {
InputAgent.logWarning("Unable to resolve path %s%s - %s", root, path.toString(), file);
return false;
}
BufferedReader buf = null;
try {
InputStream in = url.openStream();
buf = new BufferedReader(new InputStreamReader(in));
} catch (IOException e) {
InputAgent.logWarning("Could not read from %s", url.toString());
return false;
}
try {
ArrayList<String> record = new ArrayList<String>();
int braceDepth = 0;
Input.ParseContext pc = new Input.ParseContext();
pc.jail = root;
pc.context = path;
while (true) {
String line = buf.readLine();
// end of file, stop reading
if (line == null)
break;
if ( line.trim().equalsIgnoreCase( addedRecordMarker ) ) {
addedRecordFound = true;
}
int previousRecordSize = record.size();
Parser.tokenize(record, line, true);
braceDepth = InputAgent.getBraceDepth(record, braceDepth, previousRecordSize);
if( braceDepth != 0 )
continue;
if (record.size() == 0)
continue;
InputAgent.echoInputRecord(record);
if ("DEFINE".equalsIgnoreCase(record.get(0))) {
InputAgent.processDefineRecord(record);
record.clear();
continue;
}
if ("INCLUDE".equalsIgnoreCase(record.get(0))) {
try {
InputAgent.processIncludeRecord(pc.jail, resolved, record);
}
catch (URISyntaxException ex) {
rethrowWrapped(ex);
}
record.clear();
continue;
}
// Otherwise assume it is a Keyword record
InputAgent.processKeywordRecord(record, pc);
record.clear();
}
// Leftover Input at end of file
if (record.size() > 0)
InputAgent.logBadInput(record, "Leftover input at end of file");
buf.close();
}
catch (IOException e) {
// Make best effort to ensure it closes
try { buf.close(); } catch (IOException e2) {}
}
FileEntity.setRootDirectory(oldRoot);
return true;
}
private static void processIncludeRecord(String root, URI path, ArrayList<String> record) throws URISyntaxException {
if (record.size() != 2) {
InputAgent.logError("Bad Include record, should be: Include <File>");
return;
}
InputAgent.readStream(root, path, record.get(1).replaceAll("\\\\", "/"));
}
private static void processDefineRecord(ArrayList<String> record) {
if (record.size() < 5 ||
!record.get(2).equals("{") ||
!record.get(record.size() - 1).equals("}")) {
InputAgent.logError("Bad Define record, should be: Define <Type> { <names>... }");
return;
}
Class<? extends Entity> proto = null;
try {
if( record.get( 1 ).equalsIgnoreCase( "Palette" ) ) {
proto = Palette.class;
}
else if( record.get( 1 ).equalsIgnoreCase( "ObjectType" ) ) {
proto = ObjectType.class;
}
else {
proto = Input.parseEntityType(record.get(1));
}
}
catch (InputErrorException e) {
InputAgent.logError("%s", e.getMessage());
return;
}
// Loop over all the new Entity names
for (int i = 3; i < record.size() - 1; i++) {
InputAgent.defineEntity(proto, record.get(i), addedRecordFound);
}
}
/**
* Like defineEntity(), but will generate a unique name if a name collision exists
* @param proto
* @param key
* @param addedEntity
* @return
*/
public static <T extends Entity> T defineEntityWithUniqueName(Class<T> proto, String key, boolean addedEntity) {
// Has the provided name been used already?
if (Entity.getNamedEntity(key) == null) {
return defineEntity(proto, key, addedEntity);
}
// Try the provided name plus "-1", "-2", etc. until an unused name is found
int entityNum = 1;
while(true) {
String name = String.format("%s-%d", key, entityNum);
if (Entity.getNamedEntity(name) == null) {
return defineEntity(proto, name, addedEntity);
}
entityNum++;
}
}
/**
* if addedEntity is true then this is an entity defined
* by user interaction or after added record flag is found;
* otherwise, it is from an input file define statement
* before the model is configured
* @param proto
* @param key
* @param addedEntity
*/
public static <T extends Entity> T defineEntity(Class<T> proto, String key, boolean addedEntity) {
Entity existingEnt = Input.tryParseEntity(key, Entity.class);
if (existingEnt != null) {
InputAgent.logError(INP_ERR_DEFINEUSED, key, existingEnt.getClass().getSimpleName());
return null;
}
T ent = null;
try {
ent = proto.newInstance();
if (addedEntity) {
ent.setFlag(Entity.FLAG_ADDED);
sessionEdited = true;
}
}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
finally {
if (ent == null) {
InputAgent.logError("Could not create new Entity: %s", key);
return null;
}
}
ent.setInputName(key);
return ent;
}
public static void processKeywordRecord(ArrayList<String> record, Input.ParseContext context) {
Entity ent = Input.tryParseEntity(record.get(0), Entity.class);
if (ent == null) {
InputAgent.logError("Could not find Entity: %s", record.get(0));
return;
}
// Validate the tokens have the Entity Keyword { Args... } Keyword { Args... }
ArrayList<KeywordIndex> words = InputAgent.getKeywords(record, context);
for (KeywordIndex keyword : words) {
try {
InputAgent.processKeyword(ent, keyword);
}
catch (Throwable e) {
InputAgent.logInpError("Entity: %s, Keyword: %s - %s", ent.getInputName(), keyword.keyword, e.getMessage());
}
}
}
public static class KeywordIndex {
public final ArrayList<String> input;
public final String keyword;
public final int start;
public final int end;
public final ParseContext context;
public KeywordIndex(ArrayList<String> inp, int s, int e, ParseContext ctxt) {
input = inp;
keyword = input.get(s);
start = s;
end = e;
context = ctxt;
}
}
private static ArrayList<KeywordIndex> getKeywords(ArrayList<String> input, ParseContext context) {
ArrayList<KeywordIndex> ret = new ArrayList<KeywordIndex>();
int braceDepth = 0;
int index = 1;
for (int i = 1; i < input.size(); i++) {
String tok = input.get(i);
if ("{".equals(tok)) {
braceDepth++;
continue;
}
if ("}".equals(tok)) {
braceDepth
if (braceDepth == 0) {
ret.add(new KeywordIndex(input, index, i, context));
index = i + 1;
continue;
}
}
}
// Look for a leftover keyword at the end of line
KeywordIndex last = ret.get(ret.size() - 1);
if (last.end != input.size() - 1) {
ret.add(new KeywordIndex(input, last.end + 1, input.size() - 1, context));
}
for (KeywordIndex kw : ret) {
if (!"{".equals(input.get(kw.start + 1)) ||
!"}".equals(input.get(kw.end))) {
throw new InputErrorException("Keyword %s not valid, should be <keyword> { <args> }", kw.keyword);
}
}
return ret;
}
public static void doError(Throwable e) {
if (!batchRun)
return;
LogBox.logLine("An error occurred in the simulation environment. Please check inputs for an error:");
LogBox.logLine(e.toString());
GUIFrame.shutdown(1);
}
// Load the run file
public static void loadConfigurationFile( String fileName) throws URISyntaxException {
String inputTraceFileName = InputAgent.getRunName() + ".log";
// Initializing the tracing for the model
try {
System.out.println( "Creating trace file" );
URI confURI = new File(fileName).toURI();
URI logURI = confURI.resolve(new URI(null, inputTraceFileName, null)); // The new URI here effectively escapes the file name
// Set and open the input trace file name
logFile = new FileEntity( logURI.getPath(), FileEntity.FILE_WRITE, false );
}
catch( Exception e ) {
InputAgent.logWarning("Could not create trace file");
}
InputAgent.loadConfigurationFile(fileName, true);
// At this point configuration file is loaded
// The session is not considered to be edited after loading a configuration file
sessionEdited = false;
// Save and close the input trace file
if (logFile != null) {
if (InputAgent.numWarnings == 0 && InputAgent.numErrors == 0) {
logFile.close();
logFile.delete();
logFile = new FileEntity( inputTraceFileName, FileEntity.FILE_WRITE, false );
}
}
// Check for found errors
if( InputAgent.numErrors > 0 )
throw new InputErrorException("%d input errors and %d warnings found, check %s", InputAgent.numErrors, InputAgent.numWarnings, inputTraceFileName);
if (Simulation.getPrintInputReport())
InputAgent.printInputFileKeywords();
}
/**
*
* @param fileName
* @param firstTime ( true => this is the main config file (run file); false => this is an included file within main config file or another included file )
*/
public static void loadConfigurationFile( String rawFileName, boolean firstTime ) throws URISyntaxException {
URI fileURI = new File(rawFileName).toURI();
String path = fileURI.getPath();
String dir = path.substring(0, path.lastIndexOf('/')+1);
URI dirURI = new URI("file", dir, null);
String fileName = path.substring(path.lastIndexOf('/') + 1, path.length());
readStream("", dirURI, fileName);
FileEntity.setRootDirectory(dir);
GUIFrame.instance().setProgressText(null);
GUIFrame.instance().setProgress(0);
}
public static final void apply(Entity ent, KeywordIndex kw) {
Input<?> in = ent.getInput(kw.keyword);
if (in == null) {
InputAgent.logWarning("Keyword %s could not be found for Entity %s.", kw.keyword, ent.getInputName());
return;
}
InputAgent.apply(ent, in, kw);
FrameBox.valueUpdate();
}
public static final void apply(Entity ent, Input<?> in, KeywordIndex kw) {
StringVector data = new StringVector(kw.end - kw.start);
for (int i = kw.start + 2; i < kw.end; i++) {
data.add(kw.input.get(i));
}
in.parse(data, kw.context);
// Only mark the keyword edited if we have finished initial configuration
if (InputAgent.hasAddedRecords() || InputAgent.recordEdits())
in.setEdited(true);
ent.updateForInput(in);
if(ent.testFlag(Entity.FLAG_GENERATED))
return;
StringBuilder out = new StringBuilder(data.size() * 6);
for (int i = 0; i < data.size(); i++) {
String dat = data.get(i);
if (Parser.needsQuoting(dat) && !dat.equals("{") && !dat.equals("}"))
out.append("'").append(dat).append("'");
else
out.append(dat);
if( i < data.size() - 1 )
out.append(" ");
}
if(in.isEdited()) {
ent.setFlag(Entity.FLAG_EDITED);
sessionEdited = true;
}
in.setValueString(out.toString());
}
private static void processKeyword(Entity entity, KeywordIndex key) {
if (entity.testFlag(Entity.FLAG_LOCKED))
throw new InputErrorException("Entity: %s is locked and cannot be modified", entity.getName());
Input<?> input = entity.getInput( key.keyword );
if (input != null) {
InputAgent.apply(entity, input, key);
FrameBox.valueUpdate();
return;
}
if (!(entity instanceof Group))
throw new InputErrorException("Not a valid keyword");
Group grp = (Group)entity;
grp.saveGroupKeyword(key);
// Store the keyword data for use in the edit table
for( int i = 0; i < grp.getList().size(); i++ ) {
Entity ent = grp.getList().get( i );
InputAgent.apply(ent, key);
}
}
private static class ConfigFileFilter implements FilenameFilter {
@Override
public boolean accept(File inFile, String fileName) {
return fileName.endsWith("[cC][fF][gG]");
}
}
public static void load(GUIFrame gui) {
LogBox.logLine("Loading...");
FileDialog chooser = new FileDialog(gui, "Load Configuration File", FileDialog.LOAD);
chooser.setFilenameFilter(new ConfigFileFilter());
chooser.setFile("*.cfg");
chooser.setVisible(true); // display the dialog, waits for selection
String file = chooser.getFile();
if (file == null)
return;
String absFile = chooser.getDirectory() + file;
absFile = absFile.trim();
setLoadFile(gui, absFile);
}
public static void save(GUIFrame gui) {
LogBox.logLine("Saving...");
if( InputAgent.getConfigFileName() != null ) {
setSaveFile(gui, InputAgent.getConfigFileName() );
}
else {
saveAs( gui );
}
}
public static void saveAs(GUIFrame gui) {
LogBox.logLine("Save As...");
FileDialog chooser = new FileDialog(gui, "Save Configuration File As", FileDialog.SAVE);
chooser.setFilenameFilter(new ConfigFileFilter());
chooser.setFile(InputAgent.getConfigFileName());
// Display the dialog and wait for selection
chooser.setVisible(true);
String file = chooser.getFile();
if (file == null)
return;
String absFile = chooser.getDirectory() + file;
// Compensate for an error in FileDialog under Java 7:
// - If the new name is shorter than the old name, then the method getDirectory() returns the absolute path and
// the file name. The method getFile() returns a corrupted version of the old file name.
// - If the new name is the same length or longer than the new name then both methods work properly.
// Expected to be fixed in Java 8.
if( System.getProperty("java.version").startsWith("1.7.") )
if( absFile.length() < InputAgent.getConfigFileName().length() ) // If corrupted, the new absolute file name is one character shorter than the old absolute file name
absFile = chooser.getDirectory();
// Add the file extension ".cfg" if needed
absFile = absFile.trim();
if( ! absFile.endsWith(".cfg") )
absFile = absFile.concat(".cfg");
// Save the configuration file
setSaveFile(gui, absFile);
}
public static void configure(GUIFrame gui, String configFileName) {
try {
gui.clear();
InputAgent.setConfigFileName(configFileName);
gui.updateForSimulationState(GUIFrame.SIM_STATE_UNCONFIGURED);
try {
InputAgent.loadConfigurationFile(configFileName);
}
catch( InputErrorException iee ) {
if (!batchRun)
ExceptionBox.instance().setErrorBox(iee.getMessage());
else
LogBox.logLine( iee.getMessage() );
}
LogBox.logLine("Configuration File Loaded");
// show the present state in the user interface
gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() );
gui.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED);
gui.enableSave(addedRecordFound);
}
catch( Throwable t ) {
ExceptionBox.instance().setError(t);
}
}
/**
* Loads configuration file , calls GraphicSimulation.configure() method
*/
private static void setLoadFile(final GUIFrame gui, String fileName) {
final String chosenFileName = fileName;
new Thread(new Runnable() {
@Override
public void run() {
File temp = new File(chosenFileName);
if( temp.isAbsolute() ) {
InputAgent.setRecordEdits(false);
InputAgent.configure(gui, chosenFileName);
InputAgent.setRecordEdits(true);
}
else {
System.out.printf("Error: loading a relative file: %s\n", chosenFileName);
}
GUIFrame.displayWindows(true);
FrameBox.valueUpdate();
}
}).start();
}
/**
* Saves the configuration file.
* @param gui = Control Panel window for JaamSim
* @param fileName = absolute file path and file name for the file to be saved
*/
private static void setSaveFile(GUIFrame gui, String fileName) {
// Set root directory
File temp = new File(fileName);
FileEntity.setRootDirectory( temp.getParentFile() );
// Save the configuration file
InputAgent.printNewConfigurationFileWithName( fileName );
sessionEdited = false;
InputAgent.setConfigFileName(fileName);
// Set the title bar to match the new run name
gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() );
}
/*
* write input file keywords and values
*
* input file format:
* Define Group { <Group names> }
* Define <Object> { <Object names> }
*
* <Object name> <Keyword> { < values > }
*
*/
public static void printInputFileKeywords() {
// Create report file for the inputs
FileEntity inputReportFile;
String inputReportFileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + ".inp";
if( FileEntity.fileExists( inputReportFileName ) ) {
inputReportFile = new FileEntity( inputReportFileName, FileEntity.FILE_WRITE, false );
inputReportFile.flush();
}
else
{
inputReportFile = new FileEntity( inputReportFileName, FileEntity.FILE_WRITE, false );
}
// Loop through the entity classes printing Define statements
for (ObjectType type : ObjectType.getAll()) {
Class<? extends Entity> each = type.getJavaClass();
// Loop through the instances for this entity class
int count = 0;
for (Entity ent : Entity.getInstanceIterator(each)) {
boolean hasinput = false;
for (Input<?> in : ent.getEditableInputs()) {
// If the keyword has been used, then add a record to the report
if (in.getValueString().length() != 0) {
hasinput = true;
count++;
break;
}
}
if (hasinput) {
String entityName = ent.getInputName();
if ((count - 1) % 5 == 0) {
inputReportFile.putString("Define");
inputReportFile.putTab();
inputReportFile.putString(type.getInputName());
inputReportFile.putTab();
inputReportFile.putString("{ " + entityName);
inputReportFile.putTab();
}
else if ((count - 1) % 5 == 4) {
inputReportFile.putString(entityName + " }");
inputReportFile.newLine();
}
else {
inputReportFile.putString(entityName);
inputReportFile.putTab();
}
}
}
if (!Entity.getInstanceIterator(each).hasNext()) {
if (count % 5 != 0) {
inputReportFile.putString(" }");
inputReportFile.newLine();
}
inputReportFile.newLine();
}
}
for (ObjectType type : ObjectType.getAll()) {
Class<? extends Entity> each = type.getJavaClass();
// Get the list of instances for this entity class
// sort the list alphabetically
ArrayList<? extends Entity> cloneList = Entity.getInstancesOf(each);
// Print the entity class name to the report (in the form of a comment)
if (cloneList.size() > 0) {
inputReportFile.putString("\" " + each.getSimpleName() + " \"");
inputReportFile.newLine();
inputReportFile.newLine(); // blank line below the class name heading
}
Collections.sort(cloneList, new Comparator<Entity>() {
@Override
public int compare(Entity a, Entity b) {
return a.getInputName().compareTo(b.getInputName());
}
});
// Loop through the instances for this entity class
for (int j = 0; j < cloneList.size(); j++) {
// Make sure the clone is an instance of the class (and not an instance of a subclass)
if (cloneList.get(j).getClass() == each) {
Entity ent = cloneList.get(j);
String entityName = ent.getInputName();
boolean hasinput = false;
// Loop through the editable keywords for this instance
for (Input<?> in : ent.getEditableInputs()) {
// If the keyword has been used, then add a record to the report
if (in.getValueString().length() != 0) {
if (!in.getCategory().contains("Graphics")) {
hasinput = true;
inputReportFile.putTab();
inputReportFile.putString(entityName);
inputReportFile.putTab();
inputReportFile.putString(in.getKeyword());
inputReportFile.putTab();
if (in.getValueString().lastIndexOf("{") > 10) {
String[] item1Array;
item1Array = in.getValueString().trim().split(" }");
inputReportFile.putString("{ " + item1Array[0] + " }");
for (int l = 1; l < (item1Array.length); l++) {
inputReportFile.newLine();
inputReportFile.putTabs(5);
inputReportFile.putString(item1Array[l] + " } ");
}
inputReportFile.putString(" }");
}
else {
inputReportFile.putString("{ " + in.getValueString() + " }");
}
inputReportFile.newLine();
}
}
}
// Put a blank line after each instance
if (hasinput) {
inputReportFile.newLine();
}
}
}
}
// Close out the report
inputReportFile.flush();
inputReportFile.close();
}
public static void closeLogFile() {
if (logFile == null)
return;
logFile.flush();
logFile.close();
if (numErrors ==0 && numWarnings == 0) {
logFile.delete();
}
logFile = null;
}
private static final String errPrefix = "*** ERROR *** %s%n";
private static final String inpErrPrefix = "*** INPUT ERROR *** %s%n";
private static final String wrnPrefix = "***WARNING*** %s%n";
public static int numErrors() {
return numErrors;
}
public static int numWarnings() {
return numWarnings;
}
private static void echoInputRecord(ArrayList<String> tokens) {
if (logFile == null)
return;
StringBuilder line = new StringBuilder();
for (int i = 0; i < tokens.size(); i++) {
line.append(" ").append(tokens.get(i));
if (tokens.get(i).startsWith("\"")) {
logFile.write(line.toString());
logFile.newLine();
line.setLength(0);
}
}
// Leftover input
if (line.length() > 0) {
logFile.write(line.toString());
logFile.newLine();
}
logFile.flush();
}
private static void logBadInput(ArrayList<String> tokens, String msg) {
InputAgent.echoInputRecord(tokens);
InputAgent.logError("%s", msg);
}
public static void logMessage(String fmt, Object... args) {
String msg = String.format(fmt, args);
System.out.println(msg);
if (logFile == null)
return;
logFile.write(msg);
logFile.newLine();
logFile.flush();
}
public static void trace(int indent, Entity ent, String meth, String... text) {
// Create an indent string to space the lines
StringBuilder ind = new StringBuilder("");
for (int i = 0; i < indent; i++)
ind.append(" ");
String spacer = ind.toString();
// Print a TIME header every time time has advanced
double traceTime = ent.getCurrentTime();
if (lastTimeForTrace != traceTime) {
System.out.format(" \nTIME = %.5f\n", traceTime);
lastTimeForTrace = traceTime;
}
// Output the traces line(s)
System.out.format("%s%s %s\n", spacer, ent.getName(), meth);
for (String line : text) {
System.out.format("%s%s\n", spacer, line);
}
System.out.flush();
}
public static void logWarning(String fmt, Object... args) {
numWarnings++;
String msg = String.format(fmt, args);
InputAgent.logMessage(wrnPrefix, msg);
}
public static void logError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(errPrefix, msg);
}
public static void logInpError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(inpErrPrefix, msg);
}
public static void processEntity_Keyword_Value(Entity ent, Input<?> in, String value){
ArrayList<String> tokens = new ArrayList<String>();
tokens.add(in.getKeyword());
tokens.add("{");
Parser.tokenize(tokens, value, true);
tokens.add("}");
KeywordIndex kw = new KeywordIndex(tokens, 0, tokens.size() - 1, null);
InputAgent.processKeyword(ent, kw);
}
public static void processEntity_Keyword_Value(Entity ent, String keyword, String value){
ArrayList<String> tokens = new ArrayList<String>();
tokens.add(keyword);
tokens.add("{");
Parser.tokenize(tokens, value, true);
tokens.add("}");
KeywordIndex kw = new KeywordIndex(tokens, 0, tokens.size() - 1, null);
InputAgent.processKeyword(ent, kw);
}
/**
* Print out a configuration file with all the edited changes attached
*/
public static void printNewConfigurationFileWithName( String fileName ) {
ArrayList<String> preAddedRecordLines = new ArrayList<String>();
String configFilePath = FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName();
if( InputAgent.hasAddedRecords() && FileEntity.fileExists( configFilePath ) ) {
// Store the original configuration file lines up to added records
try {
BufferedReader in = new BufferedReader( new FileReader( configFilePath ) );
String line;
while ( ( line = in.readLine() ) != null ) {
if ( line.startsWith( addedRecordMarker ) ) {
break;
}
else {
preAddedRecordLines.add( line );
}
}
in.close();
}
catch ( Exception e ) {
throw new ErrorException( e );
}
}
FileEntity file = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
// include the original configuration file
if (!InputAgent.hasAddedRecords()) {
file.format( "\" File: %s%n%n", file.getFileName() );
file.format( "include %s%n%n", InputAgent.getConfigFileName() );
}
else {
for( int i=0; i < preAddedRecordLines.size(); i++ ) {
String line = preAddedRecordLines.get( i );
if( line.startsWith( "\" File: " ) ) {
file.format( "\" File: %s%n", file.getFileName() );
}
else {
file.format("%s%n", line);
}
}
}
file.format("%s%n", addedRecordMarker);
addedRecordFound = true;
// Determine all the new classes that were created
ArrayList<Class<? extends Entity>> newClasses = new ArrayList<Class<? extends Entity>>();
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_ADDED))
continue;
if (!newClasses.contains(ent.getClass()))
newClasses.add(ent.getClass());
}
// Print the define statements for each new class
for( Class<? extends Entity> newClass : newClasses ) {
for (ObjectType o : ObjectType.getAll()) {
if (o.getJavaClass() == newClass) {
file.format("Define %s {", o.getInputName());
break;
}
}
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_ADDED))
continue;
if (ent.getClass() == newClass)
file.format(" %s ", ent.getInputName());
}
file.format("}%n");
}
// List all the changes that were saved for each edited entity
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_EDITED))
continue;
writeInputsOnFile_ForEntity( file, ent );
}
file.flush();
file.close();
}
static void writeInputsOnFile_ForEntity( FileEntity file, Entity ent ) {
// Write new configuration file for non-appendable keywords
file.format("\n");
for( int j=0; j < ent.getEditableInputs().size(); j++ ) {
Input<?> in = ent.getEditableInputs().get( j );
if (!in.isEdited())
continue;
if (in instanceof FileInput) {
writeFileInput((FileInput)in, file, ent);
continue;
}
String value = in.getValueString();
ArrayList<String> tokens = new ArrayList<String>();
Parser.tokenize(tokens, value);
if (!InputAgent.enclosedByBraces(tokens))
file.format("%s %s { %s }%n", ent.getInputName(), in.getKeyword(), value);
else
file.format("%s %s %s%n", ent.getInputName(), in.getKeyword(), value);
}
}
static private void writeFileInput(FileInput in, FileEntity file, Entity ent) {
URI fileURI = file.getFileURI();
URI inputURI = in.getValue();
String resString = resRoot.toString();
String inputString = inputURI.toString();
// Check if this is a resource
if (inputString.indexOf(resString) == 0) {
file.format("%s %s { '<res>/%s' }%n", ent.getInputName(), in.getKeyword(), inputString.substring(resString.length()));
return;
}
// Try to relativize this URL to the current file
try {
String filePath = fileURI.getPath();
URI dirURI = new URI(fileURI.getScheme(), filePath.substring(0, filePath.lastIndexOf('/') + 1), null);
inputURI = dirURI.relativize(inputURI);
} catch (Exception ex) {
// We failed, just spit out an absolute URI
}
file.format("%s %s { '%s' }%n", ent.getInputName(), in.getKeyword(), inputURI.getPath());
}
public static void loadDefault() {
// Read the default configuration file
InputAgent.readResource("inputs/default.cfg");
sessionEdited = false;
}
/**
* Split an input (list of strings) down to a single level of nested braces, this may then be called again for
* further nesting.
* @param input
* @return
*/
public static ArrayList<ArrayList<String>> splitForNestedBraces(List<String> input) {
ArrayList<ArrayList<String>> inputs = new ArrayList<ArrayList<String>>();
int braceDepth = 0;
ArrayList<String> currentLine = null;
for (int i = 0; i < input.size(); i++) {
if (currentLine == null)
currentLine = new ArrayList<String>();
currentLine.add(input.get(i));
if (input.get(i).equals("{")) {
braceDepth++;
continue;
}
if (input.get(i).equals("}")) {
braceDepth
if (braceDepth == 0) {
inputs.add(currentLine);
currentLine = null;
continue;
}
}
}
return inputs;
}
/**
* This is the heart of path handling, find a file relative to a root 'context' and then check that
* the normalized URI matches the jail prefix, otherwise reject it
* @param context
* @param path
* @param jailPrefix
* @return
*/
public static URI getFileURI(URI context, String path, String jailPrefix) throws URISyntaxException {
int openBrace = path.indexOf('<');
int closeBrace = path.indexOf('>');
int firstSlash = path.indexOf('/');
URI ret = null;
if (openBrace == 0 && closeBrace != -1 && firstSlash == closeBrace + 1) {
// Special path format, expand the resource
String specPath = path.substring(openBrace + 1, closeBrace);
if (specPath.equals("res")) {
ret = new URI(resRoot.getScheme(), resRoot.getSchemeSpecificPart() + path.substring(closeBrace+2), null).normalize();
}
} else {
URI pathURI = new URI(null, path, null).normalize();
if (context != null) {
if (context.isOpaque()) {
// Things are going to get messy in here
URI schemeless = new URI(null, context.getSchemeSpecificPart(), null);
URI resolved = schemeless.resolve(pathURI).normalize();
// Note: we are using the one argument constructor here because the 'resolved' URI is already encoded
// and we do not want to double-encode (and schemes should never need encoding, I hope)
ret = new URI(context.getScheme() + ":" + resolved.toString());
} else {
ret = context.resolve(pathURI).normalize();
}
} else {
// We have no context, so append a 'file' scheme if necessary
if (pathURI.getScheme() == null) {
ret = new URI("file", pathURI.getPath(), null);
} else {
ret = pathURI;
}
}
}
if (jailPrefix != null && ret.toString().indexOf(jailPrefix) != 0) {
System.out.printf("Failed jail test: %s in jail: %s context: %s\n", ret.toString(), jailPrefix, context.toString());
return null; // This resolved URI is not in our jail
}
return ret;
}
}
|
package org.apache.jmeter.control;
import java.io.Serializable;
import org.apache.jmeter.samplers.AbstractSampler;
//import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.testelement.PerSampleClonable;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.BooleanProperty;
import org.apache.jmeter.testelement.property.IntegerProperty;
import org.apache.jmeter.testelement.property.StringProperty;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
public class LoopController extends GenericController implements Serializable
{
private static Logger log = LoggingManager.getLoggerFor(JMeterUtils.ELEMENTS);
private final static String LOOPS = "LoopController.loops";
private final static String CONTINUE_FOREVER = "LoopController.continue_forever";
private int loopCount = 0;
public LoopController()
{
setContinueForever(true);
}
public void setLoops(int loops)
{
setProperty(new IntegerProperty(LOOPS,loops));
}
public void setLoops(String loopValue)
{
setProperty(new StringProperty(LOOPS,loopValue));
}
public int getLoops()
{
return getPropertyAsInt(LOOPS);
}
public void setContinueForever(boolean forever)
{
setProperty(new BooleanProperty(CONTINUE_FOREVER,forever));
}
public boolean getContinueForever()
{
return getPropertyAsBoolean(CONTINUE_FOREVER);
}
public void initialize()
{
super.initialize();
resetLoopCount();
}
public void reInitialize()
{
super.reInitialize();
resetLoopCount();
}
protected void incrementLoopCount()
{
loopCount++;
}
protected void resetLoopCount()
{
if(!getContinueForever() && getLoops() > -1)
{
this.setShortCircuit(true);
}
else
{
loopCount = 0;
}
}
public boolean hasNext()
{
if (getLoops()!=0)
{
return super.hasNext();
}
else
{
return false;
}
}
protected boolean hasNextAtEnd()
{
resetCurrent();
incrementLoopCount();
if(endOfLoop())
{
return false;
}
else
{
return hasNext();
}
}
/* public Sampler next() {
if ((!getContinueForever() && getLoops()>0) || getContinueForever())
{
return super.next();
}
else
{
return null;
}
}*/
public boolean isDone() {
if (getLoops()!=0)
{
return super.isDone();
}
else
{
return true;
}
}
protected void nextAtEnd()
{
resetCurrent();
incrementLoopCount();
}
private boolean endOfLoop()
{
return (!getContinueForever() || getLoops() > -1) && loopCount >= getLoops();
}
public static class Test extends junit.framework.TestCase
{
public Test(String name)
{
super(name);
}
public void testProcessing() throws Exception
{
GenericController controller = new GenericController();
GenericController sub_1 = new GenericController();
sub_1.addTestElement(makeSampler("one"));
sub_1.addTestElement(makeSampler("two"));
controller.addTestElement(sub_1);
controller.addTestElement(makeSampler("three"));
LoopController sub_2 = new LoopController();
sub_2.setLoops(3);
GenericController sub_3 = new GenericController();
sub_2.addTestElement(makeSampler("four"));
sub_3.addTestElement(makeSampler("five"));
sub_3.addTestElement(makeSampler("six"));
sub_2.addTestElement(sub_3);
sub_2.addTestElement(makeSampler("seven"));
controller.addTestElement(sub_2);
String[] order = new String[]{"one","two","three","four","five","six","seven",
"four","five","six","seven","four","five","six","seven"};
int counter = 15;
for (int i = 0; i < 2; i++)
{
assertEquals(15,counter);
counter = 0;
while(controller.hasNext())
{
TestElement sampler = controller.next();
assertEquals(order[counter++],sampler.getPropertyAsString(TestElement.NAME));
}
}
}
private TestElement makeSampler(String name)
{
TestSampler s= new TestSampler();
s.setName(name);
return s;
}
class TestSampler extends AbstractSampler implements PerSampleClonable {
public void addCustomTestElement(TestElement t) { }
public org.apache.jmeter.samplers.SampleResult sample(org.apache.jmeter.samplers.Entry e) { return null; }
}
}
}
|
package com.hubspot.baragon.service.edgecache.cloudflare.client.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties( ignoreUnknown = true )
public class CloudflarePurgeCacheResult {
private final String id;
@JsonCreator
public CloudflarePurgeCacheResult(@JsonProperty("id") String id) {
this.id = id;
}
public String getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CloudflarePurgeCacheResult that = (CloudflarePurgeCacheResult) o;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public String toString() {
return "CloudflarePurgeCacheResult{" +
"id='" + id + '\'' +
'}';
}
}
|
package com.udacity.gamedev.fallingobjects;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.viewport.Viewport;
import java.util.Random;
public class Boulder {
private static final float RADIUS_RATIO = 0.01f;
private static final Color COLOR = Color.RED;
// Declare a constant holding the acceleration due to gravity. -20 works well
private static final float GRAVITY = 20;
private static final float WIND_SPEED = 3;
Vector2 position;
Vector2 velocity;
float radius;
public Boulder(Viewport viewport){
init(viewport);
}
public void init(Viewport viewport){
position = new Vector2();
// Set the initial velocity to zero in both directions
velocity = new Vector2(0, 0);
radius = viewport.getWorldWidth() * RADIUS_RATIO;
position.y = viewport.getWorldHeight() + radius;
Random random = new Random();
position.x = random.nextFloat() * (viewport.getWorldWidth() - 2 * radius) + radius;
}
public void update(float delta){
// Apply gravitational acceleration to the vertical velocity
velocity.y -= GRAVITY;
velocity.x += WIND_SPEED;
position.x += delta * velocity.x;
position.y += delta * velocity.y;
}
public boolean isBelowScreen(){
return position.y < -radius;
}
public void render(ShapeRenderer renderer){
renderer.set(ShapeType.Filled);
renderer.setColor(COLOR);
renderer.circle(position.x, position.y, radius);
}
// TODO: Challenge - Add wind blowing from the side
}
|
package com.jcabi.log;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Convenient {@link ThreadFactory}, that logs all uncaught exceptions.
*
* <p>It's a wrapper around
* {@link Executors#defaultThreadFactory()}. The factory should be used together
* with executor services from {@code java.util.concurrent} package. Without
* these "verbose" threads your runnable tasks will not report anything to
* console once they die because of a runtime exception, for example:
*
* <pre>
* Executors.newScheduledThreadPool(2).scheduleAtFixedRate(
* new Runnable() {
* @Override
* public void run() {
* // some sensitive operation that may throw
* // a runtime exception
* },
* 1L, 1L, TimeUnit.SECONDS
* }
* );
* </pre>
*
* <p>The exception in this example will never be caught by nobody. It will
* just terminate current execution of the {@link Runnable} task. Moreover,
* it won't reach any {@link Thread.UncaughtExceptionHandler}, because this
* is how {@link ScheduledExecutorService} is behaving. This is how we solve
* the problem with {@link VerboseThreads}:
*
* <pre>
* ThreadFactory factory = new VerboseThreads();
* Executors.newScheduledThreadPool(2, factory).scheduleAtFixedRate(
* new Runnable() {
* @Override
* public void run() {
* // the same sensitive operation that may throw
* // a runtime exception
* },
* 1L, 1L, TimeUnit.SECONDS
* }
* );
* </pre>
*
* <p>Now, every runtime exception that is not caught inside your
* {@link Runnable} will be reported to log (using {@link Logger}).
*
* <p>This class is thread-safe.
*
* @author Yegor Bugayenko (yegor@jcabi.com)
* @version $Id$
* @since 0.1.2
*/
@SuppressWarnings("PMD.DoNotUseThreads")
public final class VerboseThreads implements ThreadFactory {
/**
* Thread group.
*/
private final transient ThreadGroup group;
/**
* Prefix to use.
*/
private final transient String prefix;
/**
* Number of the next thread to create.
*/
private final transient AtomicInteger number = new AtomicInteger(1);
/**
* Create threads as daemons?
*/
private final transient boolean daemon;
/**
* Default thread priority.
*/
private final transient int priority;
/**
* Default constructor ({@code "verbose"} as a prefix, threads are daemons,
* default thread priority is {@code 1}).
*/
public VerboseThreads() {
this("verbose", true, 1);
}
/**
* Detailed constructor, with a prefix of thread names (threads are daemons,
* default thread priority is {@code 1}).
* @param pfx Prefix for thread names
*/
public VerboseThreads(final String pfx) {
this(pfx, true, 1);
}
/**
* Detailed constructor, with a prefix of thread names (threads are daemons,
* default thread priority is {@code 1}).
* @param type Prefix will be build from this type name
*/
public VerboseThreads(final Object type) {
this(type.getClass().getSimpleName(), true, 1);
}
/**
* Detailed constructor, with a prefix of thread names (threads are daemons,
* default thread priority is {@code 1}).
* @param type Prefix will be build from this type name
*/
public VerboseThreads(final Class<?> type) {
this(type.getSimpleName(), true, 1);
}
/**
* Detailed constructor.
* @param pfx Prefix for thread names
* @param dmn Threads should be daemons?
* @param prt Default priority for all threads
*/
public VerboseThreads(final String pfx, final boolean dmn, final int prt) {
this.prefix = pfx;
this.daemon = dmn;
this.priority = prt;
this.group = new ThreadGroup(pfx) {
@Override
public void uncaughtException(final Thread thread,
final Throwable throwable) {
Logger.warn(this, "%[exception]s", throwable);
}
};
}
/**
* {@inheritDoc}
*/
@Override
public Thread newThread(final Runnable runnable) {
final Thread thread = new Thread(
this.group,
// @checkstyle AnonInnerLength (50 lines)
new Runnable() {
@Override
@SuppressWarnings("PMD.AvoidCatchingGenericException")
public void run() {
try {
runnable.run();
} catch (RuntimeException ex) {
Logger.warn(
this,
"%s: %[exception]s",
Thread.currentThread().getName(),
ex
);
throw ex;
} catch (Error error) {
Logger.error(
this,
"%s (error): %[exception]s",
Thread.currentThread().getName(),
error
);
throw error;
}
}
}
);
thread.setName(
String.format(
"%s-%d",
this.prefix,
this.number.getAndIncrement()
)
);
thread.setDaemon(this.daemon);
thread.setPriority(this.priority);
return thread;
}
}
|
package com.example.android.milestone.fragments;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.backendless.Backendless;
import com.backendless.BackendlessUser;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.example.android.bluetoothlegatt.R;
import com.example.android.milestone.MenuActivity;
import com.example.android.milestone.adapters.ContactAdapter2;
import com.example.android.milestone.models.Contact;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.L;
public class ContactFragment2 extends Fragment implements AddContact.ContactListener {
ArrayList<Contact> contacts;//Listes des contacts a afficher
ContactAdapter2 c_Adapter;//Adapteur gerant la liste des conacts
ListView lvContact;//Objet view qui va afficher les contacts
Contact contact;
FloatingActionButton flAddContact;
AddContact quickAdd;//Objet de type Addcontact, pour enregistrer un nouveau contact (DialogFragment)
FragmentManager fm;
MenuActivity menuActivity;//Instance de l'activite principale
BackendlessUser user;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View racine_contact = inflater.inflate(R.layout.contact_ui, container, false);
contacts = new ArrayList<>();
c_Adapter = new ContactAdapter2(getContext(), contacts);
user = Backendless.UserService.CurrentUser();
flAddContact = (FloatingActionButton) racine_contact.findViewById(R.id.floatingAddContact);
lvContact = (ListView) racine_contact.findViewById(R.id.lvContact);
menuActivity = (MenuActivity) getActivity();
menuActivity.fab.setVisibility(View.INVISIBLE);//Remplacer le FAB d'urgence par le FAB d'ajout de contact
fm = getFragmentManager();
lvContact.setAdapter(c_Adapter);
quickAdd = new AddContact();
//Ouverture du DialogFragment AddContact pour enregistre un nouveau contact
flAddContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
quickAdd.setTargetFragment(ContactFragment2.this, 300);
quickAdd.show(fm, "Adding contact");
}
});
contact = new Contact();
populateContact();
return racine_contact;
}
@Override
public void onDestroyView() {
super.onDestroyView();
menuActivity.fab.setVisibility(View.VISIBLE);
}
public void populateContact() {
contacts.add(contact);//Fake Data
Backendless.Persistence.of(Contact.class).find(new AsyncCallback<List<Contact>>() {
@Override
public void handleResponse(List<Contact> response) {
contacts.addAll(response);
Log.d("DEBUG", response.toString());
c_Adapter.notifyDataSetChanged();
}
@Override
public void handleFault(BackendlessFault fault) {
Log.d("DEBUG", fault.getMessage());
}
});
c_Adapter.notifyDataSetChanged();
}
//Methode qui recoit l'enregistrement d'un nouveau contact et l'ajoute a la liste
@Override
public void onFinishEditContact(String nom, String prenom, String email, int number1, int number2) {
Contact newContact = new Contact(nom, prenom, email, number1, number2, user.getUserId().toString());
contacts.add(newContact);
Backendless.Data.of(Contact.class).save(newContact, new AsyncCallback<Contact>() {
@Override
public void handleResponse(Contact response) {
Toast.makeText(getContext(), "Contact saved", Toast.LENGTH_SHORT).show();
}
@Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(getContext(), fault.getMessage(), Toast.LENGTH_SHORT).show();
}
});
c_Adapter.notifyDataSetChanged();
}
}
|
package com.lothrazar.cyclicmagic.spell;
import javax.annotation.Nullable;
import com.lothrazar.cyclicmagic.ModCyclic;
import com.lothrazar.cyclicmagic.gui.wand.InventoryWand;
import com.lothrazar.cyclicmagic.item.tool.ItemCyclicWand;
import com.lothrazar.cyclicmagic.net.PacketSpellFromServer;
import com.lothrazar.cyclicmagic.util.UtilChat;
import com.lothrazar.cyclicmagic.util.UtilSound;
import com.lothrazar.cyclicmagic.util.UtilSpellCaster;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class SpellRangeBuild extends BaseSpellRange implements ISpellFromServer {
final static int max = 32;// max search range
private PlaceType type;
public static enum PlaceType {
PLACE, UP, DOWN, LEFT, RIGHT;
}
public SpellRangeBuild(int id, String n, PlaceType t) {
super.init(id, n);
this.type = t;
}
@Override
public boolean cast(World world, EntityPlayer p, ItemStack wand, BlockPos pos, EnumFacing side) {
if (world.isRemote) {
// only client side can call this method. mouseover does not exist on server
BlockPos mouseover = ModCyclic.proxy.getBlockMouseoverExact(maxRange);
BlockPos offset = ModCyclic.proxy.getBlockMouseoverOffset(maxRange);
EnumFacing sideMouseover = ModCyclic.proxy.getSideMouseover(maxRange);
if (mouseover != null && offset != null) {
ModCyclic.network.sendToServer(new PacketSpellFromServer(mouseover, offset, sideMouseover, this.getID()));
}
ItemStack heldWand = UtilSpellCaster.getPlayerWandIfHeld(p);
if (heldWand != null) {
int itemSlot = ItemCyclicWand.BuildType.getSlot(heldWand);
IBlockState state = InventoryWand.getToPlaceFromSlot(heldWand, itemSlot);
if (state != null && state.getBlock() != null && offset != null) {
UtilSound.playSoundPlaceBlock(world, offset, state.getBlock());
}
}
}
return true;
}
public void castFromServer(BlockPos posMouseover, BlockPos posOffset, @Nullable EnumFacing sideMouseover, EntityPlayer p) {
World world = p.getEntityWorld();
ItemStack heldWand = UtilSpellCaster.getPlayerWandIfHeld(p);
if (heldWand == null) { return; }
int itemSlot = ItemCyclicWand.BuildType.getSlot(heldWand);
IBlockState state = InventoryWand.getToPlaceFromSlot(heldWand, itemSlot);
if (state == null || state.getBlock() == null) {
//one last chance to update slot, in case something happened
ItemCyclicWand.BuildType.setNextSlot(heldWand);
itemSlot = ItemCyclicWand.BuildType.getSlot(heldWand);
state = InventoryWand.getToPlaceFromSlot(heldWand, itemSlot);
if (state == null || state.getBlock() == null) {
UtilChat.addChatMessage(p, "wand.inventory.empty");
return;
}
}
BlockPos posToPlaceAt = null;
EnumFacing facing = null;
EnumFacing playerFacing = p.getHorizontalFacing();
switch (type) {
case DOWN:
facing = EnumFacing.DOWN;
break;
case UP:
facing = EnumFacing.UP;
break;
case LEFT:
switch (playerFacing) {
case DOWN:
break;
case EAST:
facing = EnumFacing.NORTH;
break;
case NORTH:
facing = EnumFacing.WEST;
break;
case SOUTH:
facing = EnumFacing.EAST;
break;
case UP:
break;
case WEST:
facing = EnumFacing.SOUTH;
break;
default:
break;
}
break;
case RIGHT:
switch (playerFacing) {
case DOWN:
break;
case EAST:
facing = EnumFacing.SOUTH;
break;
case NORTH:
facing = EnumFacing.EAST;
break;
case SOUTH:
facing = EnumFacing.WEST;
break;
case UP:
break;
case WEST:
facing = EnumFacing.NORTH;
break;
default:
break;
}
break;
case PLACE:
break;
default:
break;
}
if (facing == null) {
posToPlaceAt = posOffset;
}
else {
BlockPos posLoop = posMouseover;
for (int i = 0; i < max; i++) {
if (world.isAirBlock(posLoop)) {
posToPlaceAt = posLoop;
break;
}
else {
posLoop = posLoop.offset(facing);
}
}
}
// if (UtilPlaceBlocks.placeStateSafe(world, p, posToPlaceAt, state)) {
ItemStack cur = InventoryWand.getFromSlot(heldWand, itemSlot);
if (sideMouseover == null) {
sideMouseover = p.getHorizontalFacing();
}
if (posToPlaceAt != null && cur.onItemUse(p, world, posToPlaceAt, p.getActiveHand(), sideMouseover, 0.5F, 0.5F, 0.5F) == EnumActionResult.SUCCESS) {
if (p.capabilities.isCreativeMode == false) {
InventoryWand.decrementSlot(heldWand, itemSlot);
}
ItemCyclicWand.BuildType.setNextSlot(heldWand);
// yes im spawning particles on the server side, but the
// util handles that
this.spawnParticle(world, p, posMouseover);
Block newSpot = null;
if (world.getBlockState(posToPlaceAt) != null) {
newSpot = world.getBlockState(posToPlaceAt).getBlock();
this.playSound(world, p, newSpot, posToPlaceAt);
}
}
}
}
|
package eu.bcvsolutions.idm.core.model.service.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import eu.bcvsolutions.idm.core.api.config.domain.EventConfiguration;
import eu.bcvsolutions.idm.core.api.domain.Auditable;
import eu.bcvsolutions.idm.core.api.domain.ConfigurationMap;
import eu.bcvsolutions.idm.core.api.domain.CoreResultCode;
import eu.bcvsolutions.idm.core.api.domain.Identifiable;
import eu.bcvsolutions.idm.core.api.domain.OperationState;
import eu.bcvsolutions.idm.core.api.domain.PriorityType;
import eu.bcvsolutions.idm.core.api.domain.comparator.CreatedComparator;
import eu.bcvsolutions.idm.core.api.dto.AbstractDto;
import eu.bcvsolutions.idm.core.api.dto.DefaultResultModel;
import eu.bcvsolutions.idm.core.api.dto.EntityEventProcessorDto;
import eu.bcvsolutions.idm.core.api.dto.IdmEntityEventDto;
import eu.bcvsolutions.idm.core.api.dto.IdmEntityStateDto;
import eu.bcvsolutions.idm.core.api.dto.OperationResultDto;
import eu.bcvsolutions.idm.core.api.dto.ResultModel;
import eu.bcvsolutions.idm.core.api.dto.filter.EntityEventProcessorFilter;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmEntityStateFilter;
import eu.bcvsolutions.idm.core.api.entity.AbstractEntity;
import eu.bcvsolutions.idm.core.api.event.AsyncEntityEventProcessor;
import eu.bcvsolutions.idm.core.api.event.CoreEvent;
import eu.bcvsolutions.idm.core.api.event.CoreEvent.CoreEventType;
import eu.bcvsolutions.idm.core.api.event.DefaultEventContext;
import eu.bcvsolutions.idm.core.api.event.EntityEvent;
import eu.bcvsolutions.idm.core.api.event.EntityEventEvent.EntityEventType;
import eu.bcvsolutions.idm.core.api.event.EntityEventProcessor;
import eu.bcvsolutions.idm.core.api.event.EventContext;
import eu.bcvsolutions.idm.core.api.event.EventResult;
import eu.bcvsolutions.idm.core.api.event.EventType;
import eu.bcvsolutions.idm.core.api.exception.EventContentDeletedException;
import eu.bcvsolutions.idm.core.api.exception.ResultCodeException;
import eu.bcvsolutions.idm.core.api.service.ConfigurationService;
import eu.bcvsolutions.idm.core.api.service.EntityEventManager;
import eu.bcvsolutions.idm.core.api.service.IdmEntityEventService;
import eu.bcvsolutions.idm.core.api.service.IdmEntityStateService;
import eu.bcvsolutions.idm.core.api.service.LookupService;
import eu.bcvsolutions.idm.core.api.utils.EntityUtils;
import eu.bcvsolutions.idm.core.model.repository.IdmEntityEventRepository;
import eu.bcvsolutions.idm.core.scheduler.api.config.SchedulerConfiguration;
import eu.bcvsolutions.idm.core.security.api.service.EnabledEvaluator;
import eu.bcvsolutions.idm.core.security.api.service.SecurityService;
public class DefaultEntityEventManager implements EntityEventManager {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DefaultEntityEventManager.class);
private static final ConcurrentHashMap<UUID, UUID> runningOwnerEvents = new ConcurrentHashMap<>();
private final ApplicationContext context;
private final ApplicationEventPublisher publisher;
private final EnabledEvaluator enabledEvaluator;
private final LookupService lookupService;
@Autowired private IdmEntityEventService entityEventService;
@Autowired private IdmEntityEventRepository entityEventRepository;
@Autowired private IdmEntityStateService entityStateService;
@Autowired private ConfigurationService configurationService;
@Autowired private SecurityService securityService;
@Autowired private EventConfiguration eventConfiguration;
@Autowired
public DefaultEntityEventManager(
ApplicationContext context,
ApplicationEventPublisher publisher,
EnabledEvaluator enabledEvaluator,
LookupService lookupService) {
Assert.notNull(context, "Spring context is required");
Assert.notNull(publisher, "Event publisher is required");
Assert.notNull(enabledEvaluator, "Enabled evaluator is required");
Assert.notNull(lookupService, "LookupService is required");
this.context = context;
this.publisher = publisher;
this.enabledEvaluator = enabledEvaluator;
this.lookupService = lookupService;
}
/**
* Cancel all previously ran events
*/
@Override
public void init() {
LOG.info("Cancel unprocessed events - event was interrupt during instance restart");
String instanceId = configurationService.getInstanceId();
entityEventService.findByState(instanceId, OperationState.RUNNING).forEach(event -> {
LOG.info("Cancel unprocessed event [{}] - event was interrupt during instance [{}] restart", event.getId(), instanceId);
// cancel event
ResultModel resultModel = new DefaultResultModel(
CoreResultCode.EVENT_CANCELED_BY_RESTART,
ImmutableMap.of(
"eventId", event.getId(),
"eventType", event.getEventType(),
"ownerId", String.valueOf(event.getOwnerId()),
"instanceId", event.getInstanceId()));
OperationResultDto result = new OperationResultDto.Builder(OperationState.CANCELED).setModel(resultModel).build();
event.setResult(result);
entityEventService.saveInternal(event);
// cancel event states
IdmEntityStateFilter filter = new IdmEntityStateFilter();
filter.setEventId(event.getId());
entityStateService.find(filter, null)
.getContent()
.stream()
.filter(state -> {
return OperationState.RUNNING == state.getResult().getState();
})
.forEach(state -> {
event.setResult(result);
entityStateService.save(state);
});
});
}
@Override
@SuppressWarnings("unchecked")
public <E extends Serializable> EventContext<E> process(EntityEvent<E> event) {
Assert.notNull(event);
Serializable content = event.getContent();
LOG.info("Publishing event [{}]", event);
// continue suspended event
event.getContext().setSuspended(false);
// read previous (original) dto source - usable in "check modification" processors
if (event.getOriginalSource() == null && (content instanceof AbstractDto)) { // original source could be set externally
AbstractDto contentDto = (AbstractDto) content;
// works only for dto modification
if (contentDto.getId() != null && lookupService.getDtoLookup(contentDto.getClass()) != null) {
event.setOriginalSource((E) lookupService.lookupDto(contentDto.getClass(), contentDto.getId()));
}
}
publisher.publishEvent(event);
LOG.info("Event [{}] is completed", event);
return event.getContext();
}
@Override
@SuppressWarnings({ "rawtypes" })
public List<EntityEventProcessorDto> find(EntityEventProcessorFilter filter) {
List<EntityEventProcessorDto> dtos = new ArrayList<>();
Map<String, EntityEventProcessor> processors = context.getBeansOfType(EntityEventProcessor.class);
for(Entry<String, EntityEventProcessor> entry : processors.entrySet()) {
EntityEventProcessor<?> processor = entry.getValue();
// entity event processor depends on module - we could not call any processor method
// TODO: all processor should be returned - disbaled by filter
if (!enabledEvaluator.isEnabled(processor)) {
continue;
}
EntityEventProcessorDto dto = toDto(processor);
if (passFilter(dto, filter)) {
dtos.add(dto);
}
}
LOG.debug("Returning [{}] registered entity event processors", dtos.size());
return dtos;
}
@Override
public EntityEventProcessorDto get(String processorId) {
EntityEventProcessor<?> processor = getProcessor(processorId);
if (processor == null) {
return null;
}
return toDto(processor);
}
/**
* Get processor from context by id
*
* @param processorId
* @return
*/
@Override
public EntityEventProcessor<?> getProcessor(String processorId) {
Assert.notNull(processorId);
return (EntityEventProcessor<?>) context.getBean(processorId);
}
@Override
public void publishEvent(Object event) {
publisher.publishEvent(event);
}
@Override
public <E extends Identifiable> void changedEntity(E owner) {
changedEntity(owner, null);
}
@Override
public <E extends Identifiable> void changedEntity(E owner, EntityEvent<? extends Identifiable> originalEvent) {
Assert.notNull(owner);
changedEntity(owner.getClass(), getOwnerId(owner), originalEvent);
}
@Override
public void changedEntity(Class<? extends Identifiable> ownerType, UUID ownerId) {
changedEntity(ownerType, ownerId, null);
}
@Override
public void changedEntity(
Class<? extends Identifiable> ownerType,
UUID ownerId,
EntityEvent<? extends Identifiable> originalEvent) {
IdmEntityEventDto event = createEvent(ownerType, ownerId, originalEvent);
event.setEventType(CoreEventType.NOTIFY.name());
putToQueue(event);
}
/**
* Spring schedule new task after previous task ended (don't run concurrently)
*/
@Scheduled(fixedDelayString = "${" + SchedulerConfiguration.PROPERTY_EVENT_QUEUE_PROCESS + ":" + SchedulerConfiguration.DEFAULT_EVENT_QUEUE_PROCESS + "}")
public void scheduleProcessCreated() {
if (!eventConfiguration.isAsynchronous()) {
// asynchronous processing is disabled
// prevent to debug some messages into log - usable for devs
return;
}
// run as system - called from scheduler internally
securityService.setSystemAuthentication();
// calculate events to process
String instanceId = configurationService.getInstanceId();
List<IdmEntityEventDto> events = getCreatedEvents(instanceId);
LOG.trace("Events to process [{}] on instance [{}].", events.size(), instanceId);
for (IdmEntityEventDto event : events) {
// @Transactional
context.getBean(this.getClass()).executeEvent(event);;
}
}
@Override
public IdmEntityEventDto getEvent(EntityEvent<? extends Serializable> event) {
Assert.notNull(event);
UUID changeId = getEventId(event);
if (changeId == null) {
// event doesn't contain entity change - event is not based on entity change
return null;
}
return entityEventService.get(changeId);
}
@Override
public UUID getEventId(EntityEvent<? extends Serializable> event) {
Assert.notNull(event);
return EntityUtils.toUuid(event.getProperties().get(EVENT_PROPERTY_EVENT_ID));
}
@Override
public String getOwnerType(Class<? extends Identifiable> ownerType) {
Assert.notNull(ownerType);
// dto class was given
Class<? extends AbstractEntity> ownerEntityType = getOwnerClass(ownerType);
if (ownerEntityType == null) {
throw new IllegalArgumentException(String.format("Owner type [%s] has to generalize [AbstractEntity]", ownerType));
}
return ownerEntityType.getCanonicalName();
}
@Override
@SuppressWarnings("unchecked")
public AbstractDto findOwner(IdmEntityEventDto change) {
try {
Class<?> ownerType = Class.forName(change.getOwnerType());
if (!AbstractEntity.class.isAssignableFrom(ownerType)) {
throw new IllegalArgumentException(String.format("Owner type [%s] has to generalize [AbstractEntity]", ownerType));
}
return (AbstractDto) lookupService.lookupDto((Class<? extends AbstractEntity>) ownerType, change.getOwnerId());
} catch (ClassNotFoundException ex) {
LOG.error("Class [{}] for entity change [{}] not found, module or type was uninstalled, returning null",
change.getOwnerType(), change.getId());
return null;
}
}
@Override
@SuppressWarnings("unchecked")
public AbstractDto findOwner(String ownerType, Serializable ownerId) {
try {
Class<?> ownerTypeClass = Class.forName(ownerType);
if (!AbstractEntity.class.isAssignableFrom(ownerTypeClass)) {
throw new IllegalArgumentException(String.format("Owner type [%s] has to generalize [AbstractEntity]", ownerType));
}
return (AbstractDto) lookupService.lookupDto((Class<? extends AbstractEntity>) ownerTypeClass, ownerId);
} catch (ClassNotFoundException ex) {
LOG.error("Class [{}] for entity change [{}] not found, module or type was uninstalled, returning null",
ownerType, ownerId);
return null;
}
}
@Override
@Transactional
public void executeEvent(IdmEntityEventDto event) {
Assert.notNull(event);
Assert.notNull(event.getOwnerId());
if (!eventConfiguration.isAsynchronous()) {
// synchronous processing
// we don't persist events and their states
process(new CoreEvent<>(EntityEventType.EXECUTE, event));
return;
}
if (event.getPriority() == PriorityType.IMMEDIATE) {
// synchronous processing
// we don't persist events and their states
// TODO: what about running event with the same owner? And events in queue for the same owner
process(new CoreEvent<>(EntityEventType.EXECUTE, event));
return;
}
if (runningOwnerEvents.putIfAbsent(event.getOwnerId(), event.getId()) != null) {
LOG.debug("Previous event [{}] for owner with id [{}] is currently processed.",
runningOwnerEvents.get(event.getOwnerId()), event.getOwnerId());
// event will be processed in another scheduling
return;
}
// check super owner is not processed
UUID superOwnerId = event.getProperties().getUuid(EntityEventManager.EVENT_PROPERTY_SUPER_OWNER_ID);
if (superOwnerId != null && !superOwnerId.equals(event.getOwnerId())) {
if (runningOwnerEvents.putIfAbsent(superOwnerId, event.getId()) != null) {
LOG.debug("Previous event [{}] for super owner with id [{}] is currently processed.",
runningOwnerEvents.get(superOwnerId), superOwnerId);
runningOwnerEvents.remove(event.getOwnerId());
// event will be processed in another scheduling
return;
}
}
// execute event in new thread asynchronously
try {
eventConfiguration.getExecutor().execute(new Runnable() {
@Override
public void run() {
try {
process(new CoreEvent<>(EntityEventType.EXECUTE, event));
} catch (Exception ex) {
// exception handling only ... all processor should persist their own entity state (see AbstractEntityEventProcessor)
ResultModel resultModel;
if (ex instanceof ResultCodeException) {
resultModel = ((ResultCodeException) ex).getError().getError();
} else {
resultModel = new DefaultResultModel(
CoreResultCode.EVENT_EXECUTE_FAILED,
ImmutableMap.of(
"eventId", event.getId(),
"eventType", String.valueOf(event.getEventType()),
"ownerId", String.valueOf(event.getOwnerId()),
"instanceId", String.valueOf(event.getInstanceId())));
}
context.getBean(DefaultEntityEventManager.this.getClass()).saveResult(event.getId(), new OperationResultDto
.Builder(OperationState.EXCEPTION)
.setCause(ex)
.setModel(resultModel)
.build());
LOG.error(resultModel.toString(), ex);
} finally {
LOG.trace("Event [{}] ends for owner with id [{}].", event.getId(), event.getOwnerId());
removeRunningEvent(event);
}
}
});
LOG.trace("Running event [{}] for owner with id [{}].", event.getId(), event.getOwnerId());
} catch (RejectedExecutionException ex) {
// thread pool is full - wait for another try
// TODO: Thread.wait(300) ?
removeRunningEvent(event);
}
}
private void removeRunningEvent(IdmEntityEventDto event) {
runningOwnerEvents.remove(event.getOwnerId());
UUID superOwnerId = event.getProperties().getUuid(EntityEventManager.EVENT_PROPERTY_SUPER_OWNER_ID);
if (superOwnerId != null) {
runningOwnerEvents.remove(superOwnerId);
}
}
/**
* TODO: Will be this method useful?
*
* @param event
*/
@SuppressWarnings("unused")
private void runOnBackground(EntityEvent<? extends Identifiable> event) {
Assert.notNull(event);
putToQueue(createEvent(event.getContent(), event));
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public IdmEntityEventDto saveResult(UUID eventId, OperationResultDto result) {
Assert.notNull(eventId);
Assert.notNull(result);
IdmEntityEventDto entityEvent = entityEventService.get(eventId);
Assert.notNull(entityEvent);
entityEvent.setResult(result);
return entityEventService.save(entityEvent);
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public <E extends Serializable> List<IdmEntityStateDto> saveStates(
EntityEvent<E> event,
List<IdmEntityStateDto> previousStates,
EventResult<E> result) {
IdmEntityEventDto entityEvent = getEvent(event);
List<IdmEntityStateDto> results = new ArrayList<>();
if (entityEvent == null) {
return results;
}
// simple drop - we don't need to find and update results, we'll create new ones
if (previousStates != null && !previousStates.isEmpty()) {
previousStates.forEach(state -> {
entityStateService.delete(state);
});
}
if (result == null) {
IdmEntityStateDto state = new IdmEntityStateDto(entityEvent);
// default result without model
state.setResult(new OperationResultDto
.Builder(OperationState.EXECUTED)
.build());
results.add(entityStateService.save(state));
return results;
}
if (result.getResults().isEmpty()) {
results.add(entityStateService.save(createState(entityEvent, result, new OperationResultDto.Builder(OperationState.EXECUTED).build())));
return results;
}
result.getResults().forEach(opeartionResult -> {
results.add(entityStateService.save(createState(entityEvent, result, opeartionResult.toDto())));
});
return results;
}
@Override
public EntityEvent<Identifiable> toEvent(IdmEntityEventDto entityEvent) {
Identifiable content = null;
// try to use persisted event content
// only if type and id is the same as owner can be used
if (entityEvent.getContent() != null
&& entityEvent.getContent().getClass().getCanonicalName().equals(entityEvent.getOwnerType())
&& entityEvent.getContent().getId().equals(entityEvent.getOwnerId())) {
content = entityEvent.getContent();
}
if (content == null) {
// content is not persisted - try to find actual entity
content = findOwner(entityEvent);
}
if (content == null) {
throw new EventContentDeletedException(entityEvent);
}
Map<String, Serializable> eventProperties = entityEvent.getProperties().toMap();
eventProperties.put(EVENT_PROPERTY_EVENT_ID, entityEvent.getId());
eventProperties.put(EVENT_PROPERTY_PRIORITY, entityEvent.getPriority());
eventProperties.put(EVENT_PROPERTY_EXECUTE_DATE, entityEvent.getExecuteDate());
eventProperties.put(EVENT_PROPERTY_PARENT_EVENT_TYPE, entityEvent.getParentEventType());
final String type = entityEvent.getEventType();
DefaultEventContext<Identifiable> initContext = new DefaultEventContext<>();
initContext.setProcessedOrder(entityEvent.getProcessedOrder());
EventType eventType = (EventType) () -> type;
EntityEvent<Identifiable> resurectedEvent = new CoreEvent<>(eventType, content, eventProperties, initContext);
resurectedEvent.setOriginalSource(entityEvent.getOriginalSource());
return resurectedEvent;
}
@Override
public void enable(String processorId) {
setEnabled(processorId, true);
}
@Override
public void disable(String processorId) {
setEnabled(processorId, false);
}
@Override
public void setEnabled(String processorId, boolean enabled) {
setEnabled(getProcessor(processorId), enabled);
}
private void setEnabled(EntityEventProcessor<?> processor, boolean enabled) {
String enabledPropertyName = processor.getConfigurationPropertyName(ConfigurationService.PROPERTY_ENABLED);
configurationService.setBooleanValue(enabledPropertyName, enabled);
}
/**
* Convert processor to dto.
*
* @param processor
* @return
*/
private EntityEventProcessorDto toDto(EntityEventProcessor<?> processor) {
EntityEventProcessorDto dto = new EntityEventProcessorDto();
dto.setId(processor.getId());
dto.setName(processor.getName());
dto.setModule(processor.getModule());
dto.setContentClass(processor.getEntityClass());
dto.setEntityType(processor.getEntityClass().getSimpleName());
dto.setEventTypes(Lists.newArrayList(processor.getEventTypes()));
dto.setClosable(processor.isClosable());
dto.setDisabled(processor.isDisabled());
dto.setDisableable(processor.isDisableable());
dto.setOrder(processor.getOrder());
// resolve documentation
dto.setDescription(processor.getDescription());
dto.setConfigurationProperties(processor.getConfigurationMap());
return dto;
}
@SuppressWarnings({"unchecked", "rawtypes" })
private void putToQueue(IdmEntityEventDto entityEvent) {
if (entityEvent.getPriority() == PriorityType.IMMEDIATE) {
LOG.trace("Event type [{}] for owner with id [{}] will be executed synchronously.",
entityEvent.getEventType(), entityEvent.getOwnerId());
executeEvent(entityEvent);
return;
}
if (!eventConfiguration.isAsynchronous()) {
LOG.trace("Event type [{}] for owner with id [{}] will be executed synchronously, asynchronous event processing [{}] is disabled.",
entityEvent.getEventType(), entityEvent.getOwnerId(), EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_ENABLED);
executeEvent(entityEvent);
return;
}
// get enabled processors
final EntityEvent<Identifiable> event = toEvent(entityEvent);
List<EntityEventProcessor> registeredProcessors = context
.getBeansOfType(EntityEventProcessor.class)
.values()
.stream()
.filter(enabledEvaluator::isEnabled)
.filter(processor -> !processor.isDisabled())
.filter(processor -> processor.supports(event))
.filter(processor -> processor.conditional(event))
.sorted(new AnnotationAwareOrderComparator())
.collect(Collectors.toList());
if (registeredProcessors.isEmpty()) {
LOG.debug("Event type [{}] for owner with id [{}] will not be executed, no enabled processor is registered.",
entityEvent.getEventType(), entityEvent.getOwnerId());
return;
}
// evaluate event priority by registered processors
PriorityType priority = evaluatePriority(event, registeredProcessors);
if (priority != null && priority.getPriority() < entityEvent.getPriority().getPriority()) {
entityEvent.setPriority(priority);
}
// registered processors voted about event will be processed synchronously
if (entityEvent.getPriority() == PriorityType.IMMEDIATE) {
LOG.trace("Event type [{}] for owner with id [{}] will be executed synchronously.",
entityEvent.getEventType(), entityEvent.getOwnerId());
executeEvent(entityEvent);
return;
}
// TODO: send notification only when event fails
// notification - info about registered (asynchronous) processors
// Map<String, Object> parameters = new LinkedHashMap<>();
// parameters.put("eventType", entityEvent.getEventType());
// parameters.put("ownerId", entityEvent.getOwnerId());
// parameters.put("instanceId", entityEvent.getInstanceId());
// parameters.put("processors", registeredProcessors
// .stream()
// .map(DefaultEntityEventManager.this::toDto)
// .collect(Collectors.toList()));
// notificationManager.send(
// CoreModuleDescriptor.TOPIC_EVENT,
// new IdmMessageDto
// .Builder()
// .setLevel(NotificationLevel.INFO)
// .setModel(new DefaultResultModel(CoreResultCode.EVENT_ACCEPTED, parameters))
// .build());
// persist event - asynchronous processing
entityEventService.save(entityEvent);
}
/**
* Evaluate event priority by registered processors
*
* @param event
* @param registeredProcessors
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected PriorityType evaluatePriority(EntityEvent<Identifiable> event, List<EntityEventProcessor> registeredProcessors) {
PriorityType priority = null;
for (EntityEventProcessor processor : registeredProcessors) {
if (!(processor instanceof AsyncEntityEventProcessor)) {
continue;
}
AsyncEntityEventProcessor asyncProcessor = (AsyncEntityEventProcessor) processor;
PriorityType processorPriority = asyncProcessor.getPriority(event);
if (processorPriority == null) {
// processor doesn't vote about priority - preserve original event priority.
continue;
}
if (priority == null || processorPriority.getPriority() < priority.getPriority()) {
priority = processorPriority;
}
if (priority == PriorityType.IMMEDIATE) {
// nothing is higher
break;
}
}
return priority;
}
/**
* Called from scheduler - concurrency is prevented.
* Returns events to process sorted by priority 7 / 3 (high / normal).
* Immediate priority is executed synchronously.
* Cancel duplicate events (same type, owner and props) - last event is returned
*
* @param instanceId
* @return
*/
protected List<IdmEntityEventDto> getCreatedEvents(String instanceId) {
Assert.notNull(instanceId);
// load created events - high priority
DateTime executeDate = new DateTime();
Page<IdmEntityEventDto> highEvents = entityEventService.findToExecute(
instanceId,
executeDate,
PriorityType.HIGH,
new PageRequest(0, 100, new Sort(Direction.ASC, Auditable.PROPERTY_CREATED)));
// load created events - low priority
Page<IdmEntityEventDto> normalEvents = entityEventService.findToExecute(
instanceId,
executeDate,
PriorityType.NORMAL,
new PageRequest(0, 100, new Sort(Direction.ASC, Auditable.PROPERTY_CREATED)));
// merge events
List<IdmEntityEventDto> events = new ArrayList<>();
events.addAll(highEvents.getContent());
events.addAll(normalEvents.getContent());
// sort by created date
events.sort(new CreatedComparator());
// cancel duplicates - by owner => properties has to be the same
// execute the first event for each owner only - preserve events order
Map<UUID, IdmEntityEventDto> distinctEvents = new LinkedHashMap<>();
events.forEach(event -> {
if (!distinctEvents.containsKey(event.getOwnerId())) {
// the first event
distinctEvents.put(event.getOwnerId(), event);
} else {
// cancel duplicate older event
IdmEntityEventDto olderEvent = distinctEvents.get(event.getOwnerId());
if (isDuplicate(olderEvent, event)) {
// try to set higher priority
if (olderEvent.getPriority() == PriorityType.HIGH) {
event.setPriority(PriorityType.HIGH);
}
distinctEvents.put(event.getOwnerId(), event);
LOG.debug(new DefaultResultModel(
CoreResultCode.EVENT_DUPLICATE_CANCELED,
ImmutableMap.of(
"eventId", olderEvent.getId(),
"eventType", String.valueOf(olderEvent.getEventType()),
"ownerId", String.valueOf(olderEvent.getOwnerId()),
"instanceId", String.valueOf(olderEvent.getInstanceId()),
"neverEventId", event.getId())).toString());
if (entityEventRepository.countByParentId(olderEvent.getId()) == 0) {
entityEventService.delete(olderEvent);
}
}
}
});
// sort by priority
events = distinctEvents
.values()
.stream()
.sorted((o1, o2) -> {
return Integer.compare(o1.getPriority().getPriority(), o2.getPriority().getPriority());
})
.collect(Collectors.toList());
int normalCount = events.stream().filter(e -> e.getPriority() == PriorityType.NORMAL).collect(Collectors.toList()).size();
int highMaximum = normalCount > 30 ? 70 : (100 - normalCount);
// evaluate priority => high 70 / low 30
int highCounter = 0;
List<IdmEntityEventDto> prioritizedEvents = new ArrayList<>();
for (IdmEntityEventDto event : events) {
if (event.getPriority() == PriorityType.HIGH) {
if (highCounter < highMaximum) {
prioritizedEvents.add(event);
highCounter++;
}
} else {
// normal priority remains only
if (prioritizedEvents.size() >= 100) {
break;
}
prioritizedEvents.add(event);
}
}
return prioritizedEvents;
}
/**
* Returns true, when events are duplicates
*
* @param olderEvent
* @param event
* @return
*/
public boolean isDuplicate(IdmEntityEventDto olderEvent, IdmEntityEventDto event) {
return Objects.equal(olderEvent.getEventType(), event.getEventType())
&& Objects.equal(olderEvent.getParentEventType(), event.getParentEventType())
&& Objects.equal(getProperties(olderEvent), getProperties(event));
}
/**
* Remove internal event properties needed for processing
*
* @param event
* @return
*/
private ConfigurationMap getProperties(IdmEntityEventDto event) {
ConfigurationMap copiedProperies = new ConfigurationMap();
copiedProperies.putAll(event.getProperties());
// remove internal event properties needed for processing
copiedProperies.remove(EVENT_PROPERTY_EVENT_ID);
copiedProperies.remove(EVENT_PROPERTY_EXECUTE_DATE);
copiedProperies.remove(EVENT_PROPERTY_PRIORITY);
copiedProperies.remove(EVENT_PROPERTY_SKIP_NOTIFY);
copiedProperies.remove(EVENT_PROPERTY_SUPER_OWNER_ID);
return copiedProperies;
}
private <E extends Serializable> IdmEntityStateDto createState(
IdmEntityEventDto entityEvent,
EventResult<E> eventResult,
OperationResultDto operationResult) {
IdmEntityStateDto state = new IdmEntityStateDto(entityEvent);
state.setClosed(eventResult.isClosed());
state.setSuspended(eventResult.isSuspended());
state.setProcessedOrder(eventResult.getProcessedOrder());
state.setProcessorId(eventResult.getProcessor().getId());
state.setProcessorModule(eventResult.getProcessor().getModule());
state.setProcessorName(eventResult.getProcessor().getName());
state.setResult(operationResult);
return state;
}
/**
* Returns true, when given processor pass given filter
*
* @param processor
* @param filter
* @return
*/
private boolean passFilter(EntityEventProcessorDto processor, EntityEventProcessorFilter filter) {
if (filter == null) {
// empty filter
return true;
}
// id - not supported
if (filter.getId() != null) {
throw new UnsupportedOperationException("Filtering event processors by [id] is not supported.");
}
// text - lowercase like in name, description, content class - canonical name
if (StringUtils.isNotEmpty(filter.getText())) {
if (!processor.getName().toLowerCase().contains(filter.getText().toLowerCase())
&& (processor.getDescription() == null || !processor.getDescription().toLowerCase().contains(filter.getText().toLowerCase()))
&& !processor.getContentClass().getCanonicalName().toLowerCase().contains(filter.getText().toLowerCase())) {
return false;
}
}
// processors name
if (StringUtils.isNotEmpty(filter.getName()) && !processor.getName().equals(filter.getName())) {
return false;
}
// content ~ entity type - dto type
if (filter.getContentClass() != null && !filter.getContentClass().isAssignableFrom(processor.getContentClass())) {
return false;
}
// module id
if (StringUtils.isNotEmpty(filter.getModule()) && !filter.getModule().equals(processor.getModule())) {
return false;
}
// description - like
if (StringUtils.isNotEmpty(filter.getDescription())
&& StringUtils.isNotEmpty(processor.getDescription())
&& !processor.getDescription().contains(filter.getDescription())) {
return false;
}
// entity ~ content type - simple name
if (StringUtils.isNotEmpty(filter.getEntityType()) && !processor.getEntityType().equals(filter.getEntityType())) {
return false;
}
// event types
if (!filter.getEventTypes().isEmpty() && !processor.getEventTypes().containsAll(filter.getEventTypes())) {
return false;
}
return true;
}
/**
* Creates entity event
*
* @param identifiable
* @param originalEvent
* @return
*/
protected IdmEntityEventDto createEvent(Identifiable identifiable, EntityEvent<? extends Identifiable> originalEvent) {
Assert.notNull(identifiable);
Assert.notNull(identifiable.getId(), "Change can be published after entity id is assigned at least.");
return createEvent(identifiable.getClass(), getOwnerId(identifiable), originalEvent);
}
private IdmEntityEventDto createEvent(Class<? extends Identifiable> ownerType, UUID ownerId, EntityEvent<? extends Identifiable> originalEvent) {
Assert.notNull(ownerType);
Assert.notNull(ownerId, "Change can be published after entity id is assigned at least.");
IdmEntityEventDto savedEvent = new IdmEntityEventDto();
savedEvent.setOwnerId(ownerId);
savedEvent.setOwnerType(getOwnerType(ownerType));
savedEvent.setResult(new OperationResultDto.Builder(OperationState.CREATED).build());
savedEvent.setInstanceId(eventConfiguration.getAsynchronousInstanceId());
if (originalEvent != null) {
savedEvent.setEventType(originalEvent.getType().name());
savedEvent.getProperties().putAll(originalEvent.getProperties());
savedEvent.setParent(EntityUtils.toUuid(originalEvent.getProperties().get(EVENT_PROPERTY_EVENT_ID)));
savedEvent.setExecuteDate((DateTime) originalEvent.getProperties().get(EVENT_PROPERTY_EXECUTE_DATE));
savedEvent.setPriority((PriorityType) originalEvent.getProperties().get(EVENT_PROPERTY_PRIORITY));
savedEvent.setParentEventType(originalEvent.getType().name());
savedEvent.setContent(originalEvent.getContent());
savedEvent.setOriginalSource(originalEvent.getOriginalSource());
savedEvent.setClosed(originalEvent.isClosed());
if (savedEvent.isClosed()) {
savedEvent.setResult(new OperationResultDto
.Builder(OperationState.EXECUTED)
.setModel(new DefaultResultModel(CoreResultCode.EVENT_ALREADY_CLOSED))
.build());
}
savedEvent.setSuspended(originalEvent.isSuspended());
} else {
// notify as default event type
savedEvent.setEventType(CoreEventType.NOTIFY.name());
}
if (savedEvent.getPriority() == null) {
savedEvent.setPriority(PriorityType.NORMAL);
}
return savedEvent;
}
/**
* UUID identifier from given owner.
*
* @param owner
* @return
*/
private UUID getOwnerId(Identifiable owner) {
Assert.notNull(owner);
if (owner.getId() == null) {
return null;
}
Assert.isInstanceOf(UUID.class, owner.getId(), "Entity with UUID identifier is supported as owner for entity changes.");
return (UUID) owner.getId();
}
/**
* Returns {@link AbstractEntity}. Owner type has to be entity class - dto class can be given.
*
* @param ownerType
* @return
*/
@SuppressWarnings("unchecked")
private Class<? extends AbstractEntity> getOwnerClass(Class<? extends Identifiable> ownerType) {
Assert.notNull(ownerType, "Owner type is required!");
// formable entity class was given
if (AbstractEntity.class.isAssignableFrom(ownerType)) {
return (Class<? extends AbstractEntity>) ownerType;
}
// dto class was given
Class<?> ownerEntityType = lookupService.getEntityClass(ownerType);
if (AbstractEntity.class.isAssignableFrom(ownerEntityType)) {
return (Class<? extends AbstractEntity>) ownerEntityType;
}
return null;
}
}
|
package com.yokmama.learn10.chapter09.lesson41;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
public class MyGdxGame extends ApplicationAdapter {
public final int VIEWPORT_WIDTH = 800;
public final int VIEWPORT_HEIGHT = 480;
public GameState gameState = GameState.Ready;
private int score;
public SpriteBatch batch;
OrthographicCamera uiCamera;
OrthographicCamera camera;
float cameraLeftEdge;
Text text;
Hero mHero;
Texture backgroundClear;
float bgWidth;
float bgSpeed;
Texture finish;
float finishX;
// Generator
private Generator mGenerator;
private SoundManager mSound;
@Override
public void create() {
batch = new SpriteBatch();
camera = new OrthographicCamera();
camera.setToOrtho(false, VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
uiCamera = new OrthographicCamera();
uiCamera.setToOrtho(false, VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
text = new Text();
mHero = new Hero();
backgroundClear = new Texture("bg.png");
bgWidth = VIEWPORT_HEIGHT * (backgroundClear.getWidth() / backgroundClear.getHeight());
bgSpeed = 0.2f;
finish = new Texture("flag.png");
finishX = (bgWidth - VIEWPORT_WIDTH) / bgSpeed + Hero.HERO_LEFT_X;
mGenerator = new Generator();
mSound = new SoundManager();
mSound.music.play();
resetWorld();
}
@Override
public void resize(int width, int height) {
uiCamera.update();
}
@Override
public void dispose() {
Hero.disposeTexture();
mSound.dispose();
}
private void resetWorld() {
score = 0;
mHero.init();
camera.position.x = VIEWPORT_WIDTH / 2 - Hero.HERO_LEFT_X;
cameraLeftEdge = camera.position.x - VIEWPORT_WIDTH / 2;
mGenerator.init(VIEWPORT_WIDTH);
mGenerator.clear();
}
@Override
public void render() {
Gdx.gl.glClearColor(0, 153.0f / 255.0f, 204.0f / 255.0f, 1); // #0099CC
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updateWorld();
drawWorld();
}
private void updateWorld() {
float deltaTime = Gdx.graphics.getDeltaTime();
if (Gdx.input.justTouched()) {
if (gameState == GameState.Ready) {
gameState = GameState.Running;
mHero.startRunning();
}
else if (gameState == GameState.GameOver) {
gameState = GameState.Ready;
resetWorld();
}
else if (gameState == GameState.GameCleared) {
gameState = GameState.Ready;
resetWorld();
}
else if (gameState == GameState.Running) {
mHero.jump();
}
Gdx.app.log("MyGdxGame", "gameState=" + gameState);
}
if (mGenerator.chipGenerationLine < cameraLeftEdge + VIEWPORT_WIDTH &&
mGenerator.chipGenerationLine + 5 * 50.0f < finishX) {
mGenerator.generate(this);
}
mGenerator.update(this, deltaTime);
mHero.update(deltaTime);
if (gameState != GameState.GameCleared) {
camera.position.x = VIEWPORT_WIDTH / 2 + mHero.getPosition().x - Hero.HERO_LEFT_X;
cameraLeftEdge = camera.position.x - VIEWPORT_WIDTH / 2;
}
if (gameState != GameState.GameCleared) {
float heroX = mHero.getPosition().x;
if (finishX < heroX) {
mSound.finaleClaps.play();
gameState = GameState.GameCleared;
mHero.win();
}
}
if (gameState == GameState.GameOver || gameState == GameState.GameCleared) {
return;
}
Rectangle heroCollision = mHero.getCollisionRect();
for (Chip chip : mGenerator.chips) {
if (!chip.isCollected && Intersector.overlaps(chip.collisionCircle, heroCollision)) {
chip.collect();
mSound.coin.play();
score += chip.getScore();
}
}
for (Mine mine : mGenerator.mines) {
if (!mine.hasCollided && Intersector.overlaps(mine.collisionCircle, heroCollision)) {
mine.collide();
mSound.collision.play();
mHero.die();
gameState = GameState.GameOver;
}
}
}
private void drawWorld() {
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
float drawOffset = cameraLeftEdge - cameraLeftEdge * bgSpeed;
batch.draw(backgroundClear, drawOffset, 0, bgWidth, VIEWPORT_HEIGHT);
mGenerator.draw(this);
mHero.draw(this);
batch.draw(finish, finishX, 0,
finish.getWidth() * 0.35f,
finish.getHeight() * 0.35f);
batch.end();
batch.setProjectionMatrix(uiCamera.combined);
batch.begin();
if (gameState == GameState.Ready) {
text.drawTextTop(batch, "START", uiCamera);
}
else if (gameState == GameState.GameCleared) {
text.drawTextTop(batch, "SCORE: " + score, uiCamera);
text.drawTextCenter(batch, "LEVEL CLEAR", uiCamera);
}
else if (gameState == GameState.GameOver) {
text.drawTextTop(batch, "SCORE: " + score, uiCamera);
text.drawTextCenter(batch, "GAME OVER", uiCamera);
}
else if (gameState == GameState.Running) {
text.drawTextTop(batch, "SCORE: " + score, uiCamera);
}
batch.end();
}
}
|
package com.mazgon.activiti;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
public final class HashUtil {
private static final Logger logger = LoggerFactory.getLogger(HashUtil.class);
public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
// The following constants may be changed without breaking existing hashes.
public static final int SALT_BYTES = 24;
public static final int HASH_BYTES = 24;
public static final int PBKDF2_ITERATIONS = 1000;
public static final int ITERATION_INDEX = 0;
public static final int SALT_INDEX = 1;
public static final int PBKDF2_INDEX = 2;
/**
* Returns a salted PBKDF2 hash of the password.
*
* @param password
* the password to hash
* @return a salted PBKDF2 hash of the password
*/
public static String createHash(String password) {
try {
return createHash(password.toCharArray());
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
return null;
}
}
/**
* Returns a salted PBKDF2 hash of the password.
*
* @param password
* the password to hash
* @return a salted PBKDF2 hash of the password
*/
public static String createHash(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Generate a random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_BYTES];
random.nextBytes(salt);
// Hash the password
byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTES);
// format iterations:salt:hash
return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);
}
/**
* Validates a password using a hash.
*
* @param password
* the password to check
* @param goodHash
* the hash of the valid password
* @return true if the password is correct, false if not
*/
public static boolean validatePassword(String password, String goodHash) {
try {
return validatePassword(password.toCharArray(), goodHash);
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
return false;
}
}
/**
* Validates a password using a hash.
*
* @param password
* the password to check
* @param goodHash
* the hash of the valid password
* @return true if the password is correct, false if not
*/
public static boolean validatePassword(char[] password, String goodHash) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Decode the hash into its parameters
String[] params = goodHash.split(":");
int iterations = Integer.parseInt(params[ITERATION_INDEX]);
byte[] salt = fromHex(params[SALT_INDEX]);
byte[] hash = fromHex(params[PBKDF2_INDEX]);
// Compute the hash of the provided password, using the same salt,
// iteration count, and hash length
byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
// Compare the hashes in constant time. The password is correct if
// both hashes match.
return slowEquals(hash, testHash);
}
/**
* Compares two byte arrays in length-constant time. This comparison method
* is used so that password hashes cannot be extracted from an on-line
* system using a timing attack and then attacked off-line.
*
* @param a
* the first byte array
* @param b
* the second byte array
* @return true if both byte arrays are the same, false if not
*/
private static boolean slowEquals(byte[] a, byte[] b) {
int diff = a.length ^ b.length;
for (int i = 0; i < a.length && i < b.length; i++)
diff |= a[i] ^ b[i];
return diff == 0;
}
/**
* Computes the PBKDF2 hash of a password.
*
* @param password
* the password to hash.
* @param salt
* the salt
* @param iterations
* the iteration count (slowness factor)
* @param bytes
* the length of the hash to compute in bytes
* @return the PBDKF2 hash of the password
*/
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
return skf.generateSecret(spec).getEncoded();
}
/**
* Converts a string of hexadecimal characters into a byte array.
*
* @param hex
* the hex string
* @return the hex string decoded into a byte array
*/
private static byte[] fromHex(String hex) {
byte[] binary = new byte[hex.length() / 2];
for (int i = 0; i < binary.length; i++) {
binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return binary;
}
/**
* Converts a byte array into a hexadecimal string.
*
* @param array
* the byte array to convert
* @return a length*2 character string encoding the byte array
*/
private static String toHex(byte[] array) {
BigInteger bi = new BigInteger(1, array);
String hex = bi.toString(16);
int paddingLength = (array.length * 2) - hex.length();
if (paddingLength > 0)
return String.format("%0" + paddingLength + "d", 0) + hex;
else
return hex;
}
}
|
package org.eclipse.birt.report.designer.internal.ui.dnd;
import org.eclipse.birt.report.designer.core.model.schematic.HandleAdapterFactory;
import org.eclipse.birt.report.designer.testutil.BaseTestCase;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ListGroupHandle;
import org.eclipse.birt.report.model.api.ListHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.TableGroupHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
public class InsertInLayoutUtilTest extends BaseTestCase
{
static class LayoutExtendsUtil extends InsertInLayoutUtil
{
public static DesignElementHandle performInsertDataSetColumn(
ResultSetColumnHandle model, Object target, Object targetParent ) throws SemanticException
{
return InsertInLayoutUtil.performInsertDataSetColumn( model,
target,
targetParent );
}
}
private static final String FILE_NAME = "../internal/ui/dnd/DndTest.rptdesign";
private static final String DATA_SET_1_NAME = "Data Set";
private static final String TABLE1_NAME = "Table";
private static final String LIST1_NAME = "List";
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.testutil.BaseTestCase#getLoadFile()
*/
protected String getLoadFile( )
{
return FILE_NAME;
}
// private ElementFactory getElementFactory( )
// return getReportDesignHandle( ).getElementFactory( );
private DataSetHandle getDataSet1( )
{
return getReportDesignHandle( ).findDataSet( DATA_SET_1_NAME );
}
private ListHandle getListHandle( )
{
return (ListHandle) getReportDesignHandle( ).findElement( LIST1_NAME );
}
private TableHandle getTableHandle( )
{
return (TableHandle) getReportDesignHandle( ).findElement( TABLE1_NAME );
}
private TableGroupHandle getTableGroup( )
{
return (TableGroupHandle) getTableHandle( ).getGroups( ).get( 0 );
}
private ListGroupHandle getListGroup( )
{
return (ListGroupHandle) getListHandle( ).getGroups( ).get( 0 );
}
private CellHandle getCell( int row, int column )
{
return (CellHandle) HandleAdapterFactory.getInstance( )
.getTableHandleAdapter( getTableHandle( ) )
.getCell( row, column );
}
public void testOpenFile( )
{
assertTrue( "test data set 1", getDataSet1( ) != null );
assertTrue( "test data set 1", getDataSet1( ).getDataSource( ) != null );
assertTrue( "test table 1", getTableHandle( ) != null );
assertTrue( "test list 1", getListHandle( ) != null );
assertTrue( "test table group", getTableGroup( ) != null );
assertTrue( "test list group", getListGroup( ) != null );
}
public void testPerformInsertDataSetColumn( ) throws SemanticException
{
// DataSetManager.setCurrentInstance( DataSetManager.newInstance( ) );
// DataSetItemModel[] columnModels = DataSetManager.getCurrentInstance( )
// .getColumns( getDataSet1( ), false );
// Object target = null;
// Object targetParent = null;
// String keyExp = null;
// //Test GroupKeySetRule
// //Test table group
// target = getCell( 2, 1 );
// targetParent = getTableHandle( );
// assertTrue( "test table group key expression",
// getTableGroup( ).getKeyExpr( ) == null );
// assertTrue( "test table data set",
// getTableHandle( ).getDataSet( ) == null );
// for ( int i = 0; i < columnModels.length; i++ )
// if ( i == 0 )
// keyExp = columnModels[i].getDataSetColumnName( );
// LayoutExtendsUtil.performInsertDataSetColumn( columnModels[i],
// target,
// targetParent );
// assertTrue( "test table group key expression",
// getTableGroup( ).getKeyExpr( ).equals( keyExp ) );
// assertTrue( "test table data set",
// getTableHandle( ).getDataSet( ) == getDataSet1( ) );
// //Test list group
// target = new ListBandProxy( getListGroup( ).getSlot( ListGroup.HEADER_SLOT ) );
// targetParent = getListHandle( );
// assertTrue( "test list group key expression",
// getListGroup( ).getKeyExpr( ) == null );
// assertTrue( "test list data set",
// getListHandle( ).getDataSet( ) == null );
// for ( int i = 0; i < columnModels.length; i++ )
// if ( i == 0 )
// keyExp = columnModels[i].getDataSetColumnName( );
// LayoutExtendsUtil.performInsertDataSetColumn( columnModels[i],
// target,
// targetParent );
// assertTrue( "test list group key expression",
// getListGroup( ).getKeyExpr( ).equals( keyExp ) );
// assertTrue( "test list data set",
// getListHandle( ).getDataSet( ) == getDataSet1( ) );
}
}
|
package com.openlattice.jdbc;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.kryptnostic.rhizome.configuration.RhizomeConfiguration;
import com.kryptnostic.rhizome.pods.ConfigurationPod;
import com.kryptnostic.rhizome.pods.MetricsPod;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.inject.Inject;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* @author Matthew Tamayo-Rios <matthew@openlattice.com>
*/
@Configuration
@Import( { ConfigurationPod.class, MetricsPod.class } )
public class JdbcPod {
private static final Logger logger = LoggerFactory.getLogger( JdbcPod.class );
@Inject
private RhizomeConfiguration rhizomeConfiguration;
@Inject
private HealthCheckRegistry healthCheckRegistry;
@Inject
private MetricRegistry metricRegistry;
@Bean
public HikariDataSource hikariDataSource() {
if ( rhizomeConfiguration.getHikariConfiguration().isPresent() ) {
HikariConfig hc = new HikariConfig( rhizomeConfiguration.getHikariConfiguration().get() );
logger.info( "JDBC URL = {}", hc.getJdbcUrl() );
HikariDataSource hds = new HikariDataSource( hc );
hds.setHealthCheckRegistry( healthCheckRegistry );
hds.setMetricRegistry( metricRegistry );
return hds;
} else {
return null;
}
}
@Bean
public Jdbi jdbi() {
Jdbi jdbi = Jdbi.create( hikariDataSource() );
jdbi.installPlugin( new SqlObjectPlugin() );
return jdbi;
}
}
|
package com.shzisg.mybatis.mapper.builder;
import com.shzisg.mybatis.mapper.anno.Not;
import com.shzisg.mybatis.mapper.auto.EntityPortray;
import com.shzisg.mybatis.mapper.auto.MapperConfig;
import com.shzisg.mybatis.mapper.auto.MapperUtils;
import com.shzisg.mybatis.mapper.auto.OrderBy;
import com.shzisg.mybatis.mapper.page.PageRequest;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.core.MethodParameter;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
public class SelectBuilder implements SqlBuilder {
@Override
public String buildSql(Class<?> mapper, Method method, EntityPortray entityPortray) {
StringBuilder builder = new StringBuilder();
Class<?> returnType = MapperUtils.getReturnType(method, mapper);
EntityPortray returnPortray = MapperUtils.getEntityPortray(mapper, returnType);
Map<String, String> columnMap = entityPortray.getColumnMap();
Map<String, Class<? extends TypeHandler>> typeHandlers = entityPortray.getColumnTypeHandlers();
// Map<String, Class<?>> parameterMap = MapperUtils.getParameters(method);
Map<String, MethodParameter> parameterMap = MapperUtils.getMethodParameters(method);
if (columnMap.containsKey(MapperConfig.getDelFlag()) && method.getName().endsWith("Valid") && !parameterMap.containsKey(MapperConfig.getDelFlag())) {
parameterMap.put("__del_flag__", null);
}
builder.append("<script>select ")
.append(returnPortray.getColumnMap().values().stream().collect(Collectors.joining(",")))
.append(" from ")
.append(entityPortray.getName())
.append("<where>");
parameterMap.forEach((param, paraType) -> {
if (PageRequest.class.isAssignableFrom(paraType.getParameterType())) {
return;
}
if (Collection.class.isAssignableFrom(paraType.getParameterType())) {
builder.append(" and ")
.append(columnMap.get(param))
.append(paraType.getParameterAnnotation(Not.class) == null ? "" : " not")
.append(" in ")
.append("<foreach item=\"item\" index=\"index\" collection=\"")
.append(param)
.append("\" open=\"(\" separator=\",\" close=\")\">")
.append("#{item}</foreach>");
} else if (param.equals("__del_flag__")) {
builder.append(" and ")
.append(columnMap.get(MapperConfig.getDelFlag()))
.append("=0");
} else {
builder.append(" and ")
.append(columnMap.get(param))
.append(paraType.getParameterAnnotation(Not.class) == null ? "" : "!")
.append("=")
.append(MapperUtils.buildTypeValue(param, paraType.getParameterType(), "", typeHandlers.get(param)));
}
});
builder.append("</where>");
OrderBy orderBy = method.getAnnotation(OrderBy.class);
if (orderBy != null) {
if (!orderBy.orderSql().isEmpty()) {
builder.append(orderBy.orderSql());
} else if (!orderBy.value().isEmpty()) {
builder.append(" order by ")
.append(columnMap.getOrDefault(orderBy.value(), orderBy.value()))
.append(orderBy.desc() ? " desc " : " asc ");
}
}
builder.append("</script>");
return builder.toString();
}
}
|
package com.szmslab.quickjavamail.receive;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeUtility;
import org.apache.commons.lang3.StringUtils;
import com.szmslab.quickjavamail.utils.AttachmentFile;
import com.szmslab.quickjavamail.utils.InlineImageFile;
import com.szmslab.quickjavamail.utils.MailAddress;
/**
*
*
* @author szmslab
*/
public class MessageLoader {
private boolean isDeleted;
private Message message;
private MessageContent contentCashe;
/**
*
*
* @param message
*
*/
public MessageLoader(Message message) {
this.message = message;
this.isDeleted = false;
}
/**
*
*
* @param message
*
* @param isDeleted
*
*/
public MessageLoader(Message message, boolean isDeleted) {
this.message = message;
this.isDeleted = isDeleted;
}
/**
*
*
* @return
*/
public boolean isDeleted() {
return isDeleted;
}
/**
*
*
* @param isDeleted
*
*/
public void deleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
/**
*
*
* @return
*/
public Message getOriginalMessage() {
return message;
}
/**
* Message-ID
*
* @return Message-ID
* @throws MessagingException
*/
public String getMessageId() throws MessagingException {
return StringUtils.defaultString(StringUtils.join(message.getHeader("Message-ID"), ","));
}
/**
* MUA
*
* @return MUA
* @throws MessagingException
*/
public String getMessageUserAgent() throws MessagingException {
String mua = StringUtils.join(message.getHeader("User-Agent"), ",");
if (StringUtils.isBlank(mua)) {
mua = StringUtils.defaultString(StringUtils.join(message.getHeader("X-Mailer"), ","));
}
return mua;
}
/**
*
*
* @return
* @throws MessagingException
*/
public Date getSentDate() throws MessagingException {
return message.getSentDate();
}
/**
*
*
* @return
* @throws MessagingException
*/
public int getSize() throws MessagingException {
return message.getSize();
}
/**
* From
*
* @return From
* @throws MessagingException
*/
public List<MailAddress> getFromAddressList() throws MessagingException {
return toMailAddressList((InternetAddress[]) message.getFrom());
}
/**
* ReplyTo
*
* @return ReplyTo
* @throws MessagingException
*/
public List<MailAddress> getReplyToAddressList() throws MessagingException {
return toMailAddressList((InternetAddress[]) message.getReplyTo());
}
/**
* To
*
* @return To
* @throws MessagingException
*/
public List<MailAddress> getToAddressList() throws MessagingException {
return toMailAddressList((InternetAddress[]) message.getRecipients(RecipientType.TO));
}
/**
* Cc
*
* @return Cc
* @throws MessagingException
*/
public List<MailAddress> getCcAddressList() throws MessagingException {
return toMailAddressList((InternetAddress[]) message.getRecipients(RecipientType.CC));
}
/**
*
*
* @return
* @throws MessagingException
*/
@SuppressWarnings("unchecked")
public Properties getHeaders() throws MessagingException {
Properties p = new Properties();
for (Enumeration<Header> headers = message.getAllHeaders(); headers.hasMoreElements();) {
Header header = headers.nextElement();
p.setProperty(header.getName(), header.getValue());
}
return p;
}
/**
*
*
* @return
* @throws MessagingException
*/
public String getSubject() throws MessagingException {
return message.getSubject();
}
/**
* TEXT
*
* @return TEXT
* @throws MessagingException
* @throws IOException
*/
public String getText() throws MessagingException, IOException {
return getContent().text;
}
/**
* HTML
*
* @return HTML
* @throws MessagingException
* @throws IOException
*/
public String getHtml() throws MessagingException, IOException {
return getContent().html;
}
/**
*
*
* @return
* @throws MessagingException
* @throws IOException
*/
public List<AttachmentFile> getAttachmentFileList() throws MessagingException, IOException {
return getContent().attachmentFileList;
}
/**
*
*
* @return
* @throws MessagingException
* @throws IOException
*/
public List<InlineImageFile> getInlineImageFileList() throws MessagingException, IOException {
return getContent().inlineImageFileList;
}
/**
*
*
* @return
* @throws MessagingException
*/
public boolean isPartial() throws MessagingException {
return message.getContentType().indexOf("message/partial") >= 0;
}
/**
*
*
* @return
* @throws MessagingException
* @throws IOException
*/
public ByteArrayInputStream getPartialContent() throws MessagingException, IOException {
return getContent().partialContent;
}
/**
* InternetAddressMailAddress
*
* @param addresses
* InternetAddress
* @return MailAddress
*/
private List<MailAddress> toMailAddressList(InternetAddress[] addresses) {
List<MailAddress> list = new ArrayList<MailAddress>();
if (addresses != null) {
for (InternetAddress address : addresses) {
list.add(new MailAddress(address.getAddress(), address.getPersonal()));
}
}
return list;
}
/**
*
*
* @return
* @throws MessagingException
* @throws IOException
*/
private MessageContent getContent() throws MessagingException, IOException {
if (contentCashe == null) {
MessageContent msgContent = new MessageContent();
Object c = message.getContent();
if (c instanceof Multipart) {
setMultipartContent((Multipart) c, msgContent);
} else if (c instanceof ByteArrayInputStream) {
msgContent.partialContent = (ByteArrayInputStream) c;
} else {
msgContent.text = c.toString();
}
contentCashe = msgContent;
}
return contentCashe;
}
/**
* MessageContent
*
* @param multiPart
*
* @param msgContent
*
* @throws MessagingException
* @throws IOException
*/
private void setMultipartContent(Multipart multiPart, MessageContent msgContent) throws MessagingException, IOException {
for (int i = 0; i < multiPart.getCount(); i++) {
Part part = multiPart.getBodyPart(i);
if (part.getContentType().indexOf("multipart") >= 0) {
setMultipartContent((Multipart) part.getContent(), msgContent);
} else if (part.isMimeType("text/html")) {
msgContent.html = part.getContent().toString();
} else if (part.isMimeType("text/plain")) {
msgContent.text = part.getContent().toString();
} else {
String disposition = part.getDisposition();
if (Part.ATTACHMENT.equals(disposition)) {
msgContent.attachmentFileList.add(
new AttachmentFile(MimeUtility.decodeText(part.getFileName()), part.getDataHandler().getDataSource()));
} else if (Part.INLINE.equals(disposition)) {
String cid = "";
if (part instanceof MimeBodyPart) {
MimeBodyPart mimePart = (MimeBodyPart) part;
cid = mimePart.getContentID();
}
msgContent.inlineImageFileList.add(
new InlineImageFile(cid, MimeUtility.decodeText(part.getFileName()), part.getDataHandler().getDataSource()));
}
}
}
}
/**
*
*
* @author szmslab
*/
class MessageContent {
/**
* (TEXT)
*/
public String text = "";
/**
* (HTML)
*/
public String html = "";
public List<AttachmentFile> attachmentFileList = new ArrayList<AttachmentFile>();
public List<InlineImageFile> inlineImageFileList = new ArrayList<InlineImageFile>();
public ByteArrayInputStream partialContent = null;
}
}
|
/*
* $Id: Channel.java,v 1.10 2010/08/20 13:33:08 hrickens Exp $
*/
package org.csstudio.config.ioconfig.model.pbmodel;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.csstudio.config.ioconfig.model.AbstractNodeDBO;
import org.csstudio.config.ioconfig.model.InvalidLeave;
import org.csstudio.config.ioconfig.model.NodeType;
import org.csstudio.config.ioconfig.model.PersistenceException;
import org.csstudio.config.ioconfig.model.tools.NodeMap;
import org.csstudio.platform.logging.CentralLogger;
import org.hibernate.annotations.BatchSize;
@Entity
@BatchSize(size = 32)
@Table(name = "ddb_Profibus_Channel")
public class ChannelDBO extends AbstractNodeDBO<ChannelStructureDBO, InvalidLeave> {
private static final long serialVersionUID = 1L;
private int _channelNumber;
private boolean _input;
private boolean _digital;
private String _ioName;
private String _currenUserParamDataIndex;
private String _currentValue;
private int _statusAddressOffset;
private int _channelType;
private String _epicsAdress;
private boolean _isUpdated;
/**
* This Constructor is only used by Hibernate. To create an new {@link ChannelDBO}
* {@link #Channel(ChannelStructureDBO, boolean, boolean)} or
* {@link #Channel(ChannelStructureDBO, String, boolean, boolean, short)} or
*/
public ChannelDBO() {
// Constructor for Hibernate
}
/**
* Generate a new Pure Channel on the parent Channel Structure. The Channel get the first free
* Station Address. The max Station Address is {@link ChannelDBO}
* {@value #DEFAULT_MAX_STATION_ADDRESS}
*
* @param channelStructure
* the parent Channel Structure.
*
* @param input
* only if true then is the channel a Input otherwise a Output channel.
* @param digital
* only if true then is the channel a Digital otherwise a Analog channel.
* @throws PersistenceException
*/
public ChannelDBO(@Nonnull final ChannelStructureDBO channelStructure,
final boolean input,
final boolean digital) throws PersistenceException {
this(channelStructure, null, input, digital, (short) -1);
}
/**
* Generate a new Pure Channel on the parent Channel Structure. The Channel get the first free
* Station Address. The max Station Address is {@link ChannelDBO}
* {@value #DEFAULT_MAX_STATION_ADDRESS}
*
* @param channelStructure
* the parent Channel Structure.
*
* @param name
* the name of this Channel.
*
* @param input
* only if true then is the channel a Input otherwise a Output channel.
* @param digital
* only if true then is the channel a Digital otherwise a Analog channel.
* @param sortIndex
* the sort posiotion for this Channel.
* @throws PersistenceException
*/
public ChannelDBO(@Nonnull final ChannelStructureDBO channelStructure,
@Nonnull final String name,
final boolean input,
final boolean digital,
final int sortIndex) throws PersistenceException {
setName(name);
setInput(input);
setDigital(digital);
setParent(channelStructure);
setSortIndex(sortIndex);
channelStructure.addChild(this);
localUpdate();
}
/**
*
* @return The Channel number inclusive offset.
* @throws PersistenceException
*/
@Transient
public int getFullChannelNumber() throws PersistenceException {
int value = 0;
if(isInput()) {
value = getModule().getInputOffsetNH();
} else {
value = getModule().getOutputOffsetNH();
}
return value + _channelNumber;
}
/**
*
* @return the Channel Number.
*/
public int getChannelNumber() {
return _channelNumber;
}
/**
* Only used from Hibernate or Internal! The Channel number are automatic set when the sortIndex
* are set.
*
* @param channelNumber
* the channel start Address.
*/
public void setChannelNumber(final int channelNumber) {
this._channelNumber = channelNumber;
}
/**
*
* @return is only true when this Channel is an Input.
*/
public boolean isInput() {
return _input;
}
/**
*
* @param input
* this channel as Input.
*/
public void setInput(final boolean input) {
this._input = input;
}
/**
*
* @return is only true when this Channel is an Output.
*/
@Transient
public boolean isOutput() {
return !isInput();
}
/**
*
* @param output
* set this channel as Output.
*/
public void setOutput(final boolean output) {
setInput(!output);
}
/**
*
* @return the IO Name of this Channel.
*/
@CheckForNull
public String getIoName() {
return _ioName;
}
/**
*
* @param ioName
* the IO Name of this Channel.
*/
public void setIoName(@Nonnull final String ioName) {
this._ioName = ioName;
}
/**
*
* @return is only true if the {@link ChannelDBO} digital.
*/
public boolean isDigital() {
return _digital;
}
/**
*
* @param digital
* set only true if this {@link ChannelDBO} digital.
*/
public void setDigital(final boolean digital) {
_digital = digital;
}
/**
*
* @return the bit size of the Channel.
*/
@Transient
public int getChSize() {
return getChannelType().getBitSize();
}
/**
*
* @return the Type of this {@link ChannelDBO}
*/
@Nonnull
public DataType getChannelType() {
if(_channelType < DataType.values().length) {
return DataType.values()[_channelType];
}
return DataType.BIT;
}
/**
*
* @param type set the Type of this {@link ChannelDBO}
*/
public void setChannelType(@Nonnull final DataType type) {
_channelType = type.ordinal();
}
public void setChannelTypeNonHibernate(@Nonnull final DataType type) throws PersistenceException {
if(getChannelType() != type) {
setChannelType(type);
setDirty(true);
if(getModule() != null) {
// Don't work with only one update!
getModule().update();
getModule().update();
} else {
localUpdate();
}
}
}
@CheckForNull
public String getCurrenUserParamDataIndex() {
return _currenUserParamDataIndex;
}
public void setCurrenUserParamDataIndex(@Nonnull final String currenUserParamDataIndex) {
_currenUserParamDataIndex = currenUserParamDataIndex;
}
@CheckForNull
public String getCurrentValue() {
return _currentValue;
}
public void setCurrentValue(@Nonnull final String currentValue) {
_currentValue = currentValue;
}
@Column(name = "CHSIZE")
public int getStatusAddressOffset() {
return _statusAddressOffset;
}
@Transient
public int getStatusAddress() throws PersistenceException {
return getModule().getInputOffsetNH() + _statusAddressOffset;
}
public void setStatusAddressOffset(@CheckForNull Integer statusAddress) {
_statusAddressOffset = statusAddress == null ? -1 : statusAddress;
}
/**
* contribution to ioName (PV-link to EPICSORA)
*
* @param epicsAdress
* the Epics Address String.
*/
public void setEpicsAddressString(@Nonnull final String epicsAdress) {
_epicsAdress = epicsAdress;
}
/**
* contribution to ioName (PV-link to EPICSORA)
*
* @return the Epics Address String
*/
@Transient
@Nonnull
public String getEpicsAddressStringNH() {
return _epicsAdress == null ? "" : _epicsAdress;
}
/**
* contribution to ioName (PV-link to EPICSORA)
*
* @return the Epics Address String
*/
@Nonnull
public String getEpicsAddressString() {
return _epicsAdress == null ? "" : _epicsAdress;
}
@Transient
public int getStruct() {
int index = 0;
if(isDigital()) {
index = getSortIndex();
}
return index;
}
/**
*
* @return the parent {@link ChannelStructureDBO}.
*/
@ManyToOne
@Nonnull
public ChannelStructureDBO getChannelStructure() {
return (ChannelStructureDBO) getParent();
}
/**
*
* @param channelStructure
* the parent {@link ChannelStructureDBO} of this Channel.
*/
public void setChannelStructure(@Nonnull final ChannelStructureDBO channelStructure) {
this.setParent(channelStructure);
}
/**
*
* @return the Slave GSD File
*/
@Transient
@CheckForNull
public GSDFileDBO getGSDFile() {
return getChannelStructure().getModule().getGSDFile();
}
/**
* {@inheritDoc}
* @throws PersistenceException
*/
@Override
protected void localUpdate() throws PersistenceException {
NodeMap.countlocalUpdate();
int channelNumber = 0;
short channelSortIndex = getSortIndex();
short structSortIndex = getParent().getSortIndex();
short moduleSortIndex = getModule().getSortIndex();
if(! ( (channelSortIndex <= 0) && (structSortIndex <= 0) && (moduleSortIndex <= 0))) {
// if it a simple Channel (AI/AO)
if(getChannelStructure().isSimple()) {
channelNumber = updateSimpleChannel(channelNumber, structSortIndex);
} else {
channelNumber = updateStructureChannel(channelNumber,
channelSortIndex,
structSortIndex);
}
}
setChannelNumber(channelNumber);
assembleEpicsAddressString();
}
private int updateStructureChannel(int channelNumber,
short channelSortIndex,
short structSortIndex) throws PersistenceException {
int cNumber = channelNumber;
// Structe Channel (8 bit (DI/DO)))
boolean isSet = false;
if(channelSortIndex > 0) {
ChannelDBO channel = null;
short counter = channelSortIndex;
while ( (channel == null) && (counter > 0)) {
channel = getChannelStructure().getChildrenAsMap().get(--counter);
if(channel != null) {
cNumber = channel.getChannelNumber();
cNumber += channel.getChannelType().getByteSize();
isSet = true;
break;
}
}
}
if( (structSortIndex > 0) && !isSet) {
ChannelStructureDBO channelStructure = null;
short counter = structSortIndex;
while ( (channelStructure == null) && (counter > 0)) {
channelStructure = getModule().getChildrenAsMap().get(--counter);
if(channelStructure != null) {
ChannelDBO firstChannel = channelStructure.getFirstChannel();
if(firstChannel != null && firstChannel.isInput() == isInput()) {
if(channelStructure.isSimple()) {
cNumber = firstChannel.getChannelNumber();
cNumber += firstChannel.getChannelType().getByteSize();
break;
} else {
ChannelDBO lastChannel = channelStructure.getLastChannel();
cNumber = lastChannel.getChannelNumber()
+ channelStructure.getStructureType().getByteSize();
break;
}
}
}
channelStructure = null;
}
}
return cNumber;
}
private int updateSimpleChannel(int channelNumber, short structSortIndex) throws PersistenceException {
int cNr = channelNumber;
if(structSortIndex > 0) {
ChannelStructureDBO channelStructure = null;
short counter = structSortIndex;
while ( (channelStructure == null) && (counter > 0)) {
channelStructure = getModule().getChildrenAsMap().get(--counter);
ChannelDBO lastChannel = channelStructure.getLastChannel();
if(isRigthSimpleChannel(channelStructure, lastChannel)) {
// Previous Channel is:
cNr = lastChannel.getChannelNumber();
if(channelStructure.isSimple()) {
cNr += lastChannel.getChannelType().getByteSize();
} else {
cNr += channelStructure.getStructureType().getByteSize();
}
break;
}
channelStructure = null;
}
}
return cNr;
}
/**
* @param channelStructure
* @param lastChannel
* @return
*/
private boolean isRigthSimpleChannel(@CheckForNull ChannelStructureDBO channelStructure,
@CheckForNull ChannelDBO lastChannel) {
return (channelStructure != null) && (lastChannel != null)
&& (lastChannel.isInput() == isInput());
}
/**
* Assemble the Epics Address String.
* @throws PersistenceException
*/
@Transient
@Override
public void assembleEpicsAddressString() throws PersistenceException {
NodeMap.countAssembleEpicsAddressString();
String oldAdr = getEpicsAddressString();
try {
StringBuilder sb = new StringBuilder(getModule().getEpicsAddressString());
sb.append("/");
sb.append(getFullChannelNumber());
if(getStatusAddressOffset() >= 0) {
sb.append("/");
sb.append(getStatusAddress());
}
sb.append(" 'T=");
Set<ModuleChannelPrototypeDBO> moduleChannelPrototypes = getModule().getGSDModule()
.getModuleChannelPrototypeNH();
for (ModuleChannelPrototypeDBO moduleChannelPrototype : moduleChannelPrototypes) {
if( (moduleChannelPrototype.isInput() == isInput())
&& (getChannelNumber() == moduleChannelPrototype.getOffset())) {
setChannelType(moduleChannelPrototype);
appendDataType(sb, moduleChannelPrototype);
setStatusAddressOffset(moduleChannelPrototype.getShift());
appendMinimum(sb, moduleChannelPrototype);
appendMaximum(sb, moduleChannelPrototype);
appendByteOdering(sb, moduleChannelPrototype);
}
}
sb.append("'");
setEpicsAddressString(sb.toString());
} catch (NullPointerException e) {
setEpicsAddressString("");
}
setDirty( (isDirty() || (oldAdr == null) || !oldAdr.equals(getEpicsAddressString())));
}
/**
* @param sb
* @param moduleChannelPrototype
*/
private void appendDataType(StringBuilder sb, ModuleChannelPrototypeDBO moduleChannelPrototype) {
if( (getChannelType() == DataType.BIT) && !getChannelStructure().isSimple()) {
sb.append(getChannelStructure().getStructureType().getType());
sb.append(getBitPostion());
} else {
sb.append(moduleChannelPrototype.getType().getType());
}
}
/**
* @param sb
* @param moduleChannelPrototype
*/
private void appendByteOdering(StringBuilder sb,
ModuleChannelPrototypeDBO moduleChannelPrototype) {
if( (moduleChannelPrototype.getMaximum() != null)
&& (moduleChannelPrototype.getByteOrdering() > 0)) {
sb.append(",O=" + moduleChannelPrototype.getByteOrdering());
}
}
/**
* @param sb
* @param moduleChannelPrototype
*/
private void appendMaximum(StringBuilder sb, ModuleChannelPrototypeDBO moduleChannelPrototype) {
if(moduleChannelPrototype.getMaximum() != null) {
sb.append(",H=" + moduleChannelPrototype.getMaximum());
}
}
/**
* @param sb
* @param moduleChannelPrototype
*/
private void appendMinimum(StringBuilder sb, ModuleChannelPrototypeDBO moduleChannelPrototype) {
if(moduleChannelPrototype.getMinimum() != null) {
sb.append(",L=" + moduleChannelPrototype.getMinimum());
}
}
/**
* @param moduleChannelPrototype
* @throws PersistenceException
*/
private void setChannelType(ModuleChannelPrototypeDBO moduleChannelPrototype) throws PersistenceException {
if(getChannelStructure().isSimple()) {
setChannelTypeNonHibernate(moduleChannelPrototype.getType());
} else {
setChannelTypeNonHibernate(moduleChannelPrototype.getType().getStructure()[0]);
}
}
@Transient
@Nonnull
public String getBitPostion() {
StringBuilder sb = new StringBuilder();
if(getChannelType() == DataType.BIT) {
// if (getChannelType() == DataType.BIT && getSortIndex()>=0) {
sb.append(",B=");
sb.append(getSortIndex());
}
return sb.toString();
}
/**
*
* @return the parent {@link ModuleDBO}.
*/
@Transient
@Nonnull
public ModuleDBO getModule() {
return getChannelStructure().getModule();
}
/**
* {@inheritDoc}
* @throws PersistenceException
*/
@Override
public void update() throws PersistenceException {
localUpdate();
if(_isUpdated) {
_isUpdated = false;
}
}
/**
* {@inheritDoc}
*/
@Override
public void save() throws PersistenceException {
super.save();
_isUpdated = false;
}
/**
* @return The Name of this Node.
* @throws PersistenceException
*/
@Override
@Nonnull
public String toString() {
StringBuffer sb = new StringBuffer();
try {
sb.append(getFullChannelNumber());
sb.append(": ");
sb.append(getName());
if( (getIoName() != null) && (getIoName().length() > 0)) {
sb.append(" [" + getIoName() + "]");
}
} catch (PersistenceException e) {
sb.append("Device Database ERROR: ").append(e.getMessage());
CentralLogger.getInstance().error(this, e);
}
return sb.toString();
}
/**
* {@inheritDoc}
* @throws PersistenceException
*/
@Override
@Nonnull
public ChannelDBO copyThisTo(@Nonnull final ChannelStructureDBO parentNode) throws PersistenceException {
ChannelDBO copy = (ChannelDBO) super.copyThisTo(parentNode);
copy.setName(getName());
return copy;
}
/**
* {@inheritDoc}
* @throws PersistenceException
*/
@Override
@Nonnull
protected ChannelDBO copyParameter(@Nonnull final ChannelStructureDBO parentNode) throws PersistenceException {
ChannelStructureDBO channelStructure = parentNode;
ChannelDBO copy = new ChannelDBO(channelStructure,
getName(),
isInput(),
isDigital(),
getSortIndex());
// copy.setDocuments(getDocuments());
// copy.setChannelNumber(getChannelNumber());
copy.setChannelType(getChannelType());
copy.setCurrentValue(getCurrentValue());
copy.setCurrenUserParamDataIndex(getCurrenUserParamDataIndex());
copy.setIoName(getIoName());
return copy;
}
/**
* {@inheritDoc}
*/
@Override
@Transient
@Nonnull
public NodeType getNodeType() {
return NodeType.CHANNEL;
}
/**
* {@inheritDoc}
*/
@Override
@CheckForNull
public InvalidLeave addChild(@Nullable InvalidLeave child) throws PersistenceException {
// do nothing. Channel is the leave node.
return null;
}
}
|
package org.waterforpeople.mapping.portal.client.widgets;
import java.util.ArrayList;
import java.util.HashMap;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointDto;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointDto.AccessPointType;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointDto.Status;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointManagerService;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointManagerServiceAsync;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointSearchCriteriaDto;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.UnitOfMeasureDto;
import org.waterforpeople.mapping.app.gwt.client.accesspoint.UnitOfMeasureDto.UnitOfMeasureSystem;
import org.waterforpeople.mapping.app.gwt.client.user.UserDto;
import com.gallatinsystems.framework.gwt.component.DataTableBinder;
import com.gallatinsystems.framework.gwt.component.DataTableHeader;
import com.gallatinsystems.framework.gwt.component.DataTableListener;
import com.gallatinsystems.framework.gwt.component.PaginatedDataTable;
import com.gallatinsystems.framework.gwt.dto.client.ResponseDto;
import com.gallatinsystems.framework.gwt.util.client.MessageDialog;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.control.SmallZoomControl;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
public class AccessPointManagerPortlet extends LocationDrivenPortlet implements
DataTableBinder<AccessPointDto>, DataTableListener<AccessPointDto> {
public static final String DESCRIPTION = "Create/Edit/Delete Access Points";
public static final String NAME = "Access Point Manager";
private static final String DEFAULT_SORT_FIELD = "key";
private static final DataTableHeader HEADERS[] = {
new DataTableHeader("Id", "key", true),
new DataTableHeader("Community Code", "communityCode", true),
new DataTableHeader("Latitude", "latitude", true),
new DataTableHeader("Longitude", "longitude", true),
new DataTableHeader("Point Type", "pointType", true),
new DataTableHeader("Collection Date", "collectionDate", true),
new DataTableHeader("Edit/Delete") };
private static final String ANY_OPT = "Any";
private static final int WIDTH = 1600;
private static final int HEIGHT = 800;
private VerticalPanel contentPane;
private boolean errorMode;
// Search UI Elements
private VerticalPanel mainVPanel = new VerticalPanel();
private FlexTable searchTable = new FlexTable();
private Label accessPointTypeLabel = new Label("Access Point Type");
private ListBox accessPointTypeListBox = new ListBox();
private Label technologyTypeLabel = new Label("Technology Type");
private ListBox techTypeListBox = new ListBox();
private Button searchButton = new Button("Search");
private Button errorsButton = new Button("Show Errors");
private FlexTable accessPointFT = new FlexTable();
private AccessPointManagerServiceAsync svc;
private Label statusLabel = new Label();
private DateBox collectionDateDPLower = new DateBox();
private DateBox collectionDateDPUpper = new DateBox();
private DateBox constructionDateDPLower = new DateBox();
private DateBox constructionDateDPUpper = new DateBox();
private Button createNewAccessPoint = new Button("Create New Access Point");
private ListBox statusLB = new ListBox();
private DateTimeFormat dateFormat;
private FlexTable accessPointDetail = new FlexTable();
private PaginatedDataTable<AccessPointDto> apTable;
public AccessPointManagerPortlet(UserDto user) {
super(NAME, true, false, false, WIDTH, HEIGHT, user, true,
LocationDrivenPortlet.ANY_OPT);
contentPane = new VerticalPanel();
Widget header = buildHeader();
apTable = new PaginatedDataTable<AccessPointDto>(DEFAULT_SORT_FIELD,
this, this, true);
dateFormat = DateTimeFormat.getShortDateFormat();
contentPane.add(header);
setContent(contentPane);
errorMode = false;
svc = GWT.create(AccessPointManagerService.class);
apTable.setVisible(false);
mainVPanel.add(apTable);
}
@Override
public String getName() {
return NAME;
}
/**
* constructs and installs the menu for this portlet. Also wires in the
* event handlers so we can update on menu value change
*
* @return
*/
private Widget buildHeader() {
Grid grid = new Grid(2, 2);
configureSearchRibbon();
grid.setWidget(0, 0, mainVPanel);
searchButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
errorMode = false;
requestData(null, false);
}
});
accessPointTypeListBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
// TODO: implement on change
// configureTechTypeListBox(event);
}
});
createNewAccessPoint.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
AccessPointDto nullItem = null;
loadAccessPointDetailTable(nullItem);
}
});
this.errorsButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
errorMode = true;
requestData(null, false);
}
});
return grid;
}
private void configureSearchRibbon() {
configureDependantControls();
searchTable.setWidget(0, 0, new Label("Country"));
searchTable.setWidget(0, 1, getCountryControl());
searchTable.setWidget(0, 2, new Label("Community"));
searchTable.setWidget(0, 3, getCommunityControl());
searchTable.setWidget(1, 0, new Label("Collection Date from: "));
searchTable.setWidget(1, 1, collectionDateDPLower);
searchTable.setWidget(1, 2, new Label("to"));
searchTable.setWidget(1, 3, collectionDateDPUpper);
searchTable.setWidget(2, 0, accessPointTypeLabel);
searchTable.setWidget(2, 1, accessPointTypeListBox);
searchTable.setWidget(2, 2, technologyTypeLabel);
searchTable.setWidget(2, 3, techTypeListBox);
searchTable.setWidget(3, 0, new Label("Construction Date From: "));
searchTable.setWidget(3, 1, constructionDateDPLower);
searchTable.setWidget(3, 2, constructionDateDPUpper);
searchTable.setWidget(4, 0, searchButton);
searchTable.setWidget(4, 1, createNewAccessPoint);
searchTable.setWidget(4, 2, errorsButton);
mainVPanel.add(searchTable);
}
private void configureDependantControls() {
configureAccessPointListBox();
configureTechnologyType();
}
private void configureTechnologyType() {
}
private void configureAccessPointListBox() {
accessPointTypeListBox.addItem("Water Point",
AccessPointType.WATER_POINT.toString());
accessPointTypeListBox.addItem("Sanitation Point",
AccessPointType.SANITATION_POINT.toString());
accessPointTypeListBox.addItem("Public Institution",
AccessPointType.PUBLIC_INSTITUTION.toString());
accessPointTypeListBox.addItem("School",
AccessPointType.SCHOOL.toString());
}
/**
* constructs a search criteria object using values from the form
*
* @return
*/
private AccessPointSearchCriteriaDto formSearchCriteria() {
AccessPointSearchCriteriaDto dto = new AccessPointSearchCriteriaDto();
dto.setCommunityCode(getSelectedCommunity());
dto.setCountryCode(getSelectedCountry());
dto.setCollectionDateFrom(collectionDateDPLower.getValue());
dto.setCollectionDateTo(collectionDateDPUpper.getValue());
dto.setConstructionDateFrom(constructionDateDPLower.getValue());
dto.setConstructionDateTo(constructionDateDPUpper.getValue());
dto.setPointType(getSelectedValue(accessPointTypeListBox));
dto.setOrderBy(apTable.getCurrentSortField());
dto.setOrderByDir(apTable.getCurrentSortDirection());
return dto;
}
private void loadAccessPointDetailTable(Long id) {
apTable.setVisible(false);
statusLabel.setText("Please wait loading access point for edit");
statusLabel.setVisible(true);
mainVPanel.add(statusLabel);
svc.getAccessPoint(id, new AsyncCallback<AccessPointDto>() {
@Override
public void onFailure(Throwable caught) {
MessageDialog errDia = new MessageDialog(
"Error loading details",
"The application could not load the access point details. Please try again. If the problem persists, contact an administrator.");
errDia.showRelativeTo(searchTable);
}
@Override
public void onSuccess(AccessPointDto result) {
AccessPointDto item = (AccessPointDto) result;
loadAccessPointDetailTable(item);
}
});
}
private HashMap<String, String> fieldsMap = new HashMap<String, String>();
private TabPanel loadTabs(AccessPointDto accessPointDto) {
TabPanel tp = new TabPanel();
tp.add(loadGeneralTab(accessPointDto), "General");
tp.add(loadMediaTab(accessPointDto), "Media");
tp.add(loadAttributeTab(accessPointDto), "Attributes");
tp.selectTab(0);
return tp;
}
private FlexTable loadMediaTab(AccessPointDto accessPointDto) {
final FlexTable accessPointDetail = new FlexTable();
accessPointDetail.setWidget(10, 0, new Label("Photo Url: "));
TextBox photoURLTB = new TextBox();
photoURLTB.setWidth("500px");
FormPanel form = new FormPanel();
form.setMethod(FormPanel.METHOD_POST);
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setAction("/webapp/photoupload");
FileUpload upload = new FileUpload();
form.setWidget(upload);
accessPointDetail.setWidget(10, 3, form);
Button submitUpload = new Button("Upload");
upload.setName("uploadFormElement");
accessPointDetail.setWidget(10, 4, submitUpload);
form.addSubmitHandler(new SubmitHandler() {
@Override
public void onSubmit(SubmitEvent event) {
// no-op
}
});
form.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert("File uploaded");
String fileName = ((FileUpload) ((FormPanel) accessPointDetail
.getWidget(10, 3)).getWidget()).getFilename();
if (fileName.contains("/")) {
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
}
if (fileName.contains("\\")) {
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
}
((TextBox) accessPointDetail.getWidget(10, 1))
.setText("http://waterforpeople.s3.amazonaws.com/images/"
+ fileName);
Image i = ((Image) accessPointDetail.getWidget(11, 1));
i.setHeight("200px");
if (i == null) {
Image photo = new Image();
photo.setUrl("http://waterforpeople.s3.amazonaws.com/images/"
+ fileName);
photo.setHeight("200px");
accessPointDetail.setWidget(11, 1, photo);
} else {
i.setUrl("http://waterforpeople.s3.amazonaws.com/images/"
+ fileName);
}
}
});
submitUpload.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
((FormPanel) accessPointDetail.getWidget(10, 3)).submit();
}
});
if (accessPointDto != null) {
photoURLTB.setText(accessPointDto.getPhotoURL());
Image photo = new Image(accessPointDto.getPhotoURL() + "?random="
+ Random.nextInt());
accessPointDetail.setWidget(11, 1, photo);
photo.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
((Image) accessPointDetail.getWidget(11, 1))
.setVisible(false);
accessPointDetail.setWidget(10, 4, new Label(
"Please wait while image is rotated 90 Degrees"));
svc.rotateImage(((TextBox) accessPointDetail.getWidget(10,
1)).getText(), new AsyncCallback<byte[]>() {
@Override
public void onFailure(Throwable caught) {
// no-op
}
@Override
public void onSuccess(byte[] result) {
Integer random = Random.nextInt();
Image photo = ((Image) accessPointDetail.getWidget(
11, 1));
accessPointDetail.getWidget(10, 4)
.setVisible(false);
photo.setUrl(((TextBox) accessPointDetail
.getWidget(11, 1)).getText()
+ "?random="
+ random);
photo.setVisible(true);
}
});
}
});
}
accessPointDetail.setWidget(10, 1, photoURLTB);
accessPointDetail.setWidget(12, 0, new Label("Photo Caption: "));
TextArea captionTB = new TextArea();
captionTB.setWidth("500px");
captionTB.setHeight("200px");
if (accessPointDto != null)
captionTB.setText(accessPointDto.getPointPhotoCaption());
accessPointDetail.setWidget(12, 1, captionTB);
Label apId;
if (accessPointDto != null) {
apId = new Label(accessPointDto.getKeyId().toString());
} else {
apId = new Label("-1");
}
apId.setVisible(false);
accessPointDetail.setWidget(15, 1, apId);
return accessPointDetail;
}
private FlexTable loadGeneralTab(AccessPointDto accessPointDto) {
FlexTable accessPointDetail = new FlexTable();
accessPointDetail.setWidget(0, 0, new Label("Community Code: "));
TextBox communityCodeTB = new TextBox();
if (accessPointDto != null) {
communityCodeTB.setText(accessPointDto.getCommunityCode());
}
accessPointDetail.setWidget(0, 1, communityCodeTB);
accessPointDetail.setWidget(1, 0, new Label("Country Code: "));
TextBox countryCodeTB = new TextBox();
if (accessPointDto != null) {
countryCodeTB.setText(accessPointDto.getCountryCode());
}
accessPointDetail.setWidget(1, 1, countryCodeTB);
accessPointDetail.setWidget(2, 0, new Label("Latititude: "));
TextBox latitudeTB = new TextBox();
if (accessPointDto != null)
latitudeTB.setText(accessPointDto.getLatitude().toString());
accessPointDetail.setWidget(2, 1, latitudeTB);
accessPointDetail.setWidget(3, 0, new Label("Longitude: "));
TextBox longitudeTB = new TextBox();
if (accessPointDto != null)
longitudeTB.setText(accessPointDto.getLongitude().toString());
accessPointDetail.setWidget(3, 1, longitudeTB);
if (accessPointDto != null && accessPointDto.getLatitude() != null
&& accessPointDto.getLongitude() != null) {
MapWidget map = new MapWidget();
map.setSize("180px", "180px");
map.addControl(new SmallZoomControl());
LatLng point = LatLng.newInstance(accessPointDto.getLatitude(),
accessPointDto.getLongitude());
map.addOverlay(new Marker(point));
map.setZoomLevel(12);
map.setCenter(point);
accessPointDetail.setWidget(0, 2, map);
accessPointDetail.getFlexCellFormatter().setRowSpan(0, 2, 5);
}
accessPointDetail.setWidget(4, 0, new Label("Collection Date: "));
DateBox pickerCollectionDate = new DateBox();
if (accessPointDto != null)
pickerCollectionDate.setValue(accessPointDto.getCollectionDate());
accessPointDetail.setWidget(4, 1, pickerCollectionDate);
accessPointDetail.setWidget(5, 0, new Label("Point Construction Date"));
DateBox pickerConstructionDate = new DateBox();
if (accessPointDto != null)
pickerConstructionDate.setValue(accessPointDto
.getConstructionDate());
accessPointDetail.setWidget(5, 1, pickerConstructionDate);
Label apId;
if (accessPointDto != null) {
apId = new Label(accessPointDto.getKeyId().toString());
} else {
apId = new Label("-1");
}
apId.setVisible(false);
accessPointDetail.setWidget(15, 1, apId);
return accessPointDetail;
}
private FlexTable loadAttributeTab(AccessPointDto accessPointDto) {
FlexTable accessPointDetail = new FlexTable();
accessPointDetail.setWidget(6, 0, new Label("Cost Per: "));
TextBox costPerTB = new TextBox();
if (accessPointDto != null && accessPointDto.getCostPer() != null)
costPerTB.setText(accessPointDto.getCostPer().toString());
accessPointDetail.setWidget(6, 1, costPerTB);
ListBox unitOfMeasureLB = new ListBox();
unitOfMeasureLB.addItem("ml");
unitOfMeasureLB.addItem("liters");
unitOfMeasureLB.addItem("ounces");
unitOfMeasureLB.addItem("gallons");
accessPointDetail.setWidget(6, 2, unitOfMeasureLB);
accessPointDetail.setWidget(7, 0, new Label(
"Current Management Structure: "));
TextBox currentMgmtStructureTB = new TextBox();
if (accessPointDto != null)
currentMgmtStructureTB.setText(accessPointDto
.getCurrentManagementStructurePoint());
accessPointDetail.setWidget(7, 1, currentMgmtStructureTB);
accessPointDetail.setWidget(8, 0, new Label("Description: "));
TextBox descTB = new TextBox();
if (accessPointDto != null)
descTB.setText(accessPointDto.getDescription());
accessPointDetail.setWidget(8, 1, descTB);
accessPointDetail.setWidget(9, 0, new Label(
"Number of Households using Point: "));
TextBox numHouseholdsTB = new TextBox();
if (accessPointDto != null
&& accessPointDto.getNumberOfHouseholdsUsingPoint() != null)
numHouseholdsTB.setText(accessPointDto
.getNumberOfHouseholdsUsingPoint().toString());
accessPointDetail.setWidget(9, 1, numHouseholdsTB);
accessPointDetail.setWidget(12, 0, new Label("Point Status: "));
statusLB = new ListBox();
statusLB.addItem("Functioning High");
statusLB.addItem("Functioning Ok");
statusLB.addItem("Functioning but with Problems");
statusLB.addItem("No Improved System");
statusLB.addItem("Other");
if (accessPointDto != null) {
AccessPointDto.Status pointStatus = accessPointDto.getPointStatus();
if (pointStatus.equals(AccessPointDto.Status.FUNCTIONING_HIGH)) {
statusLB.setSelectedIndex(0);
} else if (pointStatus.equals(AccessPointDto.Status.FUNCTIONING_OK)) {
statusLB.setSelectedIndex(1);
} else if (pointStatus
.equals(AccessPointDto.Status.FUNCTIONING_WITH_PROBLEMS)) {
statusLB.setSelectedIndex(2);
} else if (pointStatus
.equals(AccessPointDto.Status.NO_IMPROVED_SYSTEM)) {
statusLB.setSelectedIndex(3);
} else {
statusLB.setSelectedIndex(4);
}
}
accessPointDetail.setWidget(12, 1, statusLB);
accessPointDetail.setWidget(13, 0, new Label("Point Type: "));
ListBox pointType = new ListBox();
pointType
.addItem("Water Point", AccessPointType.WATER_POINT.toString());
pointType.addItem("Sanitation Point",
AccessPointType.SANITATION_POINT.toString());
pointType.addItem("Public Institution",
AccessPointType.PUBLIC_INSTITUTION.toString());
pointType.addItem("School", AccessPointType.SCHOOL.toString());
if (accessPointDto != null) {
AccessPointType apType = accessPointDto.getPointType();
if (apType.equals(AccessPointType.WATER_POINT)) {
pointType.setSelectedIndex(0);
} else if (apType.equals(AccessPointType.SANITATION_POINT)) {
pointType.setSelectedIndex(1);
} else if (apType.equals(AccessPointType.PUBLIC_INSTITUTION)) {
pointType.setSelectedIndex(2);
} else if (apType.equals(AccessPointType.SCHOOL)) {
pointType.setSelectedIndex(3);
}
} else {
pointType.setSelectedIndex(0);
}
accessPointDetail.setWidget(13, 1, pointType);
accessPointDetail.setWidget(14, 0, new Label("Farthest Point From"));
TextBox farthestPointFromTB = new TextBox();
if (accessPointDto != null)
farthestPointFromTB.setText(accessPointDto
.getFarthestHouseholdfromPoint());
accessPointDetail.setWidget(14, 1, farthestPointFromTB);
Label apId;
if (accessPointDto != null) {
apId = new Label(accessPointDto.getKeyId().toString());
} else {
apId = new Label("-1");
}
apId.setVisible(false);
accessPointDetail.setWidget(15, 1, apId);
accessPointDetail.setWidget(16, 0, new Label("SMS Code"));
TextBox smsCode = new TextBox();
if (accessPointDto != null)
smsCode.setText(accessPointDto.getSmsCode());
accessPointDetail.setWidget(16, 1, smsCode);
return accessPointDetail;
}
private void loadAccessPointDetailTable(AccessPointDto accessPointDto) {
apTable.setVisible(false);
// if(accessPointDto.getPointType().toString()!=null){
// type = accessPointDto.getPointType().toString();
// pointTypeTB.setText(type);
// accessPointDetail.setWidget(12, 1, pointTypeTB);
statusLabel.setText("Done loading access point");
statusLabel.setVisible(false);
mainVPanel.remove(statusLabel);
Button saveButton = new Button("Save");
saveButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (validateAccessPointDetail()) {
statusLabel.setVisible(true);
statusLabel.setText("Please wait saving access point");
mainVPanel.add(statusLabel);
AccessPointDto apDto = buildAccessPointDto();
svc.saveAccessPoint(apDto,
new AsyncCallback<AccessPointDto>() {
@Override
public void onFailure(Throwable caught) {
MessageDialog errDialog = new MessageDialog(
"Error while saving",
"Could not save. Please try again. If the problem persists, contact an administrator");
errDialog.showRelativeTo(mainVPanel);
}
@Override
public void onSuccess(AccessPointDto result) {
Window.alert("Access Point successfully updated");
}
});
accessPointDetail.setVisible(false);
statusLabel.setVisible(false);
mainVPanel.remove(statusLabel);
accessPointFT.setVisible(true);
}
}
});
Button cancelButton = new Button("Cancel");
cancelButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Boolean ok = Window.confirm("Any changes made will be lost");
if (ok) {
accessPointDetail.setVisible(false);
statusLabel.setVisible(false);
mainVPanel.remove(statusLabel);
accessPointFT.setVisible(true);
}
}
});
accessPointDetail.setWidget(1, 0, loadTabs(accessPointDto));
HorizontalPanel hButtonPanel = new HorizontalPanel();
hButtonPanel.add(saveButton);
hButtonPanel.add(cancelButton);
accessPointDetail.setWidget(17, 0, hButtonPanel);
// accessPointDetail.setWidget(17, 0, saveButton);
// accessPointDetail.setWidget(17, 1, cancelButton);
accessPointDetail.setVisible(true);
mainVPanel.add(accessPointDetail);
// mainVPanel.add(this.loadTabs(accessPointDto));
}
private AccessPointDto buildAccessPointDto() {
AccessPointDto apDto = new AccessPointDto();
TabPanel tp = (TabPanel) accessPointDetail.getWidget(1, 0);
FlexTable accessPointDetail = (FlexTable) tp.getWidget(0);
apDto = getGeneralAP(apDto, accessPointDetail);
accessPointDetail =(FlexTable)tp.getWidget(1);
apDto = getMediaAP(apDto,accessPointDetail);
accessPointDetail = (FlexTable)tp.getWidget(2);
apDto = getAttributeAP(apDto,accessPointDetail);
return apDto;
}
private AccessPointDto getGeneralAP(AccessPointDto apDto, FlexTable accessPointDetail){
Label apId = (Label) accessPointDetail.getWidget(15, 1);
Long id = new Long(apId.getText());
if (id > -1) {
apDto.setKeyId(id);
} else {
apDto.setKeyId(null);
}
TextBox communityCodeTB = (TextBox) accessPointDetail.getWidget(0, 1);
String communityCode = communityCodeTB.getText();
apDto.setCommunityCode(communityCode);
TextBox countryCodeTB = (TextBox) accessPointDetail.getWidget(1, 1);
String countryCode = countryCodeTB.getText();
apDto.setCountryCode(countryCode);
TextBox latitudeTB = (TextBox) accessPointDetail.getWidget(2, 1);
Double latitude = new Double(latitudeTB.getText());
apDto.setLatitude(latitude);
TextBox longitudeTB = (TextBox) accessPointDetail.getWidget(3, 1);
Double longitude = new Double(longitudeTB.getText());
apDto.setLongitude(longitude);
DateBox collectionDateTB = (DateBox) accessPointDetail.getWidget(4, 1);
apDto.setCollectionDate(collectionDateTB.getValue());
DateBox constructionDateTB = (DateBox) accessPointDetail
.getWidget(5, 1);
apDto.setConstructionDate(constructionDateTB.getValue());
return apDto;
}
private AccessPointDto getMediaAP(AccessPointDto apDto,FlexTable accessPointDetail){
TextBox photoURLTB = (TextBox) accessPointDetail.getWidget(10, 1);
String photoUrl = photoURLTB.getText();
apDto.setPhotoURL(photoUrl);
TextArea captionTB = (TextArea) accessPointDetail.getWidget(12, 1);
String caption = captionTB.getText();
apDto.setPointPhotoCaption(caption);
return apDto;
}
private AccessPointDto getAttributeAP(AccessPointDto apDto,FlexTable accessPointDetail){
TextBox costPerTB = (TextBox) accessPointDetail.getWidget(6, 1);
String costPerTemp = costPerTB.getText();
if (costPerTemp != null && costPerTemp.length() > 0) {
Double costPer = new Double(costPerTB.getText());
apDto.setCostPer(costPer);
}
ListBox unitOfMeasureLB = (ListBox) accessPointDetail.getWidget(6, 2);
if (unitOfMeasureLB.getSelectedIndex() == 0) {
UnitOfMeasureDto uom = new UnitOfMeasureDto();
uom.setSystem(UnitOfMeasureSystem.METRIC);
uom.setCode("ml");
apDto.setCostPerUnitOfMeasure(uom);
} else if (unitOfMeasureLB.getSelectedIndex() == 1) {
// liters
UnitOfMeasureDto uom = new UnitOfMeasureDto();
uom.setSystem(UnitOfMeasureSystem.METRIC);
uom.setCode("l");
apDto.setCostPerUnitOfMeasure(uom);
} else if (unitOfMeasureLB.getSelectedIndex() == 2) {
UnitOfMeasureDto uom = new UnitOfMeasureDto();
uom.setSystem(UnitOfMeasureSystem.IMPERIAL);
uom.setCode("oz");
apDto.setCostPerUnitOfMeasure(uom);
// /ounces
} else {
// gallons
UnitOfMeasureDto uom = new UnitOfMeasureDto();
uom.setSystem(UnitOfMeasureSystem.IMPERIAL);
uom.setCode("g");
apDto.setCostPerUnitOfMeasure(uom);
}
TextBox currentMgmtStructureTB = (TextBox) accessPointDetail.getWidget(
7, 1);
String currentMgmtStructure = currentMgmtStructureTB.getText();
apDto.setCurrentManagementStructurePoint(currentMgmtStructure);
TextBox descTB = (TextBox) accessPointDetail.getWidget(8, 1);
String desc = descTB.getText();
apDto.setDescription(desc);
TextBox numHouseholdsTB = (TextBox) accessPointDetail.getWidget(9, 1);
String numHouseholds = numHouseholdsTB.getText();
if (numHouseholds != null && numHouseholds.trim().length() > 0) {
try {
apDto.setNumberOfHouseholdsUsingPoint(new Long(numHouseholds
.trim()));
} catch (NumberFormatException e) {
// to-do: display validation error
}
}
ListBox statusLB = (ListBox) accessPointDetail.getWidget(12, 1);
if (statusLB.getSelectedIndex() == 0) {
apDto.setPointStatus(AccessPointDto.Status.FUNCTIONING_HIGH);
} else if (statusLB.getSelectedIndex() == 1) {
apDto.setPointStatus(Status.FUNCTIONING_OK);
} else if (statusLB.getSelectedIndex() == 2) {
apDto.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
} else if (statusLB.getSelectedIndex() == 3) {
apDto.setPointStatus(Status.NO_IMPROVED_SYSTEM);
} else {
apDto.setPointStatus(Status.OTHER);
}
ListBox pointTypeLB = (ListBox) accessPointDetail.getWidget(13, 1);
Integer selectedIndex = pointTypeLB.getSelectedIndex();
String type = pointTypeLB.getItemText(selectedIndex);
if (type.equals("Water Point")) {
apDto.setPointType(AccessPointType.WATER_POINT);
} else if (type.equals("Sanitation Point")) {
apDto.setPointType(AccessPointType.SANITATION_POINT);
} else if (type.equals("Public Institution")) {
apDto.setPointType(AccessPointType.PUBLIC_INSTITUTION);
} else if (type.equals("School")) {
apDto.setPointType(AccessPointType.SCHOOL);
}
TextBox farthestPointFromTB = (TextBox) accessPointDetail.getWidget(14,
1);
String farthestPointFrom = farthestPointFromTB.getText();
apDto.setFarthestHouseholdfromPoint(farthestPointFrom);
TextBox smsCodeTB = (TextBox) accessPointDetail.getWidget(16, 1);
String smsCode = smsCodeTB.getText();
apDto.setSmsCode(smsCode);
return apDto;
}
public Boolean validateAccessPointDetail() {
return true;
}
/**
* helper method to get value out of a listbox. If "Any" is selected, it's
* translated to null since the service expects null to be passed in rather
* than "all" if you don't want to filter by that param
*
* @param lb
* @return
*/
private String getSelectedValue(ListBox lb) {
if (lb.getSelectedIndex() >= 0) {
String val = lb.getValue(lb.getSelectedIndex());
if (ANY_OPT.equals(val)) {
return null;
} else {
return val;
}
} else {
return null;
}
}
@Override
public void bindRow(Grid grid, AccessPointDto apDto, int row) {
Label keyIdLabel = new Label(apDto.getKeyId().toString());
grid.setWidget(row, 0, keyIdLabel);
if (apDto.getCommunityCode() != null) {
String communityCode = apDto.getCommunityCode();
if (communityCode.length() > 10)
communityCode = communityCode.substring(0, 10);
grid.setWidget(row, 1, new Label(communityCode));
}
if (apDto.getLatitude() != null && apDto.getLongitude() != null) {
grid.setWidget(row, 2, new Label(apDto.getLatitude().toString()));
grid.setWidget(row, 3, new Label(apDto.getLongitude().toString()));
}
if (apDto.getPointType() != null) {
grid.setWidget(row, 4, new Label(apDto.getPointType().name()));
}
if (apDto.getCollectionDate() != null) {
grid.setWidget(row, 5,
new Label(dateFormat.format(apDto.getCollectionDate())));
}
Button editAccessPoint = new Button("edit");
editAccessPoint.setTitle(keyIdLabel.getText());
Button deleteAccessPoint = new Button("delete");
deleteAccessPoint.setTitle(keyIdLabel.getText());
HorizontalPanel buttonHPanel = new HorizontalPanel();
buttonHPanel.add(editAccessPoint);
buttonHPanel.add(deleteAccessPoint);
editAccessPoint.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Button pressedButton = (Button) event.getSource();
Long itemId = new Long(pressedButton.getTitle());
loadAccessPointDetailTable(itemId);
}
});
deleteAccessPoint.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Button pressedButton = (Button) event.getSource();
Window.alert("delete key id: " + pressedButton.getTitle());
}
});
grid.setWidget(row, 6, buttonHPanel);
}
@Override
public DataTableHeader[] getHeaders() {
return HEADERS;
}
@Override
public void onItemSelected(AccessPointDto item) {
// no-op
}
@Override
public void requestData(String cursor, final boolean isResort) {
accessPointDetail.setVisible(false);
final boolean isNew = (cursor == null);
final AccessPointSearchCriteriaDto searchDto = formSearchCriteria();
boolean isOkay = true;
AsyncCallback<ResponseDto<ArrayList<AccessPointDto>>> dataCallback = new AsyncCallback<ResponseDto<ArrayList<AccessPointDto>>>() {
@Override
public void onFailure(Throwable caught) {
MessageDialog errDia = new MessageDialog("Application Error",
"Cannot search");
errDia.showRelativeTo(searchTable);
}
@Override
public void onSuccess(ResponseDto<ArrayList<AccessPointDto>> result) {
apTable.bindData(result.getPayload(), result.getCursorString(),
isNew, isResort);
if (result.getPayload() != null
&& result.getPayload().size() > 0) {
apTable.setVisible(true);
if (!errorMode) {
Button exportButton = new Button("Export to Excel");
apTable.appendRow(exportButton);
exportButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String appletString = "<applet width='100' height='30' code=com.gallatinsystems.framework.dataexport.applet.DataExportAppletImpl width=256 height=256 archive='exporterapplet.jar,json.jar'>";
appletString += "<PARAM name='cache-archive' value='exporterapplet.jar, json.jar'><PARAM name='cache-version' value'1.3, 1.0'>";
appletString += "<PARAM name='exportType' value='ACCESS_POINT'>";
appletString += "<PARAM name='factoryClass' value='org.waterforpeople.mapping.dataexport.SurveyDataImportExportFactory'>";
AccessPointSearchCriteriaDto crit = formSearchCriteria();
if (crit != null) {
appletString += "<PARAM name='criteria' value='"
+ crit.toDelimitedString() + "'>";
}
appletString += "</applet>";
HTML html = new HTML();
html.setHTML(appletString);
apTable.appendRow(html);
}
});
}
}
}
};
if (!errorMode) {
if (searchDto != null) {
if (searchDto.getCollectionDateFrom() != null
|| searchDto.getCollectionDateTo() != null) {
if (searchDto.getConstructionDateFrom() != null
|| searchDto.getConstructionDateTo() != null) {
MessageDialog errDia = new MessageDialog(
"Invalid search criteria",
"Sorry, only one date range can be selected for a search at a time. If you specify collection date, you cannot also specify a construction date. Please change the criteria and retry your search");
errDia.showRelativeTo(searchTable);
isOkay = false;
}
if (isOkay) {
if (searchDto.getCollectionDateFrom() != null
|| searchDto.getCollectionDateTo() != null) {
if (isResort) {
if (!"collectionDate".equals(apTable
.getCurrentSortField())) {
MessageDialog errDia = new MessageDialog(
"Invalid sort criteria",
"Sorry, when searching using Collection Date, you cannot sort by any column except Collection Date.");
errDia.showRelativeTo(searchTable);
isOkay = false;
}
} else {
apTable.overrideSort("collectionDate",
PaginatedDataTable.DSC_SORT);
}
}
if (searchDto.getConstructionDateFrom() != null
|| searchDto.getConstructionDateTo() != null) {
if (isResort) {
if (!"constructionDate".equals(apTable
.getCurrentSortField())) {
MessageDialog errDia = new MessageDialog(
"Invalid sort criteria",
"Sorry, when searching using Collection Date, you cannot sort by any column except Collection Date.");
errDia.showRelativeTo(searchTable);
isOkay = false;
}
} else {
apTable.overrideSort("constructionDate",
PaginatedDataTable.DSC_SORT);
}
}
searchDto.setOrderBy(apTable.getCurrentSortField());
searchDto.setOrderByDir(apTable
.getCurrentSortDirection());
}
}
}
if (isOkay) {
svc.listAccessPoints(searchDto, cursor, dataCallback);
}
} else {
svc.listErrorAccessPoints(cursor, dataCallback);
}
}
}
|
package com.terradue.dsione;
import static com.google.inject.Guice.createInjector;
import static com.google.inject.name.Names.named;
import static java.lang.Runtime.getRuntime;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.getProperty;
import static java.lang.System.setProperty;
import static org.nnsoft.guice.rocoto.Rocoto.expandVariables;
import static org.slf4j.LoggerFactory.getILoggerFactory;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import org.nnsoft.guice.rocoto.configuration.ConfigurationModule;
import org.slf4j.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.terradue.dsione.restclient.RestClientModule;
abstract class BaseTool
extends ConfigurationModule
implements Tool
{
@Parameter( names = { "-h", "--help" }, description = "Display help information." )
private boolean printHelp;
@Parameter( names = { "-v", "--version" }, description = "Display version information." )
private boolean showVersion;
@Parameter( names = { "-X", "--debug" }, description = "Produce execution debug output." )
private boolean debug;
@Parameter( names = { "-H", "--host" }, description = "The DSI web service URI." )
protected String serviceHost = "testcloud.t-systems.com";
@Parameter( names = { "-u", "--username" }, description = "The DSI account username." )
private String username;
@Parameter( names = { "-p", "--password" }, description = "The DSI account password." )
private String password;
private File dsiCertificate;
@Override
public final int execute( String... args )
{
final JCommander commander = new JCommander( this );
commander.setProgramName( getProperty( "app.name" ) );
commander.parse( args );
if ( printHelp )
{
commander.usage();
return -1;
}
if ( showVersion )
{
printVersionInfo();
return -1;
}
if ( debug )
{
setProperty( "log.level", "DEBUG" );
}
else
{
setProperty( "log.level", "INFO" );
}
// assume SLF4J is bound to logback in the current environment
final LoggerContext lc = (LoggerContext) getILoggerFactory();
try
{
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext( lc );
// the context was probably already configured by default configuration
// rules
lc.reset();
configurator.doConfigure( getClass().getClassLoader().getResourceAsStream( "logback-config.xml" ) );
}
catch ( JoranException je )
{
// StatusPrinter should handle this
}
// validation
if ( username == null )
{
return printAndExit( "DSI Username not specified. Please type `%s -h` for the usage." );
}
if ( password == null )
{
return printAndExit( "DSI Password not specified. Please type `%s -h` for the usage." );
}
dsiCertificate = new File( getProperty( "basedir" ), format( "certs/%s.pem", username ) );
if ( !dsiCertificate.exists() )
{
return printAndExit( "DSI certificate %s does not exist, put %s.pem certificate under %s/certs directory",
dsiCertificate, username, getProperty( "basedir" ) );
}
Logger logger = getLogger( getClass() );
logger.info( "" );
logger.info( "
logger.info( "DSI-ONE: {}", getProperty( "app.name" ) );
logger.info( "
logger.info( "" );
long start = currentTimeMillis();
int exit = 0;
Throwable error = null;
try
{
createInjector( expandVariables( this ), new RestClientModule() ).injectMembers( this );
execute();
}
catch ( Throwable t )
{
exit = -1;
error = t;
}
finally
{
logger.info( "" );
logger.info( "
logger.info( "{} {}", getProperty( "app.name" ), ( exit < 0 ) ? "FAILURE" : "SUCCESS" );
if ( exit < 0 )
{
logger.info( "" );
if ( debug )
{
logger.error( "Execution terminated with errors", error );
}
else
{
logger.error( "Execution terminated with errors: {}", error.getMessage() );
}
logger.info( "" );
}
logger.info( "Total time: {}s", ( ( currentTimeMillis() - start ) / 1000 ) );
logger.info( "Finished at: {}", new Date() );
final Runtime runtime = getRuntime();
final int megaUnit = 1024 * 1024;
logger.info( "Final Memory: {}M/{}M", ( runtime.totalMemory() - runtime.freeMemory() ) / megaUnit,
runtime.totalMemory() / megaUnit );
logger.info( "
}
return exit;
}
protected abstract void execute()
throws Exception;
@Override
protected final void bindConfigurations()
{
bindSystemProperties();
// commons settings
bindProperty( "dsi.username" ).toValue( username );
bindProperty( "dsi.password" ).toValue( password );
bindProperty( "service.host" ).toValue( serviceHost );
bindProperty( "service.url" ).toValue( "https://${service.host}/services/api" );
// services
bindProperty( "service.appliances" ).toValue( "${service.url}/appliances" );
bindProperty( "service.upload" ).toValue( "${service.appliances}/uploadTicket" );
bindProperty( "service.deployments" ).toValue( "${service.url}/deployments" );
bindProperty( "service.accounts" ).toValue( "${service.url}/accounts" );
// certificate
bind( File.class ).annotatedWith( named( "user.certificate" ) ).toInstance( dsiCertificate );
}
private static int printAndExit( String messageTemplate, Object...args )
{
System.out.printf( messageTemplate, args );
return -1;
}
private static void printVersionInfo()
{
Properties properties = new Properties();
InputStream input = BaseTool.class.getClassLoader().getResourceAsStream( "META-INF/maven/com.terradue/ondsi-tools/pom.properties" );
if ( input != null )
{
try
{
properties.load( input );
}
catch ( IOException e )
{
// ignore, just don't load the properties
}
finally
{
try
{
input.close();
}
catch ( IOException e )
{
// close quietly
}
}
}
System.out.printf( "%s %s (%s)%n",
properties.getProperty( "name" ),
properties.getProperty( "version" ),
properties.getProperty( "build" ) );
System.out.printf( "Java version: %s, vendor: %s%n",
getProperty( "java.version" ),
getProperty( "java.vendor" ) );
System.out.printf( "Java home: %s%n", getProperty( "java.home" ) );
System.out.printf( "Default locale: %s_%s, platform encoding: %s%n",
getProperty( "user.language" ),
getProperty( "user.country" ),
getProperty( "sun.jnu.encoding" ) );
System.out.printf( "OS name: \"%s\", version: \"%s\", arch: \"%s\", family: \"%s\"%n",
getProperty( "os.name" ),
getProperty( "os.version" ),
getProperty( "os.arch" ),
getOsFamily() );
}
private static final String getOsFamily()
{
String osName = getProperty( "os.name" ).toLowerCase();
String pathSep = getProperty( "path.separator" );
if ( osName.indexOf( "windows" ) != -1 )
{
return "windows";
}
else if ( osName.indexOf( "os/2" ) != -1 )
{
return "os/2";
}
else if ( osName.indexOf( "z/os" ) != -1 || osName.indexOf( "os/390" ) != -1 )
{
return "z/os";
}
else if ( osName.indexOf( "os/400" ) != -1 )
{
return "os/400";
}
else if ( pathSep.equals( ";" ) )
{
return "dos";
}
else if ( osName.indexOf( "mac" ) != -1 )
{
if ( osName.endsWith( "x" ) )
{
return "mac"; // MACOSX
}
return "unix";
}
else if ( osName.indexOf( "nonstop_kernel" ) != -1 )
{
return "tandem";
}
else if ( osName.indexOf( "openvms" ) != -1 )
{
return "openvms";
}
else if ( pathSep.equals( ":" ) )
{
return "unix";
}
return "undefined";
}
}
|
package com.thaze.peakmatch.processors;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.thaze.peakmatch.EventProcessorConf;
import com.thaze.peakmatch.Util;
import com.thaze.peakmatch.XCorrProcessor;
import com.thaze.peakmatch.event.BasicEvent;
import com.thaze.peakmatch.event.Event;
import com.thaze.peakmatch.event.EventException;
import com.thaze.peakmatch.event.EventPair;
import com.thaze.peakmatch.event.MapCollector;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author srodgers
* created: 14/06/13
*/
public class AnalyseProcessor implements Processor {
private final EventProcessorConf _conf;
@Override
public void process() throws EventException {
analyseAccuracy();
analysePerformance();
}
public AnalyseProcessor(EventProcessorConf conf) throws EventException {
_conf = conf;
}
private void analyseAccuracy() throws EventException {
List<Event> events = loadSampleEvents();
System.out.println("found " + _conf.countAllEvents() + " full events");
MapCollector candidates = new MapCollector();
MapCollector rejections = new MapCollector();
PeakMatchRunner.peakmatchCandidates(_conf, events, candidates, rejections);
Map<String, Double> full = loadSampleXCorr(events);
Map<String, Double> fullAboveThreshold = reduceToFinalThreshold(full);
System.out.println();
System.out.println("*** Accuracy analysis ***");
System.out.println(events.size() + " events sampled -> " + (long)events.size()*(long)events.size()/2 + " distinct pairs");
System.out.println(fullAboveThreshold.size() + " definite XCorr event pairs above final threshold");
System.out.println(candidates.size() + " candidates found above candidate threshold");
if (fullAboveThreshold.isEmpty())
System.out.println("no matches found in full xcorr");
else {
System.out.println();
System.out.println("=== false positives ===");
Set<String> falsePositives = Sets.newHashSet(candidates.keySet());
falsePositives.removeAll(fullAboveThreshold.keySet());
System.out.println(falsePositives.size() + " (" + 100*falsePositives.size()/fullAboveThreshold.size() + "% of " + fullAboveThreshold.size() + ") false positives (higher = more post-process required)");
if (_conf.isVerbose()){
for (String fp: falsePositives)
System.out.println(fp + "\t candidate xcorr: " + Util.NF.format(candidates.get(fp)) + ", real xcorr: " + full.get(fp));
}
System.out.println();
System.out.println("=== false negatives ===");
Set<String> falseNegatives = Sets.newHashSet(fullAboveThreshold.keySet());
falseNegatives.removeAll(candidates.keySet());
System.out.println(falseNegatives.size() + " (" + 100*falseNegatives.size()/fullAboveThreshold.size() + "% of " + fullAboveThreshold.size() + ") false negatives (higher = more missed events)");
if (_conf.isVerbose()){
for (String fn: falseNegatives)
System.out.println(fn + "\t real xcorr: " + fullAboveThreshold.get(fn) + ", candidate xcorr: " + rejections.get(fn));
}
}
System.out.println();
System.out.println("*** Accuracy analysis completed ***");
}
private void analysePerformance() throws EventException {
List<Event> events = loadSampleEvents();
System.out.println();
System.out.println("*** Performance analysis ***");
MapCollector candidates = new MapCollector();
final long samplePairs = (long)events.size()*(long)events.size()/2;
final long allPairs = (long)_conf.countAllEvents()*(long)_conf.countAllEvents()/2;
long extrapolatedForAllMS;
{
System.out.println();
System.out.println("=== Peakmatch phase ===");
long t0 = System.currentTimeMillis();
PeakMatchRunner.peakmatchCandidates(_conf, events, candidates, null);
double tPM = System.currentTimeMillis()-t0;
double eachMicrosec = 1000*tPM/samplePairs;
double perSec = 1000000 / eachMicrosec;
extrapolatedForAllMS = (long)(allPairs * eachMicrosec / 1000);
System.out.println(events.size() + " events sampled -> " + samplePairs + " distinct pairs");
System.out.println(tPM + " ms, " + (long)eachMicrosec + " microsec each, " + (long)perSec + "/sec");
System.out.println("Peakmatch method - extrapolation to all events (" + allPairs + " distinct pairs of " + _conf.countAllEvents() + " events): " + Util.periodToString(extrapolatedForAllMS));
}
{
System.out.println();
System.out.println("=== Postprocess phase ===");
long t0 = System.currentTimeMillis();
Map<String, Double> finalMatches = Util.fullFFTXCorr(_conf, candidates.keySet(), events);
long tPostProcess = System.currentTimeMillis()-t0;
long eachMicrosec = 1000*tPostProcess/candidates.size();
long perSec = 1000000 / eachMicrosec;
long multiple = samplePairs / candidates.size();
long extrapolatedNaiveBFForAllMS = allPairs * eachMicrosec / 1000;
long extrapolatedPMForAllMS = extrapolatedNaiveBFForAllMS / multiple;
System.out.println(candidates.size() + " pairs post-processed with full FFT xcorr -> " + finalMatches.size() + " final matches");
System.out.println("1 / " + multiple + " of entire eventpair space necessary to full xcorr");
System.out.println(tPostProcess + " ms, " + eachMicrosec + " microsec each, " + perSec + "/sec");
System.out.println("extrapolation to all events (" + allPairs + " distinct pairs of " + _conf.countAllEvents() + " events): " + Util.periodToString(extrapolatedPMForAllMS));
long totalPMExtrapolation = extrapolatedPMForAllMS + extrapolatedForAllMS;
System.out.println();
System.out.println("total PM + postprocess extrapolation: " + Util.periodToString(totalPMExtrapolation));
System.out.println();
System.out.println("full n^2 brute force (FFT) for comparison - extrapolation to all events: " + Util.periodToString(extrapolatedNaiveBFForAllMS));
}
System.out.println();
System.out.println("*** Performance analysis completed ***");
}
private Map<String, Double> reduceToFinalThreshold(Map<String, Double> fullXcorr) {
return Maps.filterValues(fullXcorr, new Predicate<Double>() {
@Override
public boolean apply(Double value) {
return value >= _conf.getFinalThreshold();
}
});
}
private Map<String, Double> loadSampleXCorr(List<Event> events) throws EventException {
Map<String, Double> samples = Maps.newHashMap();
// all event pair keys that we want to examine
Set<String> keys = Sets.newHashSet();
for (Event a: events){
for (Event b: events){
if (!a.equals(b))
keys.add(new EventPair(a, b).getKey());
}
}
System.out.println("loading " + keys.size() + " event pairs");
String line = null;
if (!new File(XCorrProcessor.XCORR_SAMPLE_SAVE_FILE).exists()){
try {
new File(XCorrProcessor.XCORR_SAMPLE_SAVE_FILE).createNewFile();
} catch (IOException e) {
throw new EventException("failed to create cache file " + XCorrProcessor.XCORR_SAMPLE_SAVE_FILE);
}
}
// load cached event pair xcorr values, throw away any not in our events list
try (BufferedReader br = new BufferedReader(new FileReader(XCorrProcessor.XCORR_SAMPLE_SAVE_FILE))){
while (null != (line = br.readLine())) {
String[] sa = line.split("\t");
if (sa.length != 3)
throw new EventException("invalid file " + XCorrProcessor.XCORR_SAMPLE_SAVE_FILE + " line: '" + line + "'");
String key = sa[0] + "\t" + sa[1];
if (!keys.contains(key))
continue;
samples.put(key, Double.parseDouble(sa[2]));
keys.remove(key);
}
} catch (IOException e) {
throw new EventException("error reading xcorr list, line '" + line + "'", e);
}
System.out.println(samples.size() + " cached pair xcorr results found, " + keys.size() + " remain to be calculated");
// generate and store ones not already cached
// store ALL pairs, not just ones above threshold - we are likely to change the threshold post-
if (!keys.isEmpty()){
System.out.println("calculating remaining event pair xcorr");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(XCorrProcessor.XCORR_SAMPLE_SAVE_FILE, true))){
long t0 = System.currentTimeMillis();
int count = 0;
for (int ii = 0; ii < events.size(); ii++) {
for (int jj = ii + 1; jj < events.size(); jj++) {
Event a = events.get(ii);
Event b = events.get(jj);
String key = new EventPair(a, b).getKey();
if (!keys.contains(key))
continue;
double[] xcorr = Util.fftXCorr(a, b); // slowish (no precaching of FFT) but doesn't matter for samples
double best = Util.getHighest(xcorr);
bw.write(key + "\t" + Util.NF.format(best) + "\n");
samples.put(key, best);
if (++count % 1000 == 0)
System.out.println(count + " sample xcorr calculated ...");
}
bw.flush();
}
long tMS = System.currentTimeMillis()-t0;
long eachMicrosec = 1000*tMS/count;
long perSec = 1000000 / eachMicrosec;
long allPairs = (long)_conf.countAllEvents()*(long)_conf.countAllEvents()/2;
long extrapolatedForAllMS = allPairs * eachMicrosec / 1000;
System.out.println("generated and cached " + count + " full FFT xcorr: " + tMS/1000 + " sec, " + eachMicrosec + "microsec each, " + perSec + "/sec");
System.out.println("extrapolation to full FFT xcorr for " + allPairs + " distinct pairs of " + _conf.countAllEvents() + " events: " + Util.periodToString(extrapolatedForAllMS));
System.out.println("(delete file " + XCorrProcessor.XCORR_SAMPLE_SAVE_FILE + " to repeat)");
} catch (IOException e) {
throw new EventException("error writing new xcorr list", e);
}
System.out.println("finished sample xcorr calculation");
}
return samples;
}
private List<Event> loadSampleEvents() throws EventException {
System.out.println("loading sample events ...");
List<Event> data = Lists.newArrayList();
boolean fail=false;
for (File f : Lists.newArrayList(_conf.getSampledataset().listFiles())){
try{
data.add(new BasicEvent(f, _conf));
} catch (EventException e1){
System.err.println("failed to load: " + e1.getMessage());
fail=true;
}
}
if (fail && !_conf.isContinueOnError())
throw new EventException("not all files validated");
System.out.println("loaded " + data.size() + " sample events");
return data;
}
}
|
package com.elmakers.mine.bukkit.magic.command;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.BlockIterator;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.magic.MagicAPI;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
import com.elmakers.mine.bukkit.utility.InventoryUtils;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
public class MagicMobCommandExecutor extends MagicTabExecutor {
protected static Gson gson;
public MagicMobCommandExecutor(MagicAPI api) {
super(api, "mmob");
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!api.hasPermission(sender, getPermissionNode()))
{
sendNoPermission(sender);
return true;
}
if (args.length == 0)
{
return false;
}
if (args[0].equalsIgnoreCase("list"))
{
onListMobs(sender, args.length > 1);
return true;
}
if (args[0].equalsIgnoreCase("clear") || args[0].equalsIgnoreCase("remove"))
{
onClearMobs(sender, args);
return true;
}
if (args[0].equalsIgnoreCase("egg"))
{
if (args.length < 2) {
return false;
}
onGetEgg(sender, args[1]);
return true;
}
boolean isSummon = args[0].equalsIgnoreCase("summon");
boolean isSpawnCommand = args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("spawn") || isSummon;
if (!isSpawnCommand || args.length < 2)
{
return false;
}
if (!(sender instanceof Player) && !(sender instanceof BlockCommandSender) && args.length < 6) {
sender.sendMessage(ChatColor.RED + "Usage: mmob spawn <type> <x> <y> <z> <world> [count]");
return true;
}
Location targetLocation = null;
World targetWorld = null;
Player player = (sender instanceof Player) ? (Player)sender : null;
BlockCommandSender commandBlock = (sender instanceof BlockCommandSender) ? (BlockCommandSender)sender : null;
if (args.length >= 6) {
targetWorld = Bukkit.getWorld(args[5]);
if (targetWorld == null) {
sender.sendMessage(ChatColor.RED + "Invalid world: " + ChatColor.GRAY + args[5]);
return true;
}
} else if (player != null) {
targetWorld = player.getWorld();
} else if (commandBlock != null) {
Block block = commandBlock.getBlock();
targetWorld = block.getWorld();
targetLocation = block.getLocation();
}
if (args.length >= 5) {
try {
double currentX = 0;
double currentY = 0;
double currentZ = 0;
if (player != null) {
Location currentLocation = player.getLocation();
currentX = currentLocation.getX();
currentY = currentLocation.getY();
currentZ = currentLocation.getZ();
} else if (commandBlock != null) {
Block blockLocation = commandBlock.getBlock();
currentX = blockLocation.getX();
currentY = blockLocation.getY();
currentZ = blockLocation.getZ();
}
targetLocation = new Location(targetWorld,
ConfigurationUtils.overrideDouble(args[2], currentX),
ConfigurationUtils.overrideDouble(args[3], currentY),
ConfigurationUtils.overrideDouble(args[4], currentZ));
} catch (Exception ex) {
sender.sendMessage(ChatColor.RED + "Usage: mmob spawn <type> <x> <y> <z> <world> [count]");
return true;
}
} else if (player != null) {
Location location = player.getEyeLocation();
BlockIterator iterator = new BlockIterator(location.getWorld(), location.toVector(), location.getDirection(), 0, 16);
Block block = location.getBlock();
while (block.getType() == Material.AIR && iterator.hasNext()) {
block = iterator.next();
}
block = block.getRelative(BlockFace.UP);
targetLocation = block.getLocation();
}
if (targetLocation == null || targetLocation.getWorld() == null) {
sender.sendMessage(ChatColor.RED + "Usage: mmob spawn <type> <x> <y> <z> <world> [count]");
return true;
}
String mobKey = args[1];
int count = 1;
String countString = null;
if (args.length == 7) {
countString = args[6];
} else if (args.length == 3) {
countString = args[2];
}
if (countString != null) {
try {
count = Integer.parseInt(countString);
} catch (Exception ex) {
sender.sendMessage(ChatColor.RED + "Invalid count: " + countString);
return true;
}
}
if (count <= 0) return true;
MageController controller = api.getController();
Entity spawned = null;
EntityData entityData = null;
int jsonStart = mobKey.indexOf('{');
if (jsonStart > 0) {
String fullKey = mobKey;
mobKey = fullKey.substring(0, jsonStart);
String json = fullKey.substring(jsonStart);
try {
JsonReader reader = new JsonReader(new StringReader(json));
reader.setLenient(true);
Map<String, Object> tags = getGson().fromJson(reader, Map.class);
InventoryUtils.convertIntegers(tags);
ConfigurationSection mobConfig = ConfigurationUtils.newConfigurationSection();
mobConfig.set("type", mobKey);
for (Map.Entry<String, Object> entry : tags.entrySet()) {
mobConfig.set(entry.getKey(), entry.getValue());
}
entityData = controller.getMob(mobConfig);
} catch (Throwable ex) {
controller.getLogger().warning("[Magic] Error parsing mob json: " + json + " : " + ex.getMessage());
}
}
if (entityData == null) {
entityData = controller.getMob(mobKey);
}
if (entityData == null) {
sender.sendMessage(ChatColor.RED + "Unknown mob type " + ChatColor.YELLOW + mobKey);
return true;
}
if (entityData.isNPC()) {
sender.sendMessage(ChatColor.YELLOW + "Mob type " + ChatColor.GOLD + mobKey + ChatColor.YELLOW + " is meant to be an NPC");
sender.sendMessage(" Spawning as a normal mob, use " + ChatColor.AQUA + "/mnpc add " + mobKey + ChatColor.WHITE + " to create as an NPC");
}
if (!isSummon) {
controller.setDisableSpawnReplacement(true);
}
try {
for (int i = 0; i < count; i++) {
spawned = entityData.spawn(targetLocation);
}
} catch (Exception ex) {
sender.sendMessage(ChatColor.RED + "Failed to spawn mob of type " + ChatColor.YELLOW + mobKey + ChatColor.RED + ", an unexpected exception occurred, please check logs");
controller.getLogger().log(Level.SEVERE, "Error spawning mob " + mobKey, ex);
return true;
}
if (!isSummon) {
controller.setDisableSpawnReplacement(false);
}
if (spawned == null) {
sender.sendMessage(ChatColor.RED + "Failed to spawn mob of type " + ChatColor.YELLOW + mobKey);
return true;
}
String name = spawned.getName();
if (name == null) {
name = mobKey;
}
sender.sendMessage(ChatColor.AQUA + "Spawned mob: " + ChatColor.LIGHT_PURPLE + name);
return true;
}
private static Gson getGson() {
if (gson == null) {
gson = new Gson();
}
return gson;
}
protected void onListMobs(CommandSender sender, boolean all) {
Map<String, Integer> mobCounts = new HashMap<>();
Collection<Entity> mobs = new ArrayList<>(api.getController().getActiveMobs());
for (Entity mob : mobs) {
EntityData entityData = controller.getMob(mob);
if (entityData == null) continue;
Integer mobCount = mobCounts.get(entityData.getKey());
if (mobCount == null) {
mobCounts.put(entityData.getKey(), 1);
} else {
mobCounts.put(entityData.getKey(), mobCount + 1);
}
}
boolean messaged = false;
Set<String> keys = api.getController().getMobKeys();
for (String key : keys) {
EntityData mobType = api.getController().getMob(key);
String message = ChatColor.AQUA + key + ChatColor.WHITE + " : " + ChatColor.DARK_AQUA + mobType.describe();
Integer mobCount = mobCounts.get(key);
if (mobCount != null) {
message = message + ChatColor.GRAY + " (" + ChatColor.GREEN + mobCount + ChatColor.DARK_GREEN + " Active" + ChatColor.GRAY + ")";
}
if (all || mobCount != null) {
sender.sendMessage(message);
messaged = true;
}
}
if (!messaged) {
sender.sendMessage(ChatColor.YELLOW + "No magic mobs active. Use '/mmob list all' to see all mob types.");
}
}
protected void onGetEgg(CommandSender sender, String mobType) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command may only be used in-game");
return;
}
MageController controller = api.getController();
EntityData entityData = controller.getMob(mobType);
String customName = null;
EntityType entityType = null;
if (entityData == null) {
entityType = com.elmakers.mine.bukkit.entity.EntityData.parseEntityType(mobType);
} else {
entityType = entityData.getType();
customName = entityData.getName();
}
if (entityType == null) {
sender.sendMessage(ChatColor.RED + "Unknown mob type " + mobType);
}
Material eggMaterial = controller.getMobEgg(entityType);
if (eggMaterial == null) {
sender.sendMessage(ChatColor.YELLOW + "Could not get a mob egg for entity of type " + entityType);
return;
}
ItemStack spawnEgg = new ItemStack(eggMaterial);
if (customName != null && !customName.isEmpty()) {
ItemMeta meta = spawnEgg.getItemMeta();
String title = controller.getMessages().get("general.spawn_egg_title");
title = title.replace("$entity", customName);
meta.setDisplayName(title);
spawnEgg.setItemMeta(meta);
spawnEgg = InventoryUtils.makeReal(spawnEgg);
Object entityTag = InventoryUtils.createNode(spawnEgg, "EntityTag");
InventoryUtils.setMeta(entityTag, "CustomName", "{\"text\":\"" + customName + "\"}");
}
controller.giveItemToPlayer((Player)sender, spawnEgg);
}
protected void onClearMobs(CommandSender sender, String[] args) {
String mobType = args.length > 1 ? args[1] : null;
if (mobType != null && mobType.equalsIgnoreCase("all")) {
mobType = null;
}
String worldName = null;
Integer radiusSquared = null;
Location targetLocation = null;
Player player = (sender instanceof Player) ? (Player)sender : null;
BlockCommandSender commandBlock = (sender instanceof BlockCommandSender) ? (BlockCommandSender)sender : null;
if (args.length == 3) {
if (!(sender instanceof ConsoleCommandSender) && Bukkit.getWorld(args[2]) == null) {
try {
int radius = Integer.parseInt(args[2]);
radiusSquared = radius * radius;
} catch (Exception ignored) {
}
}
if (radiusSquared == null) {
worldName = args[2];
} else {
if (player != null) {
targetLocation = player.getLocation();
} else if (commandBlock != null) {
targetLocation = commandBlock.getBlock().getLocation();
} else {
sender.sendMessage(ChatColor.RED + "Invalid world: " + args[2]);
}
}
} else if (args.length > 5) {
World world = null;
if (args.length > 6) {
worldName = args[6];
world = Bukkit.getWorld(worldName);
}
if (world == null) {
sender.sendMessage(ChatColor.RED + "Invalid world: " + worldName);
}
try {
int radius = Integer.parseInt(args[2]);
radiusSquared = radius * radius;
double currentX = 0;
double currentY = 0;
double currentZ = 0;
if (player != null) {
targetLocation = player.getLocation();
} else if (commandBlock != null) {
targetLocation = commandBlock.getBlock().getLocation();
}
if (targetLocation != null) {
currentX = targetLocation.getX();
currentY = targetLocation.getY();
currentZ = targetLocation.getZ();
if (world == null) {
world = targetLocation.getWorld();
worldName = world.getName();
}
}
if (world == null) {
sender.sendMessage(ChatColor.RED + "Usage: mmob clear <type> <radius> <x> <y> <z> <world>");
return;
}
targetLocation = new Location(world,
ConfigurationUtils.overrideDouble(args[3], currentX),
ConfigurationUtils.overrideDouble(args[4], currentY),
ConfigurationUtils.overrideDouble(args[5], currentZ));
} catch (Exception ex) {
sender.sendMessage(ChatColor.RED + "Usage: mmob clear <type> <radius> <x> <y> <z> <world>");
return;
}
}
MageController controller = api.getController();
Collection<Entity> mobs = new ArrayList<>(controller.getActiveMobs());
int removed = 0;
for (Entity entity : mobs) {
if (controller.isNPC(entity)) continue;
EntityData entityData = controller.getMob(entity);
if (entityData == null || entityData.getKey() == null) continue;
if (worldName != null && !entity.getLocation().getWorld().getName().equals(worldName)) continue;
if (mobType != null && !entityData.getKey().equals(mobType)) continue;
if (radiusSquared != null && targetLocation != null && entity.getLocation().distanceSquared(targetLocation) > radiusSquared) continue;
Mage mage = controller.getRegisteredMage(entity);
if (mage != null) {
mage.undoScheduled();
api.getController().removeMage(mage);
}
if (entity != null) {
entity.remove();
}
removed++;
}
sender.sendMessage("Removed " + removed + " magic mobs");
}
@Override
public Collection<String> onTabComplete(CommandSender sender, String commandName, String[] args) {
List<String> options = new ArrayList<>();
if (!sender.hasPermission("Magic.commands.mmob")) return options;
if (args.length == 1) {
options.add("add");
options.add("spawn");
options.add("summon");
options.add("egg");
options.add("list");
options.add("clear");
options.add("remove");
} else if (args.length == 2 && (args[0].equalsIgnoreCase("spawn")
|| args[0].equalsIgnoreCase("summon")
|| args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("add")
|| args[0].equalsIgnoreCase("clear") || args[0].equalsIgnoreCase("egg")
)) {
for (String mobKey : api.getController().getMobKeys()) {
EntityData mob = api.getController().getMob(mobKey);
if (mob != null && !mob.isNPC() && !mob.isHidden()) {
options.add(mob.getKey());
}
}
for (EntityType entityType : EntityType.values()) {
if (entityType.isAlive() && entityType.isSpawnable()) {
options.add(entityType.name().toLowerCase());
}
}
} else if (args.length == 3 && (args[0].equalsIgnoreCase("clear") || args[0].equalsIgnoreCase("remove"))) {
List<World> worlds = api.getPlugin().getServer().getWorlds();
for (World world : worlds) {
options.add(world.getName());
}
}
return options;
}
}
|
package com.thekelvinliu.KPCBChallenge;
/**
* A generic, homogeneous fixed-size hash map.
*
* This hash map uses an implicit AVL Tree to maintain a self-balancing binary
* search tree. Each node of the tree represents an entry in the hash map. The
* hash map accepts strings as keys and internally stores the hashed values of
* these strings using {@link java.lang.String#hashCode()}. This class is
* implemented with java generics, allowing the mapped values to be of any type,
* however an individual instance of this hash map may only hold a single type.
* <p>
* Each node of the implicit tree is stored in an array. A Node has integer
* fields, which hold the array indices of a node's left and right children in
* the implicit tree. This hash map uses modified implementations of standard
* AVL Tree operations to achieve O(log n) set, get, and delete time complexity.
*
* @param <T> the type of value that this hash map will hold
* @see com.thekelvinliu.KPCBChallenge.FixedSizeHashMap.Node
*/
public class FixedSizeHashMap<T> {
//HELPER CLASS
/**
* A generic class that represents a node in a binary tree.
*
* Each node holds a key and a value, as well as indices for the node's
* left and right children. Because this class is not accessible to the
* outside world, fields will be accessed and modified directly by
* FixedSizeHashMap for convenience.
*
* @param <T> the type of the value to be held by this node
*/
private final class Node<T> {
//INSTANCE VARIABLES
/**
* The key held by this node.
*/
private int key;
/**
* The value held by this node.
*/
private T value;
/**
* The height of this node.
*/
private int height;
/**
* The index of this node's left child.
*/
private int left;
/**
* The index of this node's right child.
*/
private int right;
//CONSTRUCTOR
/**
* Creates an empty node.
*
* All integer fields are set to -1, which in the context of this whole
* class, refers to being null. The value field is actually set to null.
*/
private Node() {
this.clean();
}
//METHODS
/**
* Returns a string representation of this node.
* @return a string representation of this node
*/
public String toString() {
String retval = "(" + this.key + ", ";
retval += (this.value != null) ? this.value.toString() : "NULL";
retval += ", " + this.left + ", " + this.right + ")";
return retval;
}
/**
* Resets all fields of this node to their original value (-1 or null).
*/
private void clean() {
this.key = -1;
this.value = null;
this.height = -1;
this.left = -1;
this.right = -1;
}
}
//INSTANCE VARIABLES
/**
* The array that holds all of this hash map's nodes.
*
* The nodes in this array may be active or inactive in the this hash map's
* implicit tree. An active node must have a non null value and nonnegative
* height field.
*/
private Node[] tree;
/**
* The bitmap used to mark which nodes in the array are active.
*
* This bitmap is accomplished with a byte array. Because of this, up to 7
* extra bits might be unused, as they point to indices outside the bounds
* of the node array.
*/
private byte[] bitmap;
/**
* The array index of this hash map's implicit root.
*/
private int rootInd;
/**
* The array index the node most recently deleted from the implicit tree.
*
* This will typically be -1 if a node hasn't been deleted.
*/
private int delInd;
/**
* The fixed size of this hash map.
*/
private final int size;
/**
* The number of items currently in this hash map.
*/
private int items;
//CONSTRUCTOR
public FixedSizeHashMap(int size) {
if (size > 0) {
this.tree = new Node[size];
for (int i = 0; i < size; i++) this.tree[i] = new Node();
this.bitmap = new byte[size/8 + 1];
this.rootInd = -1;
this.delInd = -1;
this.size = size;
this.items = 0;
} else {
throw new IllegalArgumentException("Size must be a positive integer.");
}
}
//USER METHODS, PRESCRIBED BY KPCB (PUBLIC)
/**
* Associates given key to a given value in this hash map.
*
* Also returns a boolean indicating the success or failure of this
* operation. Success depends on the following three constraints:<p>
* (1) there must be at least one inactive node in this hash map,<p>
* (2) the given value must not be null,<p>
* (3) the given key must not already be associated with a value.
*
* @param key the key to be associated
* @param value the value to be associated
* @return a boolean indicating success (true) or failure (false)
*/
public boolean set(String key, T value) {
if (this.items < this.size && value != null) {
int newInd = this.getAvailableNode();
this.tree[newInd].key = key.hashCode();
this.tree[newInd].value = value;
this.tree[newInd].height = 0;
try {
this.rootInd = this.insert(newInd, this.rootInd);
this.bitFlip(newInd);
this.items++;
return true;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.printf("%d %d", newInd, this.rootInd);
return false;
} catch (IllegalArgumentException e) {
//clean up and return false
this.tree[newInd].clean();
return false;
}
} else {
return false;
}
}
/**
* Returns the value associated with a given key.
*
* This will fail and return null if there are no entries in this hash map,
* or if the key is not found.
*
* @param key the key associated with the returned value
* @return the value associated with key (or null)
*/
public T get(String key) {
if (this.items > 0 && this.rootInd != -1) {
//get the index of the node with the given string
int nodeInd = this.find(key.hashCode(), this.rootInd);
return (nodeInd != -1) ? (T) this.tree[nodeInd].value : null;
} else {
return null;
}
}
/**
* Deletes the entry with the given key from this hash map.
*
* Also returns the keys associated value. This operation can fail if there
* are no active nodes in the implicit tree, or if the given key is not
* associated with any values in this hash map. If this happens, null is
* returned.
*
* @param key the key of the entry to be deleted
* @param key the key paired with the returned value
* @return the value associated with key or null
*/
public T delete(String key) {
if (this.items > 0 && this.rootInd != -1) {
//attempt to remove the node with key from the implicit tree
this.rootInd = this.remove(key.hashCode(), this.rootInd);
//this.delInd will hold the index of the node that should be delted
if (this.delInd != -1) {
//save the return value
T retval = (T) this.tree[delInd].value;
//clean the deleted node and mark as inactive
this.tree[this.delInd].clean();
this.bitFlip(this.delInd);
this.delInd = -1;
this.items
return retval;
} else {
return null;
}
} else {
return null;
}
}
/**
* Returns the load (ratio of items to size) of this fixed-size hash map.
*
* @return the load of this fixed-size hash map
*/
public float load() {
return (float)this.items/this.size;
}
//EXTRAS (PUBLIC)
/**
* Returns the maximum number of items that this hash map can hold.
*
* @return the maximum number of items that this hash map can hold
*/
public int getSize() {
return this.size;
}
//TREE UTILITIES (PRIVATE)
private int insert(int newInd, int startInd) throws IllegalArgumentException {
//insert at startInd if startInd isn't actually part of the implicit tree
if (startInd == -1) {
return newInd;
}
//insert into left subtree
else if (this.tree[newInd].key < this.tree[startInd].key) {
this.tree[startInd].left = this.insert(newInd, this.tree[startInd].left);
}
//insert into right subtree
else if (this.tree[newInd].key > this.tree[startInd].key) {
this.tree[startInd].right = this.insert(newInd, this.tree[startInd].right);
}
//duplicate key
else {
throw new IllegalArgumentException("Key already used.");
}
//rebalance tree and return
return this.rebalance(startInd);
}
/**
* Returns the index of the node with the given key.
*
* This method recursively traverses the tree, beginning at the node at
* index startInd. If startInd is not actually a node in the tree, -1 will
* be returned, indicating that no node was found with the given key.
*
* @param key the key to search for
* @param startInd the index of the subtree root
* @return the index of the node with the given key
*/
private int find(int key, int startInd) {
if (startInd == -1) {
return -1;
} else if (key == this.tree[startInd].key) {
return startInd;
} else if (key < this.tree[startInd].key) {
return this.find(key, this.tree[startInd].left);
} else {
return this.find(key, this.tree[startInd].right);
}
}
/**
* Removes node with key from the subtree rooted by node at startInd.
*
* This method recursively traverses the implicit subtree rooted by the node
* at startInd to find and remove the node with the given key. Depending on
* the number of children the found node has, it may or may not rebalance
* the implicit tree using {@link FixedSizeHashMap#rebalance}.
*
* @param key the key of the node to be removed
* @param startInd the index of the subtree root
* @return the index of the (new) subtree root
*/
private int remove(int key, int startInd) {
//startInd isn't actually part of the implicit tree
if (startInd == -1) {
this.delInd = -1;
return -1;
}
//remove from left subtree
else if (key < this.tree[startInd].key) {
this.tree[startInd].left = this.remove(key, this.tree[startInd].left);
return this.rebalance(startInd);
}
//remove from right subtree
else if (key > this.tree[startInd].key) {
this.tree[startInd].right = this.remove(key, this.tree[startInd].right);
return this.rebalance(startInd);
}
//startInd is the node to be removed
else {
int lInd = this.tree[startInd].left;
int rInd = this.tree[startInd].right;
this.delInd = startInd;
//node is a leaf, simply remove it
if (lInd == -1 && rInd == -1) {
return -1;
}
//node has a single child, give the node it's grandchildren
else if (lInd != -1 && rInd == -1) {
return lInd;
} else if (lInd == -1 && rInd != -1) {
return rInd;
}
//node has two children, replace the node it's successor (smallest
//node in right subtree), then remove the successor
else {
int smallestInd = this.getSmallest(rInd);
int tempInd = startInd;
this.nodeKVSwap(startInd, smallestInd);
this.tree[startInd].right = this.remove(this.tree[smallestInd].key, rInd);
this.delInd = smallestInd;
return this.rebalance(startInd);
}
}
}
/**
* Rebalances the subtree rooted by the node at index startInd.
*
* Based on the balance factor of the given node, this method will apply the
* appropriate tree rotation. This method is NOT recursive and will only
* apply the rotation to the node at index startInd.
*
* @param startInd the index of the subree root
* @return the index of the (new) subtree root
* @see FixedSizeHashMap#balanceFactor
*/
private int rebalance(int startInd) {
if (startInd == -1) System.out.println("shit");
int newStartInd;
int lInd = this.tree[startInd].left;
int rInd = this.tree[startInd].right;
//left subtree heavy
if (this.balanceFactor(startInd) == 2) {
if (this.tree[lInd].left == -1) {
newStartInd = this.rotateCaseLL(startInd);
} else {
newStartInd = this.rotatecaseLR(startInd);
}
}
//right subtree heavy
else if (this.balanceFactor(startInd) == -2) {
if (this.tree[rInd].right == -1) {
newStartInd = this.rotateCaseRL(startInd);
} else {
newStartInd = this.rotateCaseRR(startInd);
}
}
//no rebalancing needed
else {
newStartInd = startInd;
}
//update height if necessary
this.updateHeight(startInd);
return newStartInd;
}
/**
* Returns the index of the smallest node in the subtree rooted by startInd.
*
* @param startInd the index of the subtree root
* @return the index of the node with the smallest key
*/
private int getSmallest(int startInd) {
if (this.tree[startInd].left != -1) {
return this.getSmallest(this.tree[startInd].left);
} else {
return startInd;
}
}
/**
* Swaps the keys and values of the nodes at indeces a and b.
* Only the key and value fields are swapped. All other fields are left
* untouched.
*
* @param a the index of the node to be overwritten (dst)
* @param b the index of the node with the data to write (src)
*/
private void nodeKVSwap(int a, int b) {
int tempKey = this.tree[a].key;
this.tree[a].key = this.tree[b].key;
this.tree[b].key = tempKey;
T tempValue = (T) this.tree[a].value;
this.tree[a].value = this.tree[b].value;
this.tree[b].value = tempValue;
}
/**
* Returns the balance factor of the subtree rooted by the node at index i.
*
* Balance factor is defined as the difference between a node's left and
* right subtrees.
*
* @param i the index of a node
* @return the balance factor of the specified node
*/
private int balanceFactor(int i) {
return this.height(this.tree[i].left) - this.height(this.tree[i].right);
}
/**
* Returns the height of the node at index i or -1 if i is not active.
*
* @param i the index of a node
* @return the height of the node at index i or -1
*/
private int height(int i) {
return (i != -1) ? this.tree[i].height : -1;
}
/**
* Updates the height of the node at index i
*
* @param i the index of the node to be updated
*/
private void updateHeight(int i) {
if (i != -1) {
int lInd = this.tree[i].left;
int rInd = this.tree[i].right;
if (lInd == -1 && rInd == -1)
this.tree[i].height = 0;
else if (lInd != -1 && rInd == -1)
this.tree[i].height = this.tree[lInd].height + 1;
else if (lInd == -1 && rInd != -1)
this.tree[i].height = this.tree[rInd].height + 1;
else
this.tree[i].height = this.max(this.height(lInd), this.height(rInd)) + 1;
}
}
//TREE ROTATIONS (PRIVATE)
private int rotateCaseLL(int startInd) {
int newStartInd = this.tree[startInd].left;
if (newStartInd == -1) {
return startInd;
} else {
this.tree[startInd].left = this.tree[newStartInd].right;
this.tree[newStartInd].right = startInd;
//update heights
this.updateHeight(startInd);
this.updateHeight(newStartInd);
return newStartInd;
}
}
private int rotateCaseRR(int startInd) {
int newStartInd = this.tree[startInd].right;
if (newStartInd == -1) {
return startInd;
} else {
this.tree[startInd].right = this.tree[newStartInd].left;
this.tree[newStartInd].left = startInd;
//update heights
this.updateHeight(startInd);
this.updateHeight(newStartInd);
return newStartInd;
}
}
private int rotatecaseLR(int startInd) {
this.tree[startInd].left = this.rotateCaseRR(this.tree[startInd].left);
return this.rotateCaseLL(startInd);
}
private int rotateCaseRL(int startInd) {
this.tree[startInd].right = this.rotateCaseLL(this.tree[startInd].right);
return this.rotateCaseRR(startInd);
}
//BITMAP UTILITIES (PRIVATE)
/**
* Returns the index of the first available node in the internal array.
*
* Iterates over this hash map's internal bitmap and searches for the first
* bit that is set to 0.
*
* @return The index of the first available node
*/
private int getAvailableNode() {
int i = 0;
for (; this.bitmap[i] == -1; i++);
int j = 0;
for (; j < 8; j++) {
//break out of loop the first time a 0 is encountered
if ((this.bitmap[i] & (1 << j)) == 0) {
break;
}
}
//ensure the returned value is less than the max size of this hashmap
return (8*i + j < this.size) ? 8*i + j : -1;
}
/**
* Flips the xth bit in the hash map's internal bitmap.
*
* @param x the bitmap index that should be flipped
*/
private void bitFlip(int x) {
int index = x/8;
int offset = x%8;
this.bitmap[index] ^= (1 << offset);
}
//MISC UTILITIES
/**
* Returns the max of two integers.
*
* @param a the first integer
* @param b the second integer
* @return the larger of the two given integers
*/
private static int max(int a, int b) {
return (a > b) ? a : b;
}
}
|
package utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.pegdown.Extensions;
import org.pegdown.PegDownProcessor;
import org.webdsl.WebDSLEntity;
import org.webdsl.lang.Environment;
import org.webdsl.tools.WikiFormatter;
import org.webdsl.logging.Logger;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
public abstract class AbstractPageServlet{
protected abstract void renderDebugJsVar(PrintWriter sout);
protected abstract boolean logSqlCheckAccess();
protected abstract void initTemplateClass();
protected abstract void redirectHttpHttps();
protected abstract boolean isActionSubmit();
protected abstract String[] getUsedSessionEntityJoins();
protected abstract void storeSessionEntities();
protected TemplateServlet templateservlet = null;
protected abstract org.webdsl.WebDSLEntity getRequestLogEntry();
protected abstract void addPrincipalToRequestLog(org.webdsl.WebDSLEntity rle);
protected abstract void addLogSqlToSessionMessages();
protected PegDownProcessor pegDownProcessor = null;
protected PegDownProcessor pegDownProcessorNoHardWraps = null;
public Session hibernateSession = null;
protected static Pattern isMarkupLangMimeType= Pattern.compile("html|xml$");
protected static Pattern baseURLPattern= Pattern.compile("^\\w{0,6}:
public boolean isReadOnly = false;
static{
common_css_link_tag_suffix = "/stylesheets/common_.css?" + System.currentTimeMillis() +"\" rel=\"stylesheet\" type=\"text/css\" />";
fav_ico_link_tag_suffix = "/favicon.ico?" + System.currentTimeMillis() + "\" rel=\"shortcut icon\" type=\"image/x-icon\" />";
ajax_js_include_name = "ajax.js?"+ System.currentTimeMillis();
}
public void serve(HttpServletRequest request, HttpServletResponse response, Map<String, String> parammap, Map<String, List<String>> parammapvalues, Map<String,List<utils.File>> fileUploads)
{
initTemplateClass();
this.startTime = System.currentTimeMillis();
ThreadLocalPage.set(this);
this.request=request;
this.response=response;
this.parammap = parammap;
this.parammapvalues = parammapvalues;
this.fileUploads=fileUploads;
redirectHttpHttps();
if(parammap.get("__ajax_runtime_request__") != null) {
this.setAjaxRuntimeRequest(true);
}
org.webdsl.WebDSLEntity rle = getRequestLogEntry();
org.apache.log4j.MDC.put("request", rle.getId().toString());
org.apache.log4j.MDC.put("template", "/" + getPageName());
utils.RequestAppender reqAppender = null;
if(parammap.get("disableopt") != null){
this.isOptimizationEnabled = false;
}
if(parammap.get("logsql") != null){
this.isLogSqlEnabled = true;
reqAppender = utils.RequestAppender.getInstance();
}
if(reqAppender != null){
reqAppender.addRequest(rle.getId().toString());
}
if(parammap.get("nocache") != null){
this.isPageCacheDisabled = true;
}
hibernateSession = utils.HibernateUtil.getCurrentSession();
hibernateSession.beginTransaction();
if(isReadOnly){
hibernateSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
}
else{
hibernateSession.setFlushMode(org.hibernate.FlushMode.COMMIT);
}
try
{
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
ThreadLocalServlet.get().loadSessionManager(hibernateSession, getUsedSessionEntityJoins());
ThreadLocalServlet.get().retrieveIncomingMessagesFromHttpSession();
initVarsAndArgs();
initRequestVars();
if(isActionSubmit()) {
if(parammap.get("__action__link__") != null) {
this.setActionLinkUsed(true);
}
templateservlet.storeInputs(null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
//storeinputs also finds which action is executed, since validation might be ignored using [ignore-validation] on the submit
boolean ignoreValidation = actionToBeExecutedHasDisabledValidation;
if (!ignoreValidation){
templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null);
ThreadLocalPage.get().clearTemplateContext();
}
if(validated){
templateservlet.handleActions(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalPage.get().clearTemplateContext();
}
}
if(isNotValid()){
// mark transaction so it will be aborted at the end
// entered form data can be used to update the form on the client with ajax, taking into account if's and other control flow template elements
// this also means that data in vars/args and hibernate session should not be cleared until form is rendered
abortTransaction();
}
String outstream = s.toString();
if(download != null) { //File.download() excecuted in action
download();
}
else {
// regular render, or failed action render
if( hasNotExecutedAction() || isNotValid() ){
//ajax replace performed during validation, assuming that handles all validation
if(isAjaxRuntimeRequest() && outstream.length() > 0){
response.getWriter().write("[");
response.getWriter().write(outstream);
if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions
if(logSqlCheckAccess()){
response.getWriter().write("{action: \"logsql\", value: \"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}");
}
else{
response.getWriter().write("{action: \"logsql\", value: \"Access to SQL logs was denied.\"}");
}
response.getWriter().write(",");
}
response.getWriter().write("{}]");
}
// action called but no action found
else if( isValid() && isActionSubmit() ){
org.webdsl.logging.Logger.error("Error: server received POST request but was unable to dispatch to a proper action");
response.getWriter().write("404 \n Error: server received POST request but was unable to dispatch to a proper action");
}
// action inside ajax template called and failed
else if( isAjaxTemplateRequest() && isActionSubmit() ){
StringWriter s1 = renderPageOrTemplateContents();
response.getWriter().write("[{action:\"replace\", id:{type:'enclosing-placeholder'}, value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(s1.toString()) + "\"}]");
}
//actionLink or ajax action used (request came through js runtime), and action failed
else if( isActionLinkUsed() || isAjaxRuntimeRequest() ){
StringWriter s1 = renderPageOrTemplateContents();
response.getWriter().write("[{action:\"replaceall\", value:\""+ org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(s1.toString()) +"\"}]");
}
// 1 regular render without any action being executed
// 2 regular action submit, and action failed
// 3 redirect in page init
// 4 download in page init
else{
renderOrInitAction();
}
}
// succesful action, always redirect, no render
else {
// actionLink or ajax action used and replace(placeholder) invoked
if( isReRenderPlaceholders() ){
templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null);
ThreadLocalPage.get().clearTemplateContext();
renderDynamicFormWithOnlyDirtyData = true;
renderPageOrTemplateContents(); // content of placeholders is collected in reRenderPlaceholdersContent map
StringWriter replacements = new StringWriter();
boolean addComma = false;
for(String ph : reRenderPlaceholders){
if(addComma){ replacements.write(","); }
else { addComma = true; }
replacements.write("{action:\"replace\", id:\""+ph+"\", value:\""
+ org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(reRenderPlaceholdersContent.get(ph))
+ "\"}");
}
response.getWriter().write("["+replacements.toString()+"]");
}
//hasExecutedAction() && isValid()
else if( isAjaxRuntimeRequest() ){
response.getWriter().write("[");
response.getWriter().write(outstream);
if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions
if(logSqlCheckAccess()){
response.getWriter().write("{action: \"logsql\", value: \"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}");
}
else{
response.getWriter().write("{action: \"logsql\", value: \"Access to SQL logs was denied.\"}");
}
response.getWriter().write(",");
}
response.getWriter().write("{}]");
}
else if( isActionLinkUsed() ){
//action link also uses ajax when ajax is not enabled
//, send only redirect location, so the client can simply set
// window.location = req.responseText;
response.getWriter().write("[{action:\"relocate\", value:\""+this.getRedirectUrl() + "\"}]");
}
if(!isAjaxRuntimeRequest()) {
addLogSqlToSessionMessages();
}
//else: action successful + no validation error + regular submit
// -> always results in a redirect, no further action necessary here
}
}
updatePageRequestStatistics();
hibernateSession = utils.HibernateUtil.getCurrentSession();
if( isTransactionAborted() || isRollback() ){
try{
hibernateSession.getTransaction().rollback();
}
catch (org.hibernate.SessionException e){
if(!e.getMessage().equals("Session is closed!")){ // closed session is not an issue when rolling back
throw e;
}
}
}
else {
ThreadLocalServlet.get().storeOutgoingMessagesInHttpSession();
storeSessionEntities();
addPrincipalToRequestLog(rle);
if(!this.isAjaxRuntimeRequest()){
ThreadLocalServlet.get().setEndTimeAndStoreRequestLog(utils.HibernateUtil.getCurrentSession());
}
if(isReadOnly || readOnlyRequestStats){ // either page has read-only modifier, or no writes have been detected
hibernateSession.getTransaction().rollback();
}
else{
hibernateSession.flush();
validateEntities();
hibernateSession.getTransaction().commit();
invalidatePageCacheIfNeeded();
}
}
ThreadLocalOut.popChecked(out);
}
catch(utils.MultipleValidationExceptions mve){
String url = ThreadLocalServlet.get().getRequest().getRequestURL().toString();
org.webdsl.logging.Logger.error("Validation exceptions occured while handling request URL [ "+url + " ]. Transaction is rolled back." );
for(utils.ValidationException vex : mve.getValidationExceptions()){
org.webdsl.logging.Logger.error( "Validation error: " + vex.getErrorMessage() , vex );
}
hibernateSession.getTransaction().rollback();
setValidated(false);
throw mve;
}
catch (Exception e) {
String url = ThreadLocalServlet.get().getRequest().getRequestURL().toString();
org.webdsl.logging.Logger.error("exception occured while handling request URL [ "+url+ " ]. Transaction is rolled back.");
org.webdsl.logging.Logger.error("exception message: "+e.getMessage(), e);
hibernateSession.getTransaction().rollback();
throw new RuntimeException("serve page request failed, requested URL: "+url);
}
finally{
cleanupThreadLocals();
org.apache.log4j.MDC.remove("request");
org.apache.log4j.MDC.remove("template");
if(reqAppender != null) reqAppender.removeRequest(rle.getId().toString());
}
}
// LoadingCache is thread-safe
public static boolean pageCacheEnabled = utils.BuildProperties.getNumCachedPages() > 0;
public static Cache<String, String> cacheAnonymousPages =
CacheBuilder.newBuilder()
.maximumSize(utils.BuildProperties.getNumCachedPages()).build();
public boolean invalidateAllPageCache = false;
protected boolean shouldTryCleanPageCaches = false;
public String invalidateAllPageCacheMessage;
public void invalidateAllPageCache(String entityname){
invalidateAllPageCache = true;
String propertySetterTrace = Warning.getStackTraceLineAtIndex(4);
invalidateAllPageCacheMessage = entityname + " - " + propertySetterTrace;
}
public void shouldTryCleanPageCaches(){
shouldTryCleanPageCaches = true;
}
public static Cache<String, String> cacheUserSpecificPages =
CacheBuilder.newBuilder()
.maximumSize(utils.BuildProperties.getNumCachedPages()).build();
public boolean invalidateUserSpecificPageCache = false;
public String invalidateUserSpecificPageCacheMessage;
public void invalidateUserSpecificPageCache(String entityname){
invalidateUserSpecificPageCache = true;
String propertySetterTrace = Warning.getStackTraceLineAtIndex(4);
invalidateUserSpecificPageCacheMessage = entityname + " - " + propertySetterTrace;
}
public boolean pageCacheWasUsed = false;
public void invalidatePageCacheIfNeeded(){
if(pageCacheEnabled && shouldTryCleanPageCaches){
if(invalidateAllPageCache){
Logger.info("All page caches invalidated, triggered by change in: "+invalidateAllPageCacheMessage);
cacheAnonymousPages.invalidateAll();
cacheUserSpecificPages.invalidateAll();
}
else if(invalidateUserSpecificPageCache){
Logger.info("user-specific page cache invalidated, triggered by change in: "+invalidateUserSpecificPageCacheMessage);
cacheUserSpecificPages.invalidateAll();
}
}
}
public void renderOrInitAction() throws IOException{
String key = request.getRequestURL().toString();
String s = "";
Cache<String, String> cache = null;
AbstractDispatchServletHelper servlet = ThreadLocalServlet.get();
if( // not using page cache if:
this.isPageCacheDisabled // ?nocache added to URL
|| this.isPostRequest() // post parameters are not included in cache key
|| isNotValid() // data validation errors need to be rendered
|| !servlet.getIncomingSuccessMessages().isEmpty() // success messages need to be rendered
){
StringWriter renderedContent = renderPageOrTemplateContents();
if(!mimetypeChanged){
s = renderResponse(renderedContent);
}
else{
s = renderedContent.toString();
}
}
else{ // using page cache
if( // use user-specific page cache if:
servlet.sessionHasChanges() // not necessarily login, any session data changes can be included in a rendered page
|| webdsl.generated.functions.loggedIn_.loggedIn_() // user might have old session from before application start, this check is needed to avoid those logged in pages ending up in the anonymous page cache
){
key = key + servlet.getSessionManager().getId();
cache = cacheUserSpecificPages;
}
else{
cache = cacheAnonymousPages;
}
try{
pageCacheWasUsed = true;
s = cache.get(key,
new Callable<String>(){
public String call(){
// System.out.println("key not found");
pageCacheWasUsed = false;
StringWriter renderedContent = renderPageOrTemplateContents();
if(!mimetypeChanged){
return renderResponse(renderedContent);
}
else{
return renderedContent.toString();
}
}
});
}
catch(java.util.concurrent.ExecutionException e){
e.printStackTrace();
}
}
// redirect in init action can be triggered with GET request, the render call in the line above will execute such inits
if( !isPostRequest() && isRedirected() ){
redirect();
cache.invalidate(key);
}
else if( download != null ){ //File.download() executed in page/template init block
download();
cache.invalidate(key); // don't cache binary file response in this page response cache, can be cached on client with expires header
}
else{
response.setContentType(getMimetype());
PrintWriter sout = response.getWriter(); //reponse.getWriter() must be called after file download checks
sout.write(s);
}
}
public boolean renderDynamicFormWithOnlyDirtyData = false;
public StringWriter renderPageOrTemplateContents(){
if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); }
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
if(request.getParameter("dynamicform") == null){
// regular pages and forms
if(isNotValid()){
clearHibernateCache();
}
ThreadLocalOut.push(out);
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
}
else{
// dynamicform uses submitted variable data to process form content
// render form with newly entered data, rest with the current persisted data
if(isNotValid() && !renderDynamicFormWithOnlyDirtyData){
StringWriter theform = new StringWriter();
PrintWriter pwform = new PrintWriter(theform);
ThreadLocalOut.push(pwform);
// render, when encountering submitted form save in abstractpage
validationFormRerender = true;
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(pwform);
clearHibernateCache();
}
ThreadLocalOut.push(out);
// render, when isNotValid and encountering submitted form render old
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
}
return s;
}
public StringWriter renderPageOrTemplateContentsSingle(){
if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); }
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
return s;
}
private boolean validationFormRerender = false;
public boolean isValidationFormRerender(){
return validationFormRerender;
}
public String submittedFormContent = null;
private static String common_css_link_tag_suffix;
private static String fav_ico_link_tag_suffix;
private static String ajax_js_include_name;
public String renderResponse(StringWriter s) {
StringWriter sw = new StringWriter();
PrintWriter sout = new PrintWriter(sw);
ThreadLocalOut.push(sout);
addJavascriptInclude( utils.IncludePaths.jQueryJS() );
addJavascriptInclude( ajax_js_include_name );
sout.println("<!DOCTYPE html>");
sout.println("<html>");
sout.println("<head>");
sout.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
sout.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
sout.println("<title>"+getPageTitle().replaceAll("<[^>]*>","")+"</title>");
sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+fav_ico_link_tag_suffix);
sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+common_css_link_tag_suffix);
renderDebugJsVar(sout);
sout.println("<script type=\"text/javascript\">var contextpath=\""+ThreadLocalPage.get().getAbsoluteLocation()+"\";</script>");
for(String sheet : this.stylesheets) {
if(sheet.startsWith("
sout.print("<link rel=\"stylesheet\" href=\""+ sheet + "\" type=\"text/css\" />");
}
else{
sout.print("<link rel=\"stylesheet\" href=\""+ThreadLocalPage.get().getAbsoluteLocation()+"/stylesheets/"+sheet+"\" type=\"text/css\" />");
}
}
for(String script : this.javascripts) {
if(script.startsWith("
sout.println("<script type=\"text/javascript\" src=\"" + script + "\"></script>");
}
else{
sout.println("<script type=\"text/javascript\" src=\""+ThreadLocalPage.get().getAbsoluteLocation()+"/javascript/"+script+"\"></script>");
}
}
for(Map.Entry<String,String> headEntry : customHeadNoDuplicates.entrySet()) {
sout.println("<!-- " + headEntry.getKey() + " -->");
sout.println(headEntry.getValue());
}
for(String headEntry : customHeads) {
sout.println(headEntry);
}
sout.println("</head>");
sout.print("<body id=\""+this.getPageName()+"\">");
renderLogSqlMessage();
renderIncomingSuccessMessages();
s.flush();
sout.write(s.toString());
if(this.isLogSqlEnabled()){
if(logSqlCheckAccess()){
sout.print("<hr/><div class=\"logsql\">");
utils.HibernateLog.printHibernateLog(sout, this, null);
sout.print("</div>");
}
else{
sout.print("<hr/><div class=\"logsql\">Access to SQL logs was denied.</div>");
}
}
sout.print("</body>");
sout.println("</html>");
ThreadLocalOut.popChecked(sout);
return sw.toString();
}
//ajax/js runtime request related
protected abstract void initializeBasics(AbstractPageServlet ps, Object[] args);
public boolean isServingAsAjaxResponse = false;
public void serveAsAjaxResponse(AbstractPageServlet ps, Object[] args, TemplateCall templateArg)
{ //use passed PageServlet ps here, since this is the context for this type of response
initializeBasics(ps, args);
ThreadLocalPage.set(this);
//outputstream threadlocal is already set, see to-java-servlet/ajax/ajax.str
this.isServingAsAjaxResponse = true;
templateservlet.render(null, args, Environment.createNewLocalEnvironment(envGlobalAndSession), null); // new clean environment with only the global templates, and global/session vars
ThreadLocalPage.set(ps);
}
protected boolean isTemplate() { return false; }
public static AbstractPageServlet getRequestedPage(){
return ThreadLocalPage.get();
}
private boolean passedThroughAjaxTemplate = false;
public boolean passedThroughAjaxTemplate(){
return passedThroughAjaxTemplate;
}
public void setPassedThroughAjaxTemplate(boolean b){
passedThroughAjaxTemplate = b;
}
protected boolean isLogSqlEnabled = false;
public boolean isLogSqlEnabled() { return isLogSqlEnabled; }
public boolean isPageCacheDisabled = false;
protected boolean isOptimizationEnabled = true;
public boolean isOptimizationEnabled() { return isOptimizationEnabled; }
public String getExtraQueryAruments(String firstChar) { // firstChar is expeced to be ? or &, depending on wether there are more query aruments
String res = "";
if(!isOptimizationEnabled || isLogSqlEnabled) {
res = firstChar;
if(isLogSqlEnabled) res += "logsql";
if(isLogSqlEnabled && !isOptimizationEnabled) res += "&";
if(!isOptimizationEnabled) res += "disableopt";
}
return res;
}
public abstract String getPageName();
public abstract String getUniqueName();
protected MessageDigest messageDigest = null;
public MessageDigest getMessageDigest(){
if(messageDigest == null){
try{
messageDigest = MessageDigest.getInstance("MD5");
}
catch(NoSuchAlgorithmException ae)
{
org.webdsl.logging.Logger.error("MD5 not available: "+ae.getMessage());
return null;
}
}
return messageDigest;
}
public boolean actionToBeExecutedHasDisabledValidation = false;
public boolean actionHasAjaxPageUpdates = false;
//TODO merge getActionTarget and getPageUrlWithParams
public String getActionTarget() {
if (isServingAsAjaxResponse){
return this.getUniqueName();
}
return getPageName();
}
//TODO merge getActionTarget and getPageUrlWithParams
public String getPageUrlWithParams(){ //used for action field in forms
if(isServingAsAjaxResponse){
return ThreadLocalPage.get().getAbsoluteLocation()+"/"+ThreadLocalPage.get().getActionTarget();
}
else{
//this doesn't work with ajax template render from action, since an ajax template needs to submit to a different page than the original request
return request.getRequestURL().toString();
}
}
protected abstract void renderIncomingSuccessMessages();
protected abstract void renderLogSqlMessage();
public boolean isPostRequest(){
return ThreadLocalServlet.get().isPostRequest;
}
public boolean isNotPostRequest(){
return !ThreadLocalServlet.get().isPostRequest;
}
public boolean isAjaxTemplateRequest(){
return ThreadLocalServlet.get().getPages().get(ThreadLocalServlet.get().getRequestedPage()).isAjaxTemplate();
}
public abstract String getHiddenParams();
public abstract String getUrlQueryParams();
public abstract String getHiddenPostParamsJson();
//public javax.servlet.http.HttpSession session;
public static void cleanupThreadLocals(){
ThreadLocalEmailContext.set(null);
ThreadLocalPage.set(null);
ThreadLocalTemplate.setNull();
}
//templates scope
public static Environment staticEnv = Environment.createSharedEnvironment();
public Environment envGlobalAndSession = Environment.createLocalEnvironment();
//emails
protected static Map<String, Class<?>> emails = new HashMap<String, Class<?>>();
public static Map<String, Class<?>> getEmails() {
return emails;
}
public boolean sendEmail(String name, Object[] emailargs, Environment emailenv){
EmailServlet temp = renderEmail(name,emailargs,emailenv);
return temp.send();
}
public EmailServlet renderEmail(String name, Object[] emailargs, Environment emailenv){
EmailServlet temp = null;
try
{
temp = ((EmailServlet)getEmails().get(name).newInstance());
}
catch(IllegalAccessException iae)
{
org.webdsl.logging.Logger.error("Problem in email template lookup: " + iae.getMessage());
}
catch(InstantiationException ie)
{
org.webdsl.logging.Logger.error("Problem in email template lookup: " + ie.getMessage());
}
temp.render(emailargs, emailenv);
return temp;
}
//rendertemplate function
public String renderTemplate(String name, Object[] args, Environment env){
return executeTemplatePhase(RENDER_PHASE, name, args, env);
}
//validatetemplate function
public String validateTemplate(String name, Object[] args, Environment env){
return executeTemplatePhase(VALIDATE_PHASE, name, args, env);
}
public static final int DATABIND_PHASE = 1;
public static final int VALIDATE_PHASE = 2;
public static final int ACTION_PHASE = 3;
public static final int RENDER_PHASE = 4;
public String executeTemplatePhase(int phase, String name, Object[] args, Environment env){
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
TemplateServlet enclosingTemplateObject = ThreadLocalTemplate.get();
try{
TemplateServlet temp = ((TemplateServlet)env.getTemplate(name).newInstance());
switch(phase){
case VALIDATE_PHASE: temp.validateInputs(name, args, env, null); break;
case RENDER_PHASE: temp.render(name, args, env, null); break;
}
}
catch(Exception oe){
try {
TemplateCall tcall = env.getWithcall(name); //'elements' or requires arg
TemplateServlet temp = ((TemplateServlet)env.getTemplate(tcall.name).newInstance());
String parent = env.getWithcall(name)==null?null:env.getWithcall(name).parentName;
switch(phase){
case VALIDATE_PHASE: temp.validateInputs(parent, tcall.args, env, null); break;
case RENDER_PHASE: temp.render(parent, tcall.args, env, null); break;
}
}
catch(Exception ie){
org.webdsl.logging.Logger.error("EXCEPTION",oe);
org.webdsl.logging.Logger.error("EXCEPTION",ie);
}
}
ThreadLocalTemplate.set(enclosingTemplateObject);
ThreadLocalOut.popChecked(out);
return s.toString();
}
//ref arg
protected static Map<String, Class<?>> refargclasses = new HashMap<String, Class<?>>();
public static Map<String, Class<?>> getRefArgClasses() {
return refargclasses;
}
public abstract String getAbsoluteLocation();
protected TemplateContext templateContext = new TemplateContext();
public String getTemplateContextString() {
return templateContext.getTemplateContextString();
}
public void enterTemplateContext(String s) {
templateContext.enterTemplateContext(s);
}
public void leaveTemplateContext() {
templateContext.leaveTemplateContext();
}
//verifies that the correct context was popped
public void leaveTemplateContextChecked(String s) {
templateContext.leaveTemplateContextChecked(s);
}
public void clearTemplateContext(){
templateContext.clearTemplateContext();
}
public void setTemplateContext(TemplateContext tc){
templateContext = tc;
}
public TemplateContext getTemplateContext(){
return templateContext;
}
// objects scheduled to be checked after action completes, filled by hibernate event listener in hibernate util class
ArrayList<WebDSLEntity> entitiesToBeValidated = new ArrayList<WebDSLEntity>();
boolean allowAddingEntitiesForValidation = true;
public void clearEntitiesToBeValidated(){
entitiesToBeValidated = new ArrayList<WebDSLEntity>();
allowAddingEntitiesForValidation = true;
}
public void addEntityToBeValidated(WebDSLEntity w){
if(allowAddingEntitiesForValidation){
entitiesToBeValidated.add(w);
}
}
public void validateEntities(){
allowAddingEntitiesForValidation = false; //adding entities must be disabled when checking is performed, new entities may be loaded for checks, but do not have to be checked themselves
java.util.Set<WebDSLEntity> set = new java.util.HashSet<WebDSLEntity>(entitiesToBeValidated);
java.util.List<utils.ValidationException> exceptions = new java.util.LinkedList<utils.ValidationException>();
for(WebDSLEntity w : set){
if(w.isChanged()){
try {
// System.out.println("validating: "+ w.get_WebDslEntityType() + ":" + w.getName());
w.validateSave();
//System.out.println("done validating");
} catch(utils.ValidationException ve){
exceptions.add(ve);
} catch(utils.MultipleValidationExceptions ve) {
for(utils.ValidationException vex : ve.getValidationExceptions()){
exceptions.add(vex);
}
}
}
}
if(exceptions.size() > 0){
throw new utils.MultipleValidationExceptions(exceptions);
}
clearEntitiesToBeValidated();
}
protected List<utils.ValidationException> validationExceptions = new java.util.LinkedList<utils.ValidationException>();
public List<utils.ValidationException> getValidationExceptions() {
return validationExceptions;
}
public void addValidationException(String name, String message){
validationExceptions.add(new ValidationException(name,message));
}
public List<utils.ValidationException> getValidationExceptionsByName(String name) {
List<utils.ValidationException> list = new java.util.LinkedList<utils.ValidationException>();
for(utils.ValidationException v : validationExceptions){
if(v.getName().equals(name)){
list.add(v);
}
}
return list;
}
public List<String> getValidationErrorsByName(String name) {
List<String> list = new java.util.ArrayList<String>();
for(utils.ValidationException v : validationExceptions){
if(v.getName().equals(name)){
list.add(v.getErrorMessage());
}
}
return list;
}
public boolean hasExecutedAction = false;
public boolean hasExecutedAction(){ return hasExecutedAction; }
public boolean hasNotExecutedAction(){ return !hasExecutedAction; }
protected boolean abortTransaction = false;
public boolean isTransactionAborted(){ return abortTransaction; }
public void abortTransaction(){ abortTransaction = true; }
public java.util.List<String> ignoreset= new java.util.ArrayList<String>();
public boolean hibernateCacheCleared = false;
protected java.util.List<String> javascripts = new java.util.ArrayList<String>();
protected java.util.List<String> stylesheets = new java.util.ArrayList<String>();
protected java.util.List<String> customHeads = new java.util.ArrayList<String>();
protected java.util.Map<String,String> customHeadNoDuplicates = new java.util.HashMap<String,String>();
public void addJavascriptInclude(String filename) {
if(!javascripts.contains(filename))
javascripts.add(filename);
}
public void addStylesheetInclude(String filename) {
if(!stylesheets.contains(filename)){
stylesheets.add(filename);
}
}
public void addStylesheetInclude(String filename, String media) {
String combined = media != null && !media.isEmpty() ? filename + "\" media=\""+ media : filename;
if(!stylesheets.contains(combined)){
stylesheets.add(combined);
}
}
public void addCustomHead(String header) {
customHeads.add(header);
}
public void addCustomHead(String key, String header) {
customHeadNoDuplicates.put(key, header);
}
protected abstract void initialize();
protected abstract void conversion();
protected abstract void loadArguments();
protected abstract void initVarsAndArgs();
public void clearHibernateCache() {
// used to be only ' hibSession.clear(); ' but that doesn't revert already flushed changes.
// since flushing now happens automatically when querying, this could produce wrong results.
// e.g. output in page with validation errors shows changes that were not persisted to the db.
// see regression test in test/succeed-web/validate-false-and-flush.app
utils.HibernateUtil.getCurrentSession().getTransaction().rollback();
openNewTransactionThroughGetCurrentSession();
ThreadLocalServlet.get().loadSessionManager(hibernateSession);
initVarsAndArgs();
hibernateCacheCleared = true;
}
protected org.hibernate.Session openNewTransactionThroughGetCurrentSession(){
hibernateSession = utils.HibernateUtil.getCurrentSession();
hibernateSession.beginTransaction();
return hibernateSession;
}
protected HttpServletRequest request;
protected HttpServletResponse response;
protected Object[] args;
// public void setHibSession(Session s) {
// hibSession = s;
// public Session getHibSession() {
// return hibSession;
public HttpServletRequest getRequest() {
return request;
}
public HttpServletResponse getResponse() {
return response;
}
protected boolean validated=true;
/*
* when this is true, it can mean:
* 1 no validation has been performed yet
* 2 some validation has been performed without errors
* 3 all validation has been performed without errors
*/
public boolean isValid() {
return validated;
}
public boolean isNotValid() {
return !validated;
}
public void setValidated(boolean validated) {
this.validated = validated;
}
/*
* complete action regularly but rollback hibernate session
* skips validation of entities at end of action, if validation messages are necessary
* use cancel() instead of rollback()
* can be used to replace templates with ajax without saving, e.g. for validation
*/
protected boolean rollback = false;
public boolean isRollback() {
return rollback;
}
public void setRollback() {
//by setting validated true, the action will succeed
this.setValidated(true);
//the session will be rolled back, to cancel persisting any changes
this.rollback = true;
}
public List<String> failedCaptchaResponses = new ArrayList<String>();
protected boolean inSubmittedForm = false;
public boolean inSubmittedForm() {
return inSubmittedForm;
}
public void setInSubmittedForm(boolean b) {
this.inSubmittedForm = b;
}
// used for runtime check to detect nested forms
protected String inForm = null;
public boolean isInForm() {
return inForm != null;
}
public void enterForm(String t) {
inForm = t;
}
public String getEnclosingForm() {
return inForm;
}
public void leaveForm() {
inForm = null;
}
public void clearParammaps(){
parammap.clear();
parammapvalues.clear();
fileUploads.clear();
}
protected java.util.Map<String, String> parammap;
public java.util.Map<String, String> getParammap() {
return parammap;
}
protected Map<String,List<utils.File>> fileUploads;
public Map<String, List<utils.File>> getFileUploads() {
return fileUploads;
}
public List<utils.File> getFileUploads(String key) {
return fileUploads.get(key);
}
protected Map<String, List<String>> parammapvalues;
public Map<String, List<String>> getParammapvalues() {
return parammapvalues;
}
protected String pageTitle = "";
public String getPageTitle() {
return pageTitle;
}
public void setPageTitle(String pageTitle) {
this.pageTitle = pageTitle;
}
protected String formIdent = "";
public String getFormIdent() {
return formIdent;
}
public void setFormIdent(String fi) {
this.formIdent = fi;
}
protected boolean actionLinkUsed = false;
public boolean isActionLinkUsed() {
return actionLinkUsed;
}
public void setActionLinkUsed(boolean a) {
this.actionLinkUsed = a;
}
protected boolean ajaxRuntimeRequest = false;
public boolean isAjaxRuntimeRequest() {
return ajaxRuntimeRequest;
}
public void setAjaxRuntimeRequest(boolean a) {
ajaxRuntimeRequest = a;
}
protected String redirectUrl = "";
public boolean isRedirected(){
return !"".equals(redirectUrl);
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String a) {
this.redirectUrl = a;
}
// perform the actual redirect
public void redirect(){
try { response.sendRedirect(this.getRedirectUrl()); }
catch (IOException ioe) { org.webdsl.logging.Logger.error("redirect failed", ioe); }
}
protected String mimetype = "text/html; charset=UTF-8";
protected boolean mimetypeChanged = false;
public String getMimetype() {
return mimetype;
}
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
mimetypeChanged = true;
if(!isMarkupLangMimeType.matcher(mimetype).find()){
enableRawoutput();
}
disableTemplateSpans();
}
protected boolean downloadInline = false;
public boolean getDownloadInline() {
return downloadInline;
}
public void enableDownloadInline() {
this.downloadInline = true;
}
protected boolean ajaxActionExecuted = false;
public boolean isAjaxActionExecuted() {
return ajaxActionExecuted;
}
public void enableAjaxActionExecuted() {
ajaxActionExecuted = true;
}
protected boolean rawoutput = false;
public boolean isRawoutput() {
return rawoutput;
}
public void enableRawoutput() {
rawoutput = true;
}
public void disableRawoutput() {
rawoutput = false;
}
protected String[] pageArguments = null;
public void setPageArguments(String[] pa) {
pageArguments = pa;
}
public String[] getPageArguments() {
return pageArguments;
}
protected String httpMethod = null;
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public String getHttpMethod() {
return httpMethod;
}
protected boolean templateSpans = true;
public boolean templateSpans() {
return templateSpans;
}
public void disableTemplateSpans() {
templateSpans = false;
}
protected List<String> reRenderPlaceholders = null;
protected Map<String,String> reRenderPlaceholdersContent = null;
public boolean isReRenderPlaceholders() {
return reRenderPlaceholders != null;
}
public void addReRenderPlaceholders(String placeholder) {
if(reRenderPlaceholders == null){
reRenderPlaceholders = new ArrayList<String>();
reRenderPlaceholdersContent = new HashMap<String,String>();
}
reRenderPlaceholders.add(placeholder);
}
public void addReRenderPlaceholdersContent(String placeholder, String content) {
if(reRenderPlaceholders != null && reRenderPlaceholders.contains(placeholder)){
reRenderPlaceholdersContent.put(placeholder,content);
}
}
protected utils.File download = null;
public void setDownload(utils.File file){
this.download = file;
}
public boolean isDownloadSet(){
return this.download != null;
}
protected void download()
{
/*
Long id = download.getId();
org.hibernate.Session hibSession = HibernateUtilConfigured.getSessionFactory().openSession();
hibSession.beginTransaction();
hibSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
utils.File download = (utils.File)hibSession.load(utils.File.class,id);
*/
try
{
javax.servlet.ServletOutputStream outstream;
outstream = response.getOutputStream();
java.sql.Blob blob = download.getContent();
java.io.InputStream in;
in = blob.getBinaryStream();
response.setContentType(download.getContentType());
if(!downloadInline) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + download.getFileName() + "\"");
}
java.io.BufferedOutputStream bufout = new java.io.BufferedOutputStream(outstream);
byte bytes[] = new byte[32768];
int index = in.read(bytes, 0, 32768);
while(index != -1)
{
bufout.write(bytes, 0, index);
index = in.read(bytes, 0, 32768);
}
bufout.flush();
}
catch(java.sql.SQLException ex)
{
org.webdsl.logging.Logger.error("exception in download serve");
org.webdsl.logging.Logger.error("EXCEPTION",ex);
}
catch (IOException ex) {
org.webdsl.logging.Logger.error("exception in download serve");
org.webdsl.logging.Logger.error("EXCEPTION",ex);
}
/*
hibSession.flush();
hibSession.getTransaction().commit();
*/
}
//data validation
public java.util.LinkedList<String> validationContext = new java.util.LinkedList<String>();
public String getValidationContext() {
//System.out.println("using" + validationContext.peek());
return validationContext.peek();
}
public void enterValidationContext(String ident) {
validationContext.add(ident);
//System.out.println("entering" + ident);
}
public void leaveValidationContext() {
/*String s = */ validationContext.removeLast();
//System.out.println("leaving" +s);
}
public boolean inValidationContext() {
return validationContext.size() != 0;
}
//form
public boolean formRequiresMultipartEnc = false;
//formGroup
public String formGroupLeftSize = "150";
//public java.util.Stack<utils.FormGroupContext> formGroupContexts = new java.util.Stack<utils.FormGroupContext>();
public utils.FormGroupContext getFormGroupContext() {
return (utils.FormGroupContext) tableContexts.peek();
}
public void enterFormGroupContext() {
tableContexts.push(new utils.FormGroupContext());
}
public void leaveFormGroupContext() {
tableContexts.pop();
}
public boolean inFormGroupContext() {
return !tableContexts.empty() && tableContexts.peek() instanceof utils.FormGroupContext;
}
public java.util.Stack<String> formGroupContextClosingTags = new java.util.Stack<String>();
public void formGroupContextsCheckEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInDoubleColumnContext()){ // ignore defaults when in scope of a double column
if(!temp.isInColumnContext()){ //don't nest left and right
temp.enterColumnContext();
if(temp.isInLeftContext()) {
out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">");
formGroupContextClosingTags.push("left");
temp.toRightContext();
}
else {
out.print("<div style=\"float: left;\">");
formGroupContextClosingTags.push("right");
temp.toLeftContext();
}
}
else{
formGroupContextClosingTags.push("none");
}
}
}
}
public void formGroupContextsCheckLeave(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInDoubleColumnContext()) {
String tags = formGroupContextClosingTags.pop();
if(tags.equals("left")){
//temp.toRightContext();
temp.leaveColumnContext();
out.print("</div>");
}
else if(tags.equals("right")){
//temp.toLeftContext();
temp.leaveColumnContext();
out.print("</div>");
}
}
}
}
public void formGroupContextsDisplayLeftEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInColumnContext()){
temp.enterColumnContext();
out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">");
formGroupContextClosingTags.push("left");
temp.toRightContext();
}
else{
formGroupContextClosingTags.push("none");
}
}
}
public void formGroupContextsDisplayRightEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInColumnContext()){
temp.enterColumnContext();
out.print("<div style=\"float: left;\">");
formGroupContextClosingTags.push("right");
temp.toLeftContext();
}
else{
formGroupContextClosingTags.push("none");
}
}
}
//label
public String getLabelString() {
return getLabelStringForTemplateContext(ThreadLocalTemplate.get().getUniqueId());
}
public java.util.Stack<String> labelStrings = new java.util.Stack<String>();
public java.util.Set<String> usedPageElementIds = new java.util.HashSet<String>();
public static java.util.Random rand = new java.util.Random();
//avoid duplicate ids; if multiple inputs are in a label, only the first is connected to the label
public String getLabelStringOnce() {
String s = labelStrings.peek();
if(usedPageElementIds.contains(s)){
do{
s += rand.nextInt();
}
while(usedPageElementIds.contains(s));
}
usedPageElementIds.add(s);
return s;
}
public java.util.Map<String,String> usedPageElementIdsTemplateContext = new java.util.HashMap<String,String>();
//subsequent calls from the same defined template (e.g. in different phases) should produce the same id
public String getLabelStringForTemplateContext(String context) {
String labelid = usedPageElementIdsTemplateContext.get(context);
if(labelid == null){
labelid = getLabelStringOnce();
usedPageElementIdsTemplateContext.put(context, labelid);
}
return labelid;
}
public void enterLabelContext(String ident) {
labelStrings.push(ident);
}
public void leaveLabelContext() {
labelStrings.pop();
}
public boolean inLabelContext() {
return !labelStrings.empty();
}
//section
public int sectionDepth = 0;
public int getSectionDepth() {
return sectionDepth;
}
public void enterSectionContext() {
sectionDepth++;
}
public void leaveSectionContext() {
sectionDepth
}
public boolean inSectionContext() {
return sectionDepth > 0;
}
//table
public java.util.Stack<Object> tableContexts = new java.util.Stack<Object>();
public utils.TableContext getTableContext() {
return (utils.TableContext) tableContexts.peek();
}
public void enterTableContext() {
tableContexts.push(new utils.TableContext());
}
public void leaveTableContext() {
tableContexts.pop();
}
public boolean inTableContext() {
return !tableContexts.empty() && tableContexts.peek() instanceof utils.TableContext;
}
public java.util.Stack<String> tableContextClosingTags = new java.util.Stack<String>();
//separate row and column checks, used by label
public void rowContextsCheckEnter(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
if(!x_temp.isInRowContext()) {
out.print("<tr>");
x_temp.enterRowContext();
tableContextClosingTags.push("</tr>");
}
else{
tableContextClosingTags.push("");
}
}
}
public void rowContextsCheckLeave(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
String tags = tableContextClosingTags.pop();
if(tags.equals("</tr>")){
x_temp.leaveRowContext();
out.print(tags);
}
}
}
public void columnContextsCheckEnter(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
if(x_temp.isInRowContext() && !x_temp.isInColumnContext()) {
out.print("<td>");
x_temp.enterColumnContext();
tableContextClosingTags.push("</td>");
}
else{
tableContextClosingTags.push("");
}
}
}
public void columnContextsCheckLeave(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
String tags = tableContextClosingTags.pop();
if(tags.equals("</td>")){
x_temp.leaveColumnContext();
out.print(tags);
}
}
}
//request vars
public HashMap<String, Object> requestScopedVariables = new HashMap<String, Object>();
public void initRequestVars(){
initRequestVars(null);
}
public abstract void initRequestVars(PrintWriter out);
protected long startTime = 0L;
public long getStartTime() {
return startTime;
}
public long getElapsedTime() {
return System.currentTimeMillis() - startTime;
}
public void addRequestScopedVar(String key, Object val){
if(val != null){
requestScopedVariables.put(key, val);
}
}
public void addRequestScopedVar(String key, WebDSLEntity val){
if(val != null){
val.setRequestVar();
requestScopedVariables.put(key, val);
}
}
public PegDownProcessor getPegDownProcessor(){
if (pegDownProcessor == null)
pegDownProcessor = new PegDownProcessor( Extensions.ALL, WikiFormatter.PARSE_TIMEOUT_MS );
return pegDownProcessor;
}
public PegDownProcessor getPegDownProcessorNoHardWraps(){
if (pegDownProcessorNoHardWraps == null)
pegDownProcessorNoHardWraps = new PegDownProcessor( Extensions.ALL & ~Extensions.HARDWRAPS , WikiFormatter.PARSE_TIMEOUT_MS );
return pegDownProcessorNoHardWraps;
}
// statistics to be shown in log
protected abstract void increaseStatReadOnly();
protected abstract void increaseStatReadOnlyFromCache();
protected abstract void increaseStatUpdate();
protected abstract void increaseStatActionFail();
protected abstract void increaseStatActionReadOnly();
protected abstract void increaseStatActionUpdate();
// register whether entity changes were made, see isChanged property of entities
public boolean readOnlyRequestStats = true;
protected void updatePageRequestStatistics(){
if(hasNotExecutedAction()){
if(readOnlyRequestStats || isRollback()){
if(pageCacheWasUsed){
increaseStatReadOnlyFromCache();
}
else{
increaseStatReadOnly();
}
}
else{
increaseStatUpdate();
}
}
else{
if(isNotValid()){
increaseStatActionFail();
}
else{
if(readOnlyRequestStats || isRollback()){
increaseStatActionReadOnly();
}
else{
increaseStatActionUpdate();
}
}
}
}
}
|
package de.meetr.hdr.paperless.model;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xmlpull.v1.XmlPullParser;
import android.util.Xml;
public class Paper {
public static final String FILENAME_EXTENSION = ".plf";
private static final String XML_ROOT = "paperless";
private static final String XML_CREATION = "creationDate";
private static final String XML_MODIFIED = "lastModified";
private static final String XML_NAME = "documentName";
private static final String XML_NUMPAGES = "numberOfPages";
private static final String XML_PAGES = "pages";
private long creationDate;
private long lastModified;
private String documentName;
private int numberOfPages;
private List<Page> pages = new ArrayList<Page>();
private File file;
private boolean changed = false;
public Paper(String documentName) {
this.creationDate = this.lastModified = System.currentTimeMillis();
this.documentName = documentName;
this.numberOfPages = 0;
}
public long getCreationDate() {
return creationDate;
}
public void setCreationDate(long creationDate) {
this.creationDate = creationDate;
this.changed = true;
}
public long getLastModified() {
return lastModified;
}
public void setLastModified(long lastModified) {
this.lastModified = lastModified;
this.changed = true;
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
this.changed = true;
}
public int getNumberOfPages() {
return numberOfPages;
}
public void setNumberOfPages(int numberOfPages) {
this.numberOfPages = numberOfPages;
this.changed = true;
}
public Page addNewPage(int w, int h) {
return this.addNewPage(w, h, this.numberOfPages+1);
}
public Page addNewPage(int w, int h, int pageNumber) {
Page p = new Page(this, w, h);
this.pages.add(p);
return p;
}
public OutputStream getOutputStreamForPage(long identifier, int layer) throws Exception {
ZipOutputStream os = new ZipOutputStream(new FileOutputStream(this.file));
os.putNextEntry(new ZipEntry(identifier + "_" + layer + ".png"));
return os;
}
public void saveToFile(File f) throws ParserConfigurationException, IOException, TransformerException {
// Build the meta file
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// Root element
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement(XML_ROOT);
doc.appendChild(rootElement);
// Meta-data
// CreationDate
Element creationDate = doc.createElement(XML_CREATION);
creationDate.appendChild(doc.createTextNode("" + this.creationDate));
rootElement.appendChild(creationDate);
// LastModified (NOW)
Element lastModified = doc.createElement(XML_MODIFIED);
lastModified.appendChild(doc.createTextNode("" + System.currentTimeMillis()));
rootElement.appendChild(lastModified);
// DocumentName
Element documentName = doc.createElement(XML_NAME);
documentName.appendChild(doc.createTextNode(this.documentName));
rootElement.appendChild(documentName);
// NumberOfPages
Element numberOfPages = doc.createElement(XML_NUMPAGES);
numberOfPages.appendChild(doc.createTextNode("" + this.numberOfPages));
rootElement.appendChild(numberOfPages);
// Order of pages
Element pages = doc.createElement(XML_PAGES);
// TODO: add pages
rootElement.appendChild(pages);
// Write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
ZipOutputStream os = new ZipOutputStream(new FileOutputStream(f));
os.putNextEntry(new ZipEntry("meta.xml"));
StreamResult result = new StreamResult(os);
transformer.transform(source, result);
os.close();
this.file = f;
}
public static Paper openFile(File f) throws Exception {
ZipFile zipFile = new ZipFile(f);
ZipEntry entry = zipFile.getEntry("meta.xml");
InputStream is = zipFile.getInputStream(entry);
String documentName = null;
long creationDate = 0;
long lastModified = 0;
int numberOfPages = 0;
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
parser.nextTag();
parser.require(XmlPullParser.START_TAG, null, XML_ROOT);
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (name.equals(XML_NAME)) {
if (parser.next() == XmlPullParser.TEXT)
documentName = parser.getText();
} else if (name.equals(XML_CREATION)) {
if (parser.next() == XmlPullParser.TEXT)
creationDate = Long.parseLong(parser.getText());
} else if (name.equals(XML_MODIFIED)) {
if (parser.next() == XmlPullParser.TEXT)
lastModified = Long.parseLong(parser.getText());
} else if (name.equals(XML_NUMPAGES)) {
if (parser.next() == XmlPullParser.TEXT)
numberOfPages = Integer.parseInt(parser.getText());
} else {
skip(parser);
continue;
}
parser.nextTag();
}
if (null == documentName)
return null;
Paper p = new Paper(documentName);
p.creationDate = creationDate;
p.lastModified = lastModified;
p.numberOfPages = numberOfPages;
p.file = f;
return p;
}
private static void skip(XmlPullParser parser) throws Exception {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
|
package org.minimalj.frontend.swing.toolkit;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.SwingWorker;
import javax.swing.SwingWorker.StateValue;
import org.minimalj.frontend.toolkit.ProgressListener;
public class SwingHeavyActionButton extends JButton {
private static final long serialVersionUID = 1L;
public SwingHeavyActionButton(Action action) {
super(action);
}
public SwingHeavyActionButton(String text) {
super(text);
}
@Override
protected void fireActionPerformed(final ActionEvent event) {
final ProgressListener progress = SwingClientToolkit.showProgress(this, "Waiting");
SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
// ApplicationContext.setApplicationContext(SwingTab.this.getApplicationContext());
SwingHeavyActionButton.super.fireActionPerformed(event);
setProgress(100);
return null;
}
};
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
progress.showProgress((Integer) evt.getNewValue(), 100);
} else if ("state".equals(evt.getPropertyName()) && evt.getNewValue() == StateValue.DONE) {
progress.showProgress(100, 100);
}
}
});
worker.execute();
}
}
|
package com.thomas15v.NoAdver.sponge;
import com.thomas15v.NoAdver.util.IgnoreAbleListener;
import com.thomas15v.NoAdver.plugin.Plugin;
import org.spongepowered.api.event.entity.living.player.PlayerChatEvent;
import org.spongepowered.api.util.event.Event;
import org.spongepowered.api.util.event.Order;
import org.spongepowered.api.util.event.Subscribe;
public class SpongeChatListener extends IgnoreAbleListener<Event> {
private Plugin plugin;
public SpongeChatListener(Plugin plugin){
this.plugin = plugin;
}
@Subscribe(order = Order.LAST, ignoreCancelled = true)
public void onChat(PlayerChatEvent event){
if (isIgnore(event))
removeIgnored(event);
else
plugin.checkEvent(new SpongeChatMessage(event));
}
}
|
package de.bwaldvogel.liblinear;
import static de.bwaldvogel.liblinear.Linear.info;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Trust Region Newton Method optimization
*/
class Tron {
private final Function fun_obj;
private final double eps;
private final int max_iter;
private final double eps_cg;
Tron(Function fun_obj, double eps, int max_iter, double eps_cg) {
this.fun_obj = fun_obj;
this.eps = eps;
this.max_iter = max_iter;
this.eps_cg = eps_cg;
}
void tron(double[] w) {
// Parameters for updating the iterates.
double eta0 = 1e-4, eta1 = 0.25, eta2 = 0.75;
// Parameters for updating the trust region size delta.
double sigma1 = 0.25, sigma2 = 0.5, sigma3 = 4;
int n = fun_obj.get_nr_variable();
int i, cg_iter;
double delta = 0, sMnorm, one = 1.0;
double alpha, f, fnew, prered, actred, gs;
int search = 1, iter = 1;
double[] s = new double[n];
double[] r = new double[n];
double[] g = new double[n];
double alpha_pcg = 0.01;
double[] M = new double[n];
// calculate gradient norm at w=0 for stopping condition.
double[] w0 = new double[n];
for (i = 0; i < n; i++)
w0[i] = 0;
fun_obj.fun(w0);
fun_obj.grad(w0, g);
double gnorm0 = euclideanNorm(g);
f = fun_obj.fun(w);
fun_obj.grad(w, g);
double gnorm = euclideanNorm(g);
if (gnorm <= eps * gnorm0)
search = 0;
fun_obj.get_diagH(M);
for (i = 0; i < n; i++)
M[i] = (1 - alpha_pcg) + alpha_pcg * M[i];
delta = Math.sqrt(uTMv(n, g, M, g));
double[] w_new = new double[n];
AtomicBoolean reach_boundary = new AtomicBoolean();
boolean delta_adjusted = false;
while (iter <= max_iter && search != 0) {
cg_iter = trpcg(delta, g, M, s, r, reach_boundary);
System.arraycopy(w, 0, w_new, 0, n);
daxpy(one, s, w_new);
gs = dot(g, s);
prered = -0.5 * (gs - dot(s, r));
fnew = fun_obj.fun(w_new);
// Compute the actual reduction.
actred = f - fnew;
// On the first iteration, adjust the initial step bound.
sMnorm = Math.sqrt(uTMv(n, s, M, s));
if (iter == 1 && !delta_adjusted) {
delta = Math.min(delta, sMnorm);
delta_adjusted = true;
}
// Compute prediction alpha*sMnorm of the step.
if (fnew - f - gs <= 0)
alpha = sigma3;
else
alpha = Math.max(sigma1, -0.5 * (gs / (fnew - f - gs)));
// Update the trust region bound according to the ratio of actual to
// predicted reduction.
if (actred < eta0 * prered)
delta = Math.min(alpha * sMnorm, sigma2 * delta);
else if (actred < eta1 * prered)
delta = Math.max(sigma1 * delta, Math.min(alpha * sMnorm, sigma2 * delta));
else if (actred < eta2 * prered)
delta = Math.max(sigma1 * delta, Math.min(alpha * sMnorm, sigma3 * delta));
else {
if (reach_boundary.get()) {
delta = sigma3 * delta;
} else {
delta = Math.max(delta, Math.min(alpha * sMnorm, sigma3 * delta));
}
}
info("iter %2d act %5.3e pre %5.3e delta %5.3e f %5.3e |g| %5.3e CG %3d%n", iter, actred, prered, delta, f, gnorm, cg_iter);
if (actred > eta0 * prered) {
iter++;
System.arraycopy(w_new, 0, w, 0, n);
f = fnew;
fun_obj.grad(w, g);
fun_obj.get_diagH(M);
for (i = 0; i < n; i++)
M[i] = (1 - alpha_pcg) + alpha_pcg * M[i];
gnorm = euclideanNorm(g);
if (gnorm <= eps * gnorm0)
break;
}
if (f < -1.0e+32) {
info("WARNING: f < -1.0e+32%n");
break;
}
if (prered <= 0) {
info("WARNING: prered <= 0%n");
break;
}
if (Math.abs(actred) <= 1.0e-12 * Math.abs(f) && Math.abs(prered) <= 1.0e-12 * Math.abs(f)) {
info("WARNING: actred and prered too small%n");
break;
}
}
}
private int trpcg(double delta, double[] g, double[] M, double[] s, double[] r, AtomicBoolean reach_boundary) {
int n = fun_obj.get_nr_variable();
double one = 1;
double[] d = new double[n];
double[] Hd = new double[n];
double zTr, znewTrnew, alpha, beta, cgtol;
double[] z = new double[n];
reach_boundary.set(false);
for (int i = 0; i < n; i++) {
s[i] = 0;
r[i] = -g[i];
z[i] = r[i] / M[i];
d[i] = z[i];
}
zTr = dot(z, r);
cgtol = eps_cg * Math.sqrt(zTr);
int cg_iter = 0;
while (true) {
if (Math.sqrt(zTr) <= cgtol)
break;
cg_iter++;
fun_obj.Hv(d, Hd);
alpha = zTr / dot(d, Hd);
daxpy(alpha, d, s);
double sMnorm = Math.sqrt(uTMv(n, s, M, s));
if (sMnorm > delta) {
info("cg reaches trust region boundary%n");
reach_boundary.set(true);
alpha = -alpha;
daxpy(alpha, d, s);
double sTMd = uTMv(n, s, M, d);
double sTMs = uTMv(n, s, M, s);
double dTMd = uTMv(n, d, M, d);
double dsq = delta * delta;
double rad = Math.sqrt(sTMd * sTMd + dTMd * (dsq - sTMs));
if (sTMd >= 0)
alpha = (dsq - sTMs) / (sTMd + rad);
else
alpha = (rad - sTMd) / dTMd;
daxpy(alpha, d, s);
alpha = -alpha;
daxpy(alpha, Hd, r);
break;
}
alpha = -alpha;
daxpy(alpha, Hd, r);
for (int i = 0; i < n; i++)
z[i] = r[i] / M[i];
znewTrnew = dot(z, r);
beta = znewTrnew / zTr;
scale(beta, d);
daxpy(one, z, d);
zTr = znewTrnew;
}
return (cg_iter);
}
/**
* constant times a vector plus a vector
*
* <pre>
* vector2 += constant * vector1
* </pre>
*
* @since 1.8
*/
private static void daxpy(double constant, double[] vector1, double[] vector2) {
if (constant == 0) return;
assert vector1.length == vector2.length;
for (int i = 0; i < vector1.length; i++) {
vector2[i] += constant * vector1[i];
}
}
/**
* returns the dot product of two vectors
*
* @since 1.8
*/
private static double dot(double[] vector1, double[] vector2) {
double product = 0;
assert vector1.length == vector2.length;
for (int i = 0; i < vector1.length; i++) {
product += vector1[i] * vector2[i];
}
return product;
}
/**
* returns the euclidean norm of a vector
*
* @since 1.8
*/
private static double euclideanNorm(double vector[]) {
int n = vector.length;
if (n < 1) {
return 0;
}
if (n == 1) {
return Math.abs(vector[0]);
}
// this algorithm is (often) more accurate than just summing up the squares and taking the square-root afterwards
double scale = 0; // scaling factor that is factored out
double sum = 1; // basic sum of squares from which scale has been factored out
for (int i = 0; i < n; i++) {
if (vector[i] != 0) {
double abs = Math.abs(vector[i]);
// try to get the best scaling factor
if (scale < abs) {
double t = scale / abs;
sum = 1 + sum * (t * t);
scale = abs;
} else {
double t = abs / scale;
sum += t * t;
}
}
}
return scale * Math.sqrt(sum);
}
/**
* scales a vector by a constant
*
* @since 1.8
*/
private static void scale(double constant, double vector[]) {
if (constant == 1.0) return;
for (int i = 0; i < vector.length; i++) {
vector[i] *= constant;
}
}
private static double uTMv(int n, double[] u, double[] M, double[] v) {
int m = n - 4;
double res = 0;
int i;
for (i = 0; i < m; i += 5)
res += u[i] * M[i] * v[i] + u[i + 1] * M[i + 1] * v[i + 1] + u[i + 2] * M[i + 2] * v[i + 2] +
u[i + 3] * M[i + 3] * v[i + 3] + u[i + 4] * M[i + 4] * v[i + 4];
for (; i < n; i++)
res += u[i] * M[i] * v[i];
return res;
}
}
|
package editor.gui.settings;
import static editor.database.attributes.CardAttribute.CATEGORIES;
import static editor.database.attributes.CardAttribute.COUNT;
import static editor.database.attributes.CardAttribute.DATE_ADDED;
import static editor.database.attributes.CardAttribute.EXPANSION;
import static editor.database.attributes.CardAttribute.MANA_COST;
import static editor.database.attributes.CardAttribute.NAME;
import static editor.database.attributes.CardAttribute.TYPE_LINE;
import java.awt.Color;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import editor.collection.deck.CategorySpec;
import editor.database.attributes.CardAttribute;
import editor.database.version.DatabaseVersion;
import editor.database.version.UpdateFrequency;
import editor.filter.leaf.options.multi.CardTypeFilter;
/**
* Structure containing global settings. This structure consists of immutable
* members and sub-structures and should be created using
* {@link SettingsBuilder}.
*
* @author Alec Roelke
*/
public final class Settings
{
/**
* Sub-structure containing global inventory and card settings.
*
* @author Alec Roelke
*/
public static final class InventorySettings
{
/** Site containing the inventory to download. */
public final String source;
/** Actual inventory file to download (without .zip). */
public final String file;
/** File name containing latest inventory version. */
public final String versionFile;
/** Version of the stored inventory. */
public final DatabaseVersion version;
/** Directory to store inventory file in. */
public final String location;
/** Directory to store card images in. */
public final String scans;
/** File to store tags in. */
public final String tags;
/** Check for inventory update on startup or don't. */
public final UpdateFrequency update;
/** Show warnings from loading inventory. */
public final boolean warn;
/** Card attributes to show in inventory table. */
public final List<CardAttribute> columns;
/** Background color of card image panel. */
public final Color background;
/** Stripe color of inventory table. */
public final Color stripe;
private InventorySettings(String source,
String file,
String versionFile,
DatabaseVersion version,
String location,
String scans,
String tags,
UpdateFrequency update,
boolean warn,
List<CardAttribute> columns,
Color background,
Color stripe)
{
this.source = source;
this.file = file;
this.versionFile = versionFile;
this.version = version;
this.location = location;
this.scans = scans;
this.tags = tags;
this.update = update;
this.warn = warn;
this.columns = Collections.unmodifiableList(new ArrayList<>(columns));
this.background = background;
this.stripe = stripe;
}
private InventorySettings()
{
this(
"https://mtgjson.com/api/v5/",
"AllSets.json",
"version.json",
new DatabaseVersion(0, 0, 0),
".",
"scans",
"tags.json",
UpdateFrequency.DAILY,
true,
List.of(NAME, MANA_COST, TYPE_LINE, EXPANSION),
Color.WHITE,
new Color(0xCC, 0xCC, 0xCC, 0xFF)
);
}
/**
* @return the full path name of the inventory file, i.e.
* [@{link #location}]/[{@link #file}].
*/
public String path()
{
return location + File.separator + file;
}
/**
* @return the full URL of the latest inventory file without .zip, i.e.
* [{@link #source}]/[{@link file}].
*/
public String url()
{
return source + file;
}
/**
* @return the full URL of the latest inventory version, i.e.
* [{@link #source}]/[{@link #versionFile}].
*/
public String versionSite()
{
return source + versionFile;
}
@Override
public boolean equals(Object other)
{
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof InventorySettings))
return false;
InventorySettings o = (InventorySettings)other;
return source.equals(o.source) &&
file.equals(o.file) &&
versionFile.equals(o.versionFile) &&
version.equals(o.version) &&
location.equals(o.location) &&
scans.equals(o.scans) &&
tags.equals(o.tags) &&
update == o.update &&
warn == o.warn &&
columns.equals(o.columns) &&
background.equals(o.background) &&
stripe.equals(o.stripe);
}
}
/**
* Sub-structure containing settings for the editor frames. It has some
* of its own sub-structures that are also immutable.
*
* @author Alec Roelke
*/
public static final class EditorSettings
{
/**
* Sub-structure containing information about recently-edited files.
*
* @author Alec Roelke
*/
public static final class RecentsSettings
{
/** Number of recent files to store. */
public final int count;
/** List of recently-edited files. */
public final List<String> files;
private RecentsSettings(int count, List<String> files)
{
this.count = count;
this.files = Collections.unmodifiableList(new ArrayList<>(files));
}
private RecentsSettings()
{
this(4, Collections.emptyList());
}
@Override
public boolean equals(Object other)
{
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof RecentsSettings))
return false;
RecentsSettings o = (RecentsSettings)other;
return count == o.count && files.equals(o.files);
}
@Override
public int hashCode()
{
return Objects.hash(count, files);
}
}
/**
* Sub-structure containing settings for category editing.
*
* @author Alec Roelke
*/
public static final class CategoriesSettings
{
/** Preset categories for quickly adding to decks. */
public final List<CategorySpec> presets;
/** Max number of rows to display cards in category tables. */
public final int rows;
/** Number of rows to show in white- or blacklists. */
public final int explicits;
private CategoriesSettings(List<CategorySpec> presets, int rows, int explicits)
{
this.presets = Collections.unmodifiableList(new ArrayList<>(presets));
this.rows = rows;
this.explicits = explicits;
}
private CategoriesSettings()
{
this(
Map.of(
"Artifacts", List.of("Artifact"),
"Creatures", List.of("Creature"),
"Lands", List.of("Land"),
"Instants/Sorceries", List.of("Instant", "Sorcery")
).entrySet().stream().map((e) -> {
CardTypeFilter filter = (CardTypeFilter)CardAttribute.createFilter(CardAttribute.CARD_TYPE);
filter.selected.addAll(e.getValue());
return new CategorySpec(e.getKey(), Collections.emptySet(), Collections.emptySet(), Color.WHITE, filter);
}).collect(Collectors.toList()),
6, 3
);
}
@Override
public boolean equals(Object other)
{
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof CategoriesSettings))
return false;
CategoriesSettings o = (CategoriesSettings)other;
return presets.equals(o.presets) && rows == o.rows && explicits == o.explicits;
}
@Override
public int hashCode()
{
return Objects.hash(presets, rows, explicits);
}
}
/**
* Sub-structure containing settings for displaying information about
* opening hands.
*
* @author Alec Roelke
*/
public static final class HandSettings
{
/** Initial size of opening hands before mulligans. */
public final int size;
/** How to round statistics (nearest, truncate, or don't). */
public final String rounding;
/** Background color for sample hand images. */
public final Color background;
private HandSettings(int size, String rounding, Color background)
{
this.size = size;
this.rounding = rounding;
this.background = background;
}
private HandSettings()
{
this(7, "No rounding", Color.WHITE);
}
@Override
public boolean equals(Object other)
{
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof HandSettings))
return false;
HandSettings o = (HandSettings)other;
return size == o.size && rounding.equals(o.rounding) && background.equals(o.background);
}
@Override
public int hashCode()
{
return Objects.hash(size, rounding, background);
}
}
public static final class LegalitySettings
{
public final boolean searchForCommander;
/** If searching for a commander, whether or not to search just the main deck. */
public final boolean main;
/** If searching for a commander, whether or not to check all lists. */
public final boolean all;
/** If searching for a commander, default name of the list to search that isn't the main deck. */
public final String list;
public final String sideboard;
private LegalitySettings(boolean searchForCommander, boolean main, boolean all, String list, String sideboard)
{
this.searchForCommander = searchForCommander;
this.main = main;
this.all = all;
this.list = list;
this.sideboard = sideboard;
}
private LegalitySettings()
{
this(true, true, false, "", "");
}
@Override
public boolean equals(Object other)
{
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof LegalitySettings))
return false;
LegalitySettings o = (LegalitySettings)other;
return searchForCommander == o.searchForCommander &&
main == o.main &&
all == o.all &&
list.equals(o.list) &&
sideboard.equals(o.sideboard);
}
@Override
public int hashCode()
{
return Objects.hash(searchForCommander, main, all, list, sideboard);
}
}
/** @see RecentsSettings */
public final RecentsSettings recents;
/** @see CategoriesSettings */
public final CategoriesSettings categories;
/** Card attributes to show in editor tables. */
public final List<CardAttribute> columns;
/** Stripe color of editor tables. */
public final Color stripe;
/** @see HandSettings */
public final HandSettings hand;
public final LegalitySettings legality;
private EditorSettings(int recentsCount, List<String> recentsFiles,
int explicits,
List<CategorySpec> presetCategories, int categoryRows,
List<CardAttribute> columns, Color stripe,
int handSize, String handRounding, Color handBackground,
boolean searchForCommander, boolean main, boolean all, String list, String sideboard)
{
this.recents = new RecentsSettings(recentsCount, recentsFiles);
this.categories = new CategoriesSettings(presetCategories, categoryRows, explicits);
this.columns = Collections.unmodifiableList(new ArrayList<>(columns));
this.stripe = stripe;
this.hand = new HandSettings(handSize, handRounding, handBackground);
this.legality = new LegalitySettings(searchForCommander, main, all, list, sideboard);
}
private EditorSettings()
{
recents = new RecentsSettings();
categories = new CategoriesSettings();
columns = List.of(NAME, MANA_COST, TYPE_LINE, EXPANSION, CATEGORIES, COUNT, DATE_ADDED);
stripe = new Color(0xCC, 0xCC, 0xCC, 0xFF);
hand = new HandSettings();
legality = new LegalitySettings();
}
@Override
public boolean equals(Object other)
{
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof EditorSettings))
return false;
EditorSettings o = (EditorSettings)other;
return recents.equals(o.recents) &&
categories.equals(o.categories) &&
columns.equals(o.columns) &&
stripe.equals(o.stripe) &&
hand.equals(o.hand) &&
legality.equals(o.legality);
}
@Override
public int hashCode()
{
return Objects.hash(recents, categories, columns, stripe, hand, legality);
}
}
/** @see InventorySettings */
public final InventorySettings inventory;
/** @see EditorSettings */
public final EditorSettings editor;
/** Initial directory of file choosers. */
public final String cwd;
protected Settings(String inventorySource, String inventoryFile, String inventoryVersionFile, DatabaseVersion inventoryVersion, String inventoryLocation, String inventoryScans, String inventoryTags, UpdateFrequency inventoryUpdate, boolean inventoryWarn, List<CardAttribute> inventoryColumns, Color inventoryBackground, Color inventoryStripe, int recentsCount, List<String> recentsFiles, int explicits, List<CategorySpec> presetCategories, int categoryRows, List<CardAttribute> editorColumns, Color editorStripe, int handSize, String handRounding, Color handBackground, boolean searchForCommander, boolean main, boolean all, String list, String sideboard, String cwd)
{
this.inventory = new InventorySettings(inventorySource, inventoryFile, inventoryVersionFile, inventoryVersion, inventoryLocation, inventoryScans, inventoryTags, inventoryUpdate, inventoryWarn, inventoryColumns, inventoryBackground, inventoryStripe);
this.editor = new EditorSettings(recentsCount, recentsFiles, explicits, presetCategories, categoryRows, editorColumns, editorStripe, handSize, handRounding, handBackground, searchForCommander, main, all, list, sideboard);
this.cwd = cwd;
}
protected Settings()
{
inventory = new InventorySettings();
editor = new EditorSettings();
cwd = ".";
}
@Override
public boolean equals(Object other)
{
if (other == null)
return false;
if (this == other)
return true;
if (!(other instanceof Settings))
return false;
Settings o = (Settings)other;
return inventory.equals(o.inventory) && editor.equals(o.editor) && cwd == o.cwd;
}
@Override
public int hashCode()
{
return Objects.hash(inventory, editor, cwd);
}
}
|
package edu.vu.isis.ammo;
/**
* Collection of all preference values used by Ammo.
* @author Demetri Miller
*
*/
public interface INetPrefKeys extends edu.vu.isis.ammo.IPrefKeys {
// Ammo Core
// keys for network configuration
public static final String CORE_IP_ADDR = "CORE_IP_ADDRESS";
public static final String CORE_IP_PORT = "CORE_IP_PORT";
public static final String CORE_SOCKET_TIMEOUT = "CORE_SOCKET_TIMEOUT";
public static final String PREF_TRANSMISSION_TIMEOUT = "CORE_TRANSMISSION_TIMEOUT";
public static final String CORE_IS_JOURNALED = "CORE_IS_JOURNALED";
public static final String CORE_DEVICE_ID = "CORE_DEVICE_ID";
public static final String CORE_OPERATOR_KEY = "CORE_OPERATOR_KEY";
public static final String CORE_OPERATOR_ID = "CORE_OPERATOR_ID";
// keys for managing network connections
public static final String NET_IS_ACTIVE = "IS_ACTIVE";
public static final String NET_SHOULD_USE = "SHOULD_USE";
public static final String NET_IS_AVAILABLE = "IS_AVAILABLE";
public static final String NET_IS_STALE = "IS_STALE";
public static final String WIRED_PREF = "AMMO_PHYSICAL_LINK_";
public static final String WIFI_PREF = "AMMO_WIFI_LINK_";
public static final String PHONE_PREF = "AMMO_PHONE_LINK_";
public static final String NET_CONN_PREF = "AMMO_NET_CONN_";
public static final String PHYSICAL_LINK_PREF_IS_ACTIVE = WIRED_PREF + NET_IS_ACTIVE;
public static final String WIRED_PREF_SHOULD_USE = WIRED_PREF + NET_SHOULD_USE;
public static final String PHYSICAL_LINK_PREF_IS_AVAILABLE = WIRED_PREF + NET_IS_AVAILABLE;
public static final String WIFI_PREF_IS_ACTIVE = WIFI_PREF + NET_IS_ACTIVE;
public static final String WIFI_PREF_SHOULD_USE = WIFI_PREF + NET_SHOULD_USE;
public static final String WIFI_PREF_IS_AVAILABLE = WIFI_PREF + NET_IS_AVAILABLE;
public static final String PHONE_PREF_IS_ACTIVE = PHONE_PREF + NET_IS_ACTIVE;
public static final String PHONE_PREF_SHOULD_USE = PHONE_PREF + NET_SHOULD_USE;
public static final String PHONE_PREF_IS_AVAILABLE = PHONE_PREF + NET_IS_AVAILABLE;
public static final String NET_CONN_PREF_IS_STALE = NET_CONN_PREF + NET_IS_STALE;
public static final String NET_CONN_PREF_SHOULD_USE = NET_CONN_PREF + NET_SHOULD_USE;
public static final String NET_CONN_PREF_IS_ACTIVE = NET_CONN_PREF + NET_IS_ACTIVE;
public static final String NET_CONN_FLAT_LINE_TIME = NET_CONN_PREF + "FLAT_LINE_TIME";
public static final String GATEWAY_SHOULD_USE = "GATEWAY_SHOULD_USE";
public static final String MULTICAST_SHOULD_USE = "MULTICAST_SHOULD_USE";
public static final String MULTICAST_IP_ADDRESS = "MULTICAST_IP_ADDRESS";
public static final String MULTICAST_PORT = "MULTICAST_PORT";
public static final String MULTICAST_NET_CONN_TIMEOUT = "MULTICAST_NET_CONN_TIMEOUT";
public static final String MULTICAST_CONN_IDLE_TIMEOUT = "MULTICAST_CONN_IDLE_TIMEOUT";
}
|
package com.ibm.streamsx.topology;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.ibm.streamsx.topology.builder.BInputPort;
import com.ibm.streamsx.topology.builder.BOperatorInvocation;
import com.ibm.streamsx.topology.builder.BOutput;
import com.ibm.streamsx.topology.function.BiFunction;
import com.ibm.streamsx.topology.function.Consumer;
import com.ibm.streamsx.topology.function.Function;
import com.ibm.streamsx.topology.function.ToIntFunction;
import com.ibm.streamsx.topology.function.Predicate;
import com.ibm.streamsx.topology.function.UnaryOperator;
import com.ibm.streamsx.topology.spl.SPLStream;
import com.ibm.streamsx.topology.tuple.Keyable;
/**
* A {@code TStream} is a declaration of a continuous sequence of tuples. A
* connected topology of streams and functional transformations is built using
* {@link Topology}. <BR>
* Generic methods on this interface provide the ability to
* {@link #filter(Predicate) filter}, {@link #transform(Function, Class)
* transform} or {@link #sink(Consumer) sink} this declared stream using a
* function. <BR>
* Utility methods in the {@code com.ibm.streams.topology.streams} package
* provide specific source streams, or transformations on streams with specific
* types.
*
* @param <T>
* Tuple type, any instance of {@code T} at runtime must be
* serializable.
*/
public interface TStream<T> extends TopologyElement {
/**
* Enumeration for routing tuples to parallel channels.
* @see TStream#parallel(int, Routing)
*/
public enum Routing {
/**
* Tuples will be routed to parallel channels such that an even
* distribution is maintained.
*/
ROUND_ROBIN,
/**
* Tuples will be consistently routed to the same channel based upon
* their value.
* <br>
* If the tuple implements the {@link Keyable} interface, then the tuple
* is routed to a parallel channel according to the
* {@code hashCode()} of the object returned by {@link Keyable#getKey()}.
* <BR>
* If the tuple does not
* implement the {@link Keyable} interface, then the tuple is routed to a parallel
* channel according to the {@code hashCode()} of the tuple object itself.
*/
PARTITIONED};
/**
* Declare a new stream that filters tuples from this stream. Each tuple
* {@code t} on this stream will appear in the returned stream if
* {@link Predicate#test(Object) filter.test(t)} returns {@code true}. If
* {@code filter.test(t)} returns {@code false} then then {@code t} will not
* appear in the returned stream.
* <P>
* Example of filtering out all empty strings from stream {@code s} of type
* {@code String}
*
* <pre>
* <code>
* TStream<String> s = ...
* TStream<String> filtered = s.filter(new Predicate<String>() {
* @Override
* public boolean test(String t) {
* return !t.isEmpty();
* }} );
* </code>
* </pre>
*
* </P>
*
* @param filter
* Filtering logic to be executed against each tuple.
* @return Filtered stream
*/
TStream<T> filter(Predicate<T> filter);
List<TStream<T>> split(int n, ToIntFunction<T> splitter);
/**
* Declare a new stream that transforms each tuple from this stream into one
* (or zero) tuple of a different type {@code U}. For each tuple {@code t}
* on this stream, the returned stream will contain a tuple that is the
* result of {@code transformer.apply(t)} when the return is not {@code null}.
* If {@code transformer.apply(t)} returns {@code null} then no tuple
* is submitted to the returned stream for {@code t}.
*
* <P>
* Example of transforming a stream containing numeric values as
* {@code String} objects into a stream of {@code Double} values.
*
* <pre>
* <code>
* TStream<String> strings = ...
* TStream<Double> doubles = strings.transform(new Function<String, Double>() {
* @Override
* public Double apply(String v) {
* return Double.valueOf(v);
* }}, Double.class );
* </code>
* </pre>
*
* </P>
*
* @param transformer
* Transformation logic to be executed against each tuple.
* @param tupleTypeClass
* Type {@code U} of the returned stream.
* @return Stream that will contain tuples of type {@code U} transformed from this
* stream's tuples.
*/
<U> TStream<U> transform(Function<T, U> transformer, Class<U> tupleTypeClass);
/**
* Declare a new stream that modifies each tuple from this stream into one
* (or zero) tuple of the same type {@code T}. For each tuple {@code t}
* on this stream, the returned stream will contain a tuple that is the
* result of {@code modifier.apply(t)} when the return is not {@code null}.
* The function may return the same reference as its input {@code t} or
* a different object of the same type.
* If {@code modifier.apply(t)} returns {@code null} then no tuple
* is submitted to the returned stream for {@code t}.
*
* <P>
* Example of modifying a stream {@code String} values by adding the suffix '{@code extra}'.
*
* <pre>
* <code>
* TStream<String> strings = ...
* TStream<String> modifiedStrings = strings.modify(new UnaryOperator<String>() {
* @Override
* public String apply(String v) {
* return v.concat("extra");
* }});
* </code>
* </pre>
*
* </P>
* <P>
* This method is equivalent to
* {@code transform(Function<T,T> modifier, T.class}).
* </P
*
* @param modifier
* Modifier logic to be executed against each tuple.
* @return Stream that will contain tuples of type {@code T} modified from this
* stream's tuples.
*/
TStream<T> modify(UnaryOperator<T> modifier);
/**
* Declare a new stream that transforms tuples from this stream into one or
* more (or zero) tuples of a different type {@code U}. For each tuple
* {@code t} on this stream, the returned stream will contain all tuples in
* the {@code Iterator<U>} that is the result of {@code transformer.apply(t)}.
* Tuples will be added to the returned stream in the order the iterator
* returns them.
*
* <BR>
* If the return is null or an empty iterator then no tuples are added to
* the returned stream for input tuple {@code t}.
* <P>
* Example of transforming a stream containing lines of text into a stream
* of words split out from each line. The order of the words in the stream
* will match the order of the words in the lines.
*
* <pre>
* <code>
* TStream<String> lines = ...
* TStream<String> words = lines.multiTransform(new Function<String, Iterable<String>>() {
* @Override
* public Iterable<String> apply(String t) {
* return Arrays.asList(t.split(" "));
* }}, String.class);
* </code>
* </pre>
*
* </P>
*
* @param transformer
* Transformation logic to be executed against each tuple.
* @param tupleTypeClass
* Type {@code U} of the returned stream.
* @return Stream that will contain tuples of type {@code U} transformed from this
* stream's tuples.
*/
<U> TStream<U> multiTransform(Function<T, Iterable<U>> transformer,
Class<U> tupleTypeClass);
/**
* Sink (terminate) this stream. For each tuple {@code t} on this stream
* {@link Consumer#accept(Object) sinker.accept(t)} will be called. This is
* typically used to send information to external systems, such as databases
* or dashboards.
* <P>
* Example of terminating a stream of {@code String} tuples by printing them
* to {@code System.out}.
*
* <pre>
* <code>
* TStream<String> values = ...
* values.sink(new Consumer<String>() {
*
* @Override
* public void accept(String v) {
* System.out.println(v);
*
* }
* });
* </code>
* </pre>
*
* </P>
*
* @param sinker
* Logic to be executed against each tuple on this stream.
*/
void sink(Consumer<T> sinker);
/**
* Create a stream that is a union of this stream and {@code other} stream
* of the same type {@code T}. Any tuple on this stream or {@code other}
* will appear on the returned stream. <BR>
* No ordering of tuples across this stream and {@code other} is defined,
* thus the return stream is unordered.
*
* @param other
* Stream to union with this stream.
* @return Stream that will contain tuples from this stream and
* {@code other}.
*/
TStream<T> union(TStream<T> other);
/**
* Create a stream that is a union of this stream and {@code others} streams
* of the same type {@code T}. Any tuple on this stream or any of
* {@code others} will appear on the returned stream. <BR>
* No ordering of tuples across this stream and {@code others} is defined,
* thus the return stream is unordered. <BR>
* If others does not contain any streams then {@code this} is returned.
*
* @param others
* Streams to union with this stream.
* @return Stream containing tuples from this stream and {@code others}.
*/
TStream<T> union(Set<TStream<T>> others);
/**
* Print each tuple on {@code System.out}. For each tuple {@code t} on this
* stream {@code System.out.println(t.toString())} will be called.
*/
void print();
Class<T> getTupleClass();
/**
* Join this stream with window of type {@code U}. For each tuple on this
* stream, it is joined with the contents of {@code other}. Each tuple is
* passed into {@code joiner} and the return value is submitted to the
* returned stream. If call returns null then no tuple is submitted.
*
* @param joiner
* @return A stream that is the results of joining this stream with
* {@code window}.
*/
<J, U> TStream<J> join(TWindow<U> window,
BiFunction<T, List<U>, J> joiner, Class<J> tupleClass);
/**
* Declare a {@link TWindow} that continually represents the last {@code time} seconds
* of tuples (in the given time {@code unit}) on this stream.
* If no tuples have been seen on the stream in the last {@code time} seconds
* then the window will be empty.
* <BR>
* When {@code T} implements {@link Keyable} then the window is partitioned
* using the value of {@link Keyable#getKey()}. In this case that means each
* partition independently maintains the last {@code time} seconds of tuples
* for that key.
*
* @param time Time size of the window
* @param unit Unit for {@code time}
* @return Window on this stream for the last {@code time} seconds.
*/
TWindow<T> last(long time, TimeUnit unit);
/**
* Declare a {@link TWindow} that continually represents the last {@code count} tuples
* seen on this stream. If the stream has not yet seen {@code count}
* tuples then it will contain all of the tuples seen on the stream,
* which will be less than {@code count}. If no tuples have been
* seen on the stream then the window will be empty.
* <BR>
* When {@code T} implements {@link Keyable} then the window is partitioned
* using the value of {@link Keyable#getKey()}. In this case that means each
* partition independently maintains the last {@code count} tuples for that
* key.
*
* @param count Tuple size of the window
* @return Window on this stream for the last {@code count} tuples.
*/
TWindow<T> last(int count);
/**
* Declare a {@link TWindow} that continually represents the last tuple on this stream.
* If no tuples have been seen on the stream then the window will be empty.
* <BR>
* When {@code T} implements {@link Keyable} then the window is partitioned
* using the value of {@link Keyable#getKey()}. In this case that means each
* partition independently maintains the last tuple for that key.
*
* @return Window on this stream for the last tuple.
*/
TWindow<T> last();
/**
* Declare a {@link TWindow} on this stream that has the same configuration
* as another window..
*
* When {@code T} implements {@link Keyable} then the window is partitioned
* using the value of {@link Keyable#getKey()}. In this case that means each
* partition independently maintains the list of tuples for that key.
*
* @param configWindow
* Window to copy the configuration from.
*/
TWindow<T> window(TWindow<?> configWindow);
/**
* Publish tuples from this stream to allow other applications to consume
* them using:
* <UL>
* <LI>
* {@link Topology#subscribe(String, Class)} for Java Streams applications.</LI>
* <LI>
* {@code com.ibm.streamsx.topology.topic::Subscribe} operator for SPL
* Streams applications.</LI>
* </UL>
* <BR>
* A subscriber matches to a publisher if:
* <UL>
* <LI>
* The topic is an exact match, and:</LI>
* <LI>
* For JSON streams ({@code TStream<JSONObject>}) the subscription is to
* a JSON stream.
* </LI
* <LI>
* For Java streams ({@code TStream<T>}) the declared Java type ({@code T}
* ) of the stream is an exact match.</LI>
* <LI>
* For {@link SPLStream SPL streams} the {@link SPLStream#getSchema() SPL
* schema} is an exact match.</LI>
* </UL>
*
* @see Topology#subscribe(String, Class)
* @see com.ibm.streamsx.topology.spl.SPLStreams#subscribe(TopologyElement, String, com.ibm.streams.operator.StreamSchema)
*/
void publish(String topic);
/**
* Parallelizes the stream into {@code width} parallel channels. If the
* tuple implements {@link Keyable}, the parallel channels are partitioned.
* Otherwise, the parallel channels are not partitioned, and tuples are routed
* in a round-robin fashion.
* <br><br>
* See the documentation for {@link #parallel(int, Routing)} for more
* information.
* @param width
* The degree of parallelism in the parallel region.
* @return A reference to a stream for which subsequent operations will be
* part of the parallel region.
*/
TStream<T> parallel(int width);
TStream<T> parallel(int width, Routing routing);
/**
* unparallel() merges the parallel channels of a parallelized stream.
* returns a Stream<T> for which subsequent operations will not be
* performed in parallel. Additionally, it merges any partitions which may
* have been present in the parallel channels. <br>
* <br>
* For additional documentation, see {@link TStream#parallel(int)}
*
* @return A Stream<T> for which subsequent operations are no longer
* parallelized.
*/
TStream<T> unparallel();
TStream<T> sample(double fraction);
TStream<T> isolate();
TStream<T> lowLatency();
TStream<T> endLowLatency();
/**
* Throttle a stream by ensuring any tuple is submitted with least
* {@code delay} from the previous tuple.
*
* @param delay
* Maximum amount to delay a tuple.
* @param unit
* Unit of {@code delay}.
* @return Stream containing all tuples on this stream. but throttled.
*/
TStream<T> throttle(long delay, TimeUnit unit);
/**
* Internal method.
* <BR>
* Not intended to be called by applications, may be removed at any time.
*/
BOutput output();
/**
* Internal method.
* Connect this stream to a downstream operator. If input is null then a new
* input port will be created, otherwise it will be used to connect to this
* stream. Returns input or the new port if input was null.
*
* <BR>
* Not intended to be called by applications, may be removed at any time.
*/
BInputPort connectTo(BOperatorInvocation receivingBop, boolean functional, BInputPort input);
}
|
package eu.amidst.scai2015;
import eu.amidst.core.datastream.*;
import eu.amidst.core.distribution.Multinomial;
import eu.amidst.core.distribution.Multinomial_MultinomialParents;
import eu.amidst.core.inference.InferenceEngineForBN;
import eu.amidst.core.inference.messagepassage.VMP;
import eu.amidst.core.io.DataStreamLoader;
import eu.amidst.core.models.BayesianNetwork;
import eu.amidst.core.models.DAG;
import eu.amidst.core.utils.Utils;
import eu.amidst.core.variables.StaticVariables;
import eu.amidst.core.variables.Variable;
import weka.classifiers.evaluation.NominalPrediction;
import weka.classifiers.evaluation.Prediction;
import weka.classifiers.evaluation.ThresholdCurve;
import weka.core.Instances;
import java.io.IOException;
import java.util.*;
public class wrapperBN {
int seed = 0;
Variable classVariable;
Variable classVariable_PM;
Attribute SEQUENCE_ID;
Attribute TIME_ID;
static int DEFAULTER_VALUE_INDEX = 1;
static int NON_DEFAULTER_VALUE_INDEX = 0;
static boolean usePRCArea = false; //By default ROCArea is used
public static boolean isUsePRCArea() {
return usePRCArea;
}
public static void setUsePRCArea(boolean usePRCArea) {
wrapperBN.usePRCArea = usePRCArea;
}
public Attribute getSEQUENCE_ID() {
return SEQUENCE_ID;
}
public void setSEQUENCE_ID(Attribute SEQUENCE_ID) {
this.SEQUENCE_ID = SEQUENCE_ID;
}
public Attribute getTIME_ID() {
return TIME_ID;
}
public void setTIME_ID(Attribute TIME_ID) {
this.TIME_ID = TIME_ID;
}
public Variable getClassVariable_PM() {
return classVariable_PM;
}
public void setClassVariable_PM(Variable classVariable_PM) {
this.classVariable_PM = classVariable_PM;
}
public int getSeed() {
return seed;
}
public void setSeed(int seed) {
this.seed = seed;
}
public Variable getClassVariable() {
return classVariable;
}
public void setClassVariable(Variable classVariable) {
this.classVariable = classVariable;
}
public BayesianNetwork wrapperBNOneMonth(DataOnMemory<DataInstance> data) throws IOException {
StaticVariables Vars = new StaticVariables(data.getAttributes());
int nbrVars = Vars.getNumberOfVars();
Variable classVar = Vars.getVariableById(-1);
//Split the whole data into training and testing
List<DataOnMemory<DataInstance>> splitData = this.splitTrainAndTest(data,66.0);
DataOnMemory<DataInstance> trainingData = splitData.get(0);
DataOnMemory<DataInstance> testData = splitData.get(1);
StaticVariables NonSelectedVars = Vars; // All the features variables minus the C and C'
int nbrNonSelected = nbrVars-2; //nbr of all features except the 2 classes C and C'?
StaticVariables SelectedVars = new StaticVariables();
Boolean stop = false;
DAG dag = new DAG(Vars);
BayesianNetwork bn = BayesianNetwork.newBayesianNetwork(dag);
//Learn the initial BN with training data including only the class variable
// bn = trainModel(trainingData,SelectedVars)
//Evaluate the initial BN with testing data including only the class variable, i.e., initial score or initial auc
double score = computeAccuracy (bn, testData, classVar); //add HashMap
//iterate until there is no improvement in score
while (nbrNonSelected > 0 && stop == false ) {
double[] scores = new double[nbrVars]; //save the score for each potential considered variable
for(Variable V:NonSelectedVars){
//learn a naive bayes including the class and the new selected set of variables including the variable V
//bn = trainModel(trainingData,NewSelectedVars)
//evaluate using the testing data
//auc = testModel(testData, bn, HashMap)
scores[V.getVarID()] = computeAccuracy (bn, testData, classVar);
//determine the max score and the index of the Variable
int maxScore = max(scores);
int index = maxIndex(scores);
if (score < maxScore){
score = maxScore;
//add the variable with index to the list of SelectedVars
//SelectedVars = SelectedVars + V
nbrNonSelected = nbrNonSelected -1;
}
else{
stop = true;
}
}
}
//Update HashMap considering the winning subset of the selected features and all the data (i.e., training +testing data)
//HashMap = updateHM (data, SelectedVars)
return bn;
}
public static double computeAccuracy(BayesianNetwork bn, DataOnMemory<DataInstance> data, Variable classVar){
double predictions = 0;
InferenceEngineForBN.setModel(bn);
for (DataInstance instance : data) {
double realValue = instance.getValue(classVar);
instance.setValue(classVar, Utils.missingValue());
InferenceEngineForBN.setEvidence(instance);
InferenceEngineForBN.runInference();
Multinomial posterior = InferenceEngineForBN.getPosterior(classVar);
if (Utils.maxIndex(posterior.getProbabilities())==realValue)
predictions++;
instance.setValue(classVar, realValue);
}
return predictions/data.getNumberOfDataInstances();
}
List<DataOnMemory<DataInstance>> splitTrainAndTest(DataOnMemory<DataInstance> data, double trainPercentage) {
Random random = new Random(this.seed);
DataOnMemoryListContainer<DataInstance> train = new DataOnMemoryListContainer(data.getAttributes());
DataOnMemoryListContainer<DataInstance> test = new DataOnMemoryListContainer(data.getAttributes());
for (DataInstance dataInstance : data) {
if (dataInstance.getValue(classVariable) == DEFAULTER_VALUE_INDEX)
continue;
if (random.nextDouble()<trainPercentage/100.0)
train.add(dataInstance);
else
test.add(dataInstance);
}
for (DataInstance dataInstance : data) {
if (dataInstance.getValue(classVariable) != DEFAULTER_VALUE_INDEX)
continue;
if (random.nextDouble()<trainPercentage/100.0)
train.add(dataInstance);
}
Collections.shuffle(train.getList(), random);
Collections.shuffle(test.getList(), random);
return Arrays.asList(train, test);
}
public double test(DataOnMemory<DataInstance> data, BayesianNetwork bn, HashMap<Integer, Multinomial> posteriors, boolean updatePosteriors){
VMP vmp = new VMP();
ArrayList<Prediction> predictions = new ArrayList<>();
for (DataInstance instance : data) {
int clientID = (int) instance.getValue(SEQUENCE_ID);
//Multinomial distClass_PM = bn.getConditionalDistribution(classVariable_PM);
//distClass_PM = posteriors.get(clientID);
((Multinomial)bn.getConditionalDistribution(classVariable_PM)).setProbabilities(posteriors.get(clientID).getProbabilities());
Multinomial_MultinomialParents distClass = bn.getConditionalDistribution(classVariable);
Multinomial deterministic = new Multinomial(classVariable);
deterministic.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0);
deterministic.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.0);
distClass.setMultinomial(DEFAULTER_VALUE_INDEX, deterministic);
vmp.setModel(bn);
instance.setValue(classVariable, Utils.missingValue());
instance.setValue(classVariable_PM, Utils.missingValue());
vmp.setEvidence(instance);
vmp.runInference();
Multinomial posterior = vmp.getPosterior(classVariable);
double realValue = instance.getValue(classVariable);
Prediction prediction = new NominalPrediction(realValue, posterior.getProbabilities());
predictions.add(prediction);
if(realValue == DEFAULTER_VALUE_INDEX) {
posterior.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0);
posterior.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0);
}
if(updatePosteriors)
posteriors.put(clientID, posterior);
}
ThresholdCurve thresholdCurve = new ThresholdCurve();
Instances tcurve = thresholdCurve.getCurve(predictions);
if(usePRCArea)
return ThresholdCurve.getPRCArea(tcurve);
else
return ThresholdCurve.getROCArea(tcurve);
}
public static void main(String[] args) throws IOException {
DataStream<DataInstance> data = DataStreamLoader.loadFromFile("datasets/randomdata.arff");
String arg;
for (int i = 0; i < args.length ; i++) {
arg = args[i];
if(args[i].equalsIgnoreCase("PRCArea"))
setUsePRCArea(true);
}
//BayesianNetwork bn = wrapperBN.wrapperBNOneMonth(data);
}
}
|
package com.hubspot.singularity.data;
import com.codahale.metrics.MetricRegistry;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.hubspot.singularity.config.SingularityConfiguration;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class InactiveAgentManager extends CuratorManager {
private static final String ROOT_PATH = "/inactiveSlaves";
private static final Logger LOG = LoggerFactory.getLogger(InactiveAgentManager.class);
@Inject
public InactiveAgentManager(
CuratorFramework curator,
SingularityConfiguration configuration,
MetricRegistry metricRegistry
) {
super(curator, configuration, metricRegistry);
}
public Set<String> getInactiveAgents() {
return new HashSet<>(getChildren(ROOT_PATH));
}
public void deactivateAgent(String host) {
create(pathOf(host));
}
public void activateAgent(String host) {
delete(pathOf(host));
}
public boolean isInactive(String host) {
return exists(pathOf(host));
}
private String pathOf(String host) {
return String.format("%s/%s", ROOT_PATH, host);
}
/**
* Delete single agent from inactive agent list.
* @param host agent hostname
*/
public void cleanInactiveAgent(String host) {
LOG.debug("Attempting to clean inactive host {}", host);
Optional<Stat> stat = checkExists(pathOf(host));
if (stat.isPresent()) {
delete(pathOf(host));
LOG.debug("Deleted inactive host {}", host);
}
}
public void cleanInactiveAgentsList(long thresholdTime) {
for (String host : getInactiveAgents()) {
LOG.debug("Attempting to clean inactive host {}", host);
Optional<Stat> stat = checkExists(pathOf(host));
if (stat.isPresent() && stat.get().getMtime() < thresholdTime) {
delete(pathOf(host));
LOG.debug("Deleted inactive host {}", host);
}
}
}
}
|
package crazypants.enderio.machine.farm;
import java.util.BitSet;
import net.minecraft.block.Block;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemShears;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.EnumSkyBlock;
import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint;
import crazypants.enderio.EnderIO;
import crazypants.enderio.ModObject;
import crazypants.enderio.config.Config;
import crazypants.enderio.machine.AbstractPoweredTaskEntity;
import crazypants.enderio.machine.ContinuousTask;
import crazypants.enderio.machine.IMachineRecipe.ResultStack;
import crazypants.enderio.machine.IPoweredTask;
import crazypants.enderio.machine.SlotDefinition;
import crazypants.enderio.machine.farm.farmers.FarmersCommune;
import crazypants.enderio.machine.farm.farmers.IHarvestResult;
import crazypants.enderio.machine.farm.farmers.RubberTreeFarmerIC2;
import crazypants.enderio.network.PacketHandler;
import crazypants.enderio.power.BasicCapacitor;
import crazypants.enderio.power.Capacitors;
import crazypants.enderio.power.ICapacitor;
import crazypants.enderio.tool.ArrayMappingTool;
import crazypants.util.BlockCoord;
import crazypants.util.Lang;
public class TileFarmStation extends AbstractPoweredTaskEntity {
private static final int TICKS_PER_WORK = 20;
public enum ToolType {
HOE {
@Override
boolean match(ItemStack item) {
for (ItemStack stack : Config.farmHoes) {
if (stack.getItem() == item.getItem()) {
return true;
}
}
return false;
}
},
AXE {
@Override
boolean match(ItemStack item) {
return item.getItem().getHarvestLevel(item, "axe") >= 0;
}
},
TREETAP {
@Override
boolean match(ItemStack item) {
return item.getItem().getClass() == RubberTreeFarmerIC2.treeTap;
}
},
SHEARS {
@Override
boolean match(ItemStack item) {
return item.getItem() instanceof ItemShears;
}
},
NONE {
@Override
boolean match(ItemStack item) {
return false;
}
};
public final boolean itemMatches(ItemStack item) {
if (item == null) {
return false;
}
return match(item) && !isBrokenTinkerTool(item);
}
private boolean isBrokenTinkerTool(ItemStack item)
{
return item.hasTagCompound() && item.getTagCompound().hasKey("InfiTool") && item.getTagCompound().getCompoundTag("InfiTool").getBoolean("Broken");
}
abstract boolean match(ItemStack item);
public static boolean isTool(ItemStack stack) {
for (ToolType type : values()) {
if (type.itemMatches(stack)) {
return true;
}
}
return false;
}
public static ToolType getToolType(ItemStack stack) {
for (ToolType type : values()) {
if (type.itemMatches(stack)) {
return type;
}
}
return NONE;
}
}
public static final String NOTIFICATION_NO_HOE = "noHoe";
public static final String NOTIFICATION_NO_AXE = "noAxe";
public static final String NOTIFICATION_NO_SEEDS = "noSeeds";
private BlockCoord lastScanned;
private EntityPlayerMP farmerJoe;
public static final int NUM_TOOL_SLOTS = 3;
private static final int minToolSlot = 0;
private static final int maxToolSlot = -1 + NUM_TOOL_SLOTS;
public static final int NUM_FERTILIZER_SLOTS = 2;
public static final int minFirtSlot = maxToolSlot + 1;
public static final int maxFirtSlot = maxToolSlot + NUM_FERTILIZER_SLOTS;
public static final int NUM_SUPPLY_SLOTS = 4;
public static final int minSupSlot = maxFirtSlot + 1;
public static final int maxSupSlot = maxFirtSlot + NUM_SUPPLY_SLOTS;
private final BitSet lockedSlots = new BitSet();
private final int upgradeBonusSize = 2;
public String notification = "";
public boolean sendNotification = false;
private boolean wasActive;
public TileFarmStation() {
super(new SlotDefinition(9, 6, 1));
}
public int getFarmSize() {
return Config.farmDefaultSize + getUpgradeDist();
}
public void actionPerformed(boolean isAxe) {
if(isAxe) {
usePower(Config.farmAxeActionEnergyUseRF);
} else {
usePower(Config.farmActionEnergyUseRF);
}
clearNotification();
}
public boolean tillBlock(BlockCoord plantingLocation) {
BlockCoord dirtLoc = plantingLocation.getLocation(ForgeDirection.DOWN);
Block dirtBlock = getBlock(dirtLoc);
if((dirtBlock == Blocks.dirt || dirtBlock == Blocks.grass)) {
if(!hasHoe()) {
setNotification(NOTIFICATION_NO_HOE);
return false;
}
damageHoe(1, dirtLoc);
worldObj.setBlock(dirtLoc.x, dirtLoc.y, dirtLoc.z, Blocks.farmland);
worldObj.playSoundEffect(dirtLoc.x + 0.5F, dirtLoc.y + 0.5F, dirtLoc.z + 0.5F, Blocks.farmland.stepSound.getStepResourcePath(),
(Blocks.farmland.stepSound.getVolume() + 1.0F) / 2.0F, Blocks.farmland.stepSound.getPitch() * 0.8F);
actionPerformed(false);
return true;
} else if(dirtBlock == Blocks.farmland) {
return true;
}
return false;
}
public int getMaxLootingValue() {
int result = 0;
for (int i = minToolSlot; i <= maxToolSlot; i++) {
if(inventory[i] != null) {
int level = getLooting(inventory[i]);
if(level > result) {
result = level;
}
}
}
return result;
}
private int getUpgradeDist() {
int upg = slotDefinition.getMaxUpgradeSlot();
if(inventory[upg] == null) {
return 0;
} else {
return upgradeBonusSize * inventory[upg].getItemDamage();
}
}
public boolean hasHoe() {
return hasTool(ToolType.HOE);
}
public boolean hasAxe() {
return hasTool(ToolType.AXE);
}
public boolean hasShears() {
return hasTool(ToolType.SHEARS);
}
public int getAxeLootingValue() {
ItemStack tool = getTool(ToolType.AXE);
if(tool == null) {
return 0;
}
return getLooting(tool);
}
public void damageAxe(Block blk, BlockCoord bc) {
damageTool(ToolType.AXE, blk, bc, 1);
}
public void damageHoe(int i, BlockCoord bc) {
damageTool(ToolType.HOE, null, bc, i);
}
public void damageShears(Block blk, BlockCoord bc) {
damageTool(ToolType.SHEARS, blk, bc, 1);
}
public boolean hasTool(ToolType type){
return getTool(type) != null;
}
private ItemStack getTool(ToolType type) {
for (int i = minToolSlot; i <= maxToolSlot; i++) {
if(type.itemMatches(inventory[i]) && inventory[i].stackSize>0) {
return inventory[i];
}
}
return null;
}
public void damageTool(ToolType type, Block blk, BlockCoord bc, int damage) {
ItemStack tool = getTool(type);
if(tool == null) {
return;
}
float rand = worldObj.rand.nextFloat();
if(rand >= Config.farmToolTakeDamageChance) {
return;
}
boolean canDamage = canDamage(tool);
if(type == ToolType.AXE) {
tool.getItem().onBlockDestroyed(tool, worldObj, blk, bc.x, bc.y, bc.z, farmerJoe);
} else if(type == ToolType.HOE) {
int origDamage = tool.getItemDamage();
tool.getItem().onItemUse(tool, farmerJoe, worldObj, bc.x, bc.y, bc.z, 1, 0.5f, 0.5f, 0.5f);
if(origDamage == tool.getItemDamage() && canDamage) {
tool.damageItem(1, farmerJoe);
}
} else if(canDamage) {
tool.damageItem(1, farmerJoe);
}
if(tool.stackSize == 0 || (canDamage && tool.getItemDamage() >= tool.getMaxDamage())) {
destroyTool(type);
}
}
private boolean canDamage(ItemStack stack) {
return stack != null && stack.isItemStackDamageable() && stack.getItem().isDamageable();
}
private void destroyTool(ToolType type) {
for (int i = minToolSlot; i <= maxToolSlot; i++) {
if(type.itemMatches(inventory[i]) && inventory[i].stackSize==0) {
inventory[i] = null;
markDirty();
return;
}
}
}
private int getLooting(ItemStack stack) {
return Math.max(
EnchantmentHelper.getEnchantmentLevel(Enchantment.looting.effectId, stack),
EnchantmentHelper.getEnchantmentLevel(Enchantment.fortune.effectId, stack));
}
public EntityPlayerMP getFakePlayer() {
return farmerJoe;
}
public Block getBlock(BlockCoord bc) {
return worldObj.getBlock(bc.x, bc.y, bc.z);
}
public Block getBlock(int x, int y, int z) {
return worldObj.getBlock(x, y, z);
}
public int getBlockMeta(BlockCoord bc) {
return worldObj.getBlockMetadata(bc.x, bc.y, bc.z);
}
public boolean isOpen(BlockCoord bc) {
Block block = worldObj.getBlock(bc.x, bc.y, bc.z);
return block.isAir(worldObj, bc.x, bc.y, bc.z) || block.isReplaceable(worldObj, bc.x, bc.y, bc.z);
}
public void setNotification(String unloc) {
String newNote = Lang.localize("farm.note." + unloc);
if(!newNote.equals(notification)) {
notification = newNote;
sendNotification = true;
}
}
public void clearNotification() {
if(hasNotification()) {
notification = "";
sendNotification = true;
}
}
public boolean hasNotification() {
return !"".equals(notification);
}
private void sendNotification() {
PacketHandler.INSTANCE.sendToAll(new PacketUpdateNotification(this, notification));
}
@Override
protected boolean isMachineItemValidForSlot(int i, ItemStack stack) {
if(stack == null) {
return false;
}
if(i <= maxToolSlot) {
if (ToolType.isTool(stack)) {
for (int j = minToolSlot; j <= maxToolSlot; j++) {
if (ToolType.getToolType(stack).itemMatches(inventory[j])) {
return false;
}
}
return true;
}
return false;
} else if (i <= maxFirtSlot) {
return stack.getItem() == Items.dye && stack.getItemDamage() == 15;
} else if (i <= maxSupSlot) {
return (inventory[i] != null || !isSlotLocked(i)) && FarmersCommune.instance.canPlant(stack);
} else {
return false;
}
}
@Override
public void updateEntity() {
super.updateEntity();
if(isActive() != wasActive) {
wasActive = isActive();
worldObj.updateLightByType(EnumSkyBlock.Block, xCoord, yCoord, zCoord);
}
}
@Override
protected boolean checkProgress(boolean redstoneChecksPassed) {
if(redstoneChecksPassed) {
usePower();
if(canTick(redstoneChecksPassed)) {
doTick();
}
}
return false;
}
protected boolean canTick(boolean redstoneChecksPassed) {
if(!shouldDoWorkThisTick(2)) {
return false;
}
if(getEnergyStored() < getPowerUsePerTick()) {
setNotification("noPower");
return false;
}
int curScaled = getProgressScaled(16);
if(curScaled != lastProgressScaled) {
sendTaskProgressPacket();
lastProgressScaled = curScaled;
}
return true;
}
protected void doTick() {
if (sendNotification && shouldDoWorkThisTick(TICKS_PER_WORK)) {
sendNotification = false;
sendNotification();
}
if(!hasPower() && Config.farmActionEnergyUseRF > 0 && Config.farmAxeActionEnergyUseRF > 0) {
setNotification("noPower");
return;
}
if("noPower".equals(notification)) {
clearNotification();
}
BlockCoord bc = getNextCoord();
if(bc != null && bc.equals(getLocation())) { //don't try and harvest ourselves
bc = getNextCoord();
}
if(bc == null) {
return;
}
lastScanned = bc;
Block block = worldObj.getBlock(bc.x, bc.y, bc.z);
if(block == null) {
return;
}
int meta = worldObj.getBlockMetadata(bc.x, bc.y, bc.z);
if(farmerJoe == null) {
farmerJoe = new FakeFarmPlayer(MinecraftServer.getServer().worldServerForDimension(worldObj.provider.dimensionId));
}
if(isOpen(bc)) {
FarmersCommune.instance.prepareBlock(this, bc, block, meta);
block = worldObj.getBlock(bc.x, bc.y, bc.z);
}
if(isOutputFull()) {
setNotification("outputFull");
return;
}
if(!hasPower() && Config.farmActionEnergyUseRF > 0 && Config.farmAxeActionEnergyUseRF > 0) {
setNotification("noPower");
return;
}
if(!isOpen(bc)) {
IHarvestResult harvest = FarmersCommune.instance.harvestBlock(this, bc, block, meta);
if(harvest != null && harvest.getDrops() != null) {
PacketFarmAction pkt = new PacketFarmAction(harvest.getHarvestedBlocks());
PacketHandler.INSTANCE.sendToAllAround(pkt, new TargetPoint(worldObj.provider.dimensionId, bc.x, bc.y, bc.z, 64));
for (EntityItem ei : harvest.getDrops()) {
if(ei != null) {
insertHarvestDrop(ei, bc);
if(!ei.isDead) {
worldObj.spawnEntityInWorld(ei);
}
}
}
} else if (!isOpen(bc) && hasBonemeal() && bonemealCooldown
// there's a block and it did not produce harvest. Try bonemealing it
if (inventory[minFirtSlot].getItem().onItemUse(inventory[minFirtSlot], farmerJoe, worldObj, bc.x, bc.y, bc.z, 1, 0.5f, 0.5f, 0.5f)) {
PacketHandler.INSTANCE.sendToAllAround(new PacketFarmAction(bc), new TargetPoint(worldObj.provider.dimensionId, bc.x, bc.y, bc.z, 64));
if (inventory[minFirtSlot].stackSize == 0) {
inventory[minFirtSlot] = null;
}
bonemealCooldown = 5;
usePower(Config.farmBonemealActionEnergyUseRF);
} else {
usePower(Config.farmBonemealTryEnergyUseRF);
}
}
}
}
private int bonemealCooldown = 5; // no need to persist this
private boolean hasBonemeal() {
if (inventory[minFirtSlot] != null) {
return true;
}
for (int i = minFirtSlot + 1; i <= maxFirtSlot; i++) {
if (inventory[i] != null) {
inventory[minFirtSlot] = inventory[i];
inventory[i] = null;
return true;
}
}
return false;
}
private boolean isOutputFull() {
for (int i = slotDefinition.minOutputSlot; i <= slotDefinition.maxOutputSlot; i++) {
ItemStack curStack = inventory[i];
if(curStack == null || curStack.stackSize < curStack.getMaxStackSize()) {
return false;
}
}
return true;
}
public boolean hasSeed(ItemStack seeds, BlockCoord bc) {
int slot = getSupplySlotForCoord(bc);
ItemStack inv = inventory[slot];
return inv != null && (inv.stackSize > 1 || !isSlotLocked(slot)) && inv.isItemEqual(seeds);
}
/*
* Returns a fuzzy boolean:
*
* <=0 - break no leaves for saplings
* 50 - break half the leaves for saplings
* 90 - break 90% of the leaves for saplings
*/
public int isLowOnSaplings(BlockCoord bc) {
int slot = getSupplySlotForCoord(bc);
ItemStack inv = inventory[slot];
return 90 * (Config.farmSaplingReserveAmount - (inv == null ? 0 : inv.stackSize)) / Config.farmSaplingReserveAmount;
}
public ItemStack takeSeedFromSupplies(ItemStack stack, BlockCoord forBlock) {
return takeSeedFromSupplies(stack, forBlock, true);
}
public ItemStack takeSeedFromSupplies(ItemStack stack, BlockCoord forBlock, boolean matchMetadata) {
if(stack == null || forBlock == null) {
return null;
}
int slot = getSupplySlotForCoord(forBlock);
ItemStack inv = inventory[slot];
if(inv != null) {
if(matchMetadata ? inv.isItemEqual(stack) : inv.getItem() == stack.getItem()) {
if (inv.stackSize <= 1 && isSlotLocked(slot)) {
return null;
}
ItemStack result = inv.copy();
result.stackSize = 1;
inv = inv.copy();
inv.stackSize
if(inv.stackSize == 0) {
inv = null;
}
setInventorySlotContents(slot, inv);
return result;
}
}
return null;
}
public ItemStack takeSeedFromSupplies(BlockCoord bc) {
return takeSeedFromSupplies(getSeedTypeInSuppliesFor(bc), bc);
}
public ItemStack getSeedTypeInSuppliesFor(BlockCoord bc) {
int slot = getSupplySlotForCoord(bc);
ItemStack inv = inventory[slot];
if(inv != null && (inv.stackSize > 1 || !isSlotLocked(slot))) {
return inv.copy();
}
return null;
}
protected int getSupplySlotForCoord(BlockCoord forBlock) {
if(forBlock.x <= xCoord && forBlock.z > zCoord) {
return minSupSlot;
} else if(forBlock.x > xCoord && forBlock.z > zCoord - 1) {
return minSupSlot + 1;
} else if(forBlock.x < xCoord && forBlock.z <= zCoord) {
return minSupSlot + 2;
}
return minSupSlot + 3;
}
private void insertHarvestDrop(Entity entity, BlockCoord bc) {
if(!worldObj.isRemote) {
if(entity instanceof EntityItem && !entity.isDead) {
EntityItem item = (EntityItem) entity;
ItemStack stack = item.getEntityItem().copy();
int numInserted = insertResult(stack, bc);
stack.stackSize -= numInserted;
item.setEntityItemStack(stack);
if(stack.stackSize == 0) {
item.setDead();
}
}
}
}
private int insertResult(ItemStack stack, BlockCoord bc) {
int slot = bc != null ? getSupplySlotForCoord(bc) : minSupSlot;
int[] slots = new int[NUM_SUPPLY_SLOTS];
int k = 0;
for (int j = slot; j <= maxSupSlot; j++) {
slots[k++] = j;
}
for (int j = minSupSlot; j < slot; j++) {
slots[k++] = j;
}
int origSize = stack.stackSize;
stack = stack.copy();
int inserted = 0;
for (int j = 0; j < slots.length && inserted < stack.stackSize; j++) {
int i = slots[j];
ItemStack curStack = inventory[i];
if(isItemValidForSlot(i, stack) && (curStack == null || curStack.stackSize < 16)) {
if(curStack == null) {
inventory[i] = stack.copy();
inserted = stack.stackSize;
} else if(curStack.isItemEqual(stack)) {
inserted = Math.min(16 - curStack.stackSize, stack.stackSize);
inventory[i].stackSize += inserted;
}
}
}
stack.stackSize -= inserted;
if(inserted >= origSize) {
return origSize;
}
ResultStack[] in = new ResultStack[] { new ResultStack(stack) };
mergeResults(in);
return origSize - (in[0].item == null ? 0 : in[0].item.stackSize);
}
private BlockCoord getNextCoord() {
int size = getFarmSize();
BlockCoord loc = getLocation();
if(lastScanned == null) {
lastScanned = new BlockCoord(loc.x - size, loc.y, loc.z - size);
return lastScanned;
}
int nextX = lastScanned.x + 1;
int nextZ = lastScanned.z;
if(nextX > loc.x + size) {
nextX = loc.x - size;
nextZ += 1;
if(nextZ > loc.z + size) {
lastScanned = null;
return getNextCoord();
}
}
return new BlockCoord(nextX, lastScanned.y, nextZ);
}
public void toggleLockedState(int slot) {
if (worldObj.isRemote) {
PacketHandler.INSTANCE.sendToServer(new PacketFarmLockedSlot(this, slot));
}
lockedSlots.flip(slot);
}
public boolean isSlotLocked(int slot) {
return lockedSlots.get(slot);
}
@Override
public String getInventoryName() {
return EnderIO.blockFarmStation.getLocalizedName();
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
@Override
public String getMachineName() {
return ModObject.blockFarmStation.unlocalisedName;
}
@Override
public float getProgress() {
return 0.5f;
}
@Override
public void onCapacitorTypeChange() {
int ppt = calcPowerUsePerTick();
switch (getCapacitorType()) {
case BASIC_CAPACITOR:
setCapacitor(new BasicCapacitor(ppt * 40, 250000, ppt));
break;
case ACTIVATED_CAPACITOR:
setCapacitor(new BasicCapacitor(ppt * 40, 500000, ppt));
break;
case ENDER_CAPACITOR:
setCapacitor(new BasicCapacitor(ppt * 40, 1000000, ppt));
break;
}
currentTask = createTask();
}
private int calcPowerUsePerTick() {
return Math.round(Config.farmContinuousEnergyUseRF * (getFarmSize()/(float)Config.farmDefaultSize ));
}
@Override
public void readCustomNBT(NBTTagCompound nbtRoot) {
super.readCustomNBT(nbtRoot);
currentTask = createTask();
}
@Override
public void readCommon(NBTTagCompound nbtRoot) {
super.readCommon(nbtRoot);
lockedSlots.clear();
for (int i : nbtRoot.getIntArray("lockedSlots")) {
lockedSlots.set(i);
}
int slotLayoutVersion = nbtRoot.getInteger("slotLayoutVersion");
if (slotLayoutVersion == 0) {
inventory = (new ArrayMappingTool<ItemStack>("TTSSSSOOOOC", "TTTBBSSSSOOOOOOC")).map(inventory);
} else if (slotLayoutVersion == 1) {
inventory = (new ArrayMappingTool<ItemStack>("TTTSSSSOOOOC", "TTTBBSSSSOOOOOOC")).map(inventory);
} else if (slotLayoutVersion == 2) {
inventory = (new ArrayMappingTool<ItemStack>("TTTSSSSOOOOOOC", "TTTBBSSSSOOOOOOC")).map(inventory);
}
}
IPoweredTask createTask() {
return new ContinuousTask(getPowerUsePerTick());
}
@Override
public void writeCustomNBT(NBTTagCompound nbtRoot) {
super.writeCustomNBT(nbtRoot);
nbtRoot.setBoolean("isActive", isActive());
}
@Override
public void writeCommon(NBTTagCompound nbtRoot) {
super.writeCommon(nbtRoot);
if(!lockedSlots.isEmpty()) {
int[] locked = new int[lockedSlots.cardinality()];
for (int i=0,bit=-1; (bit=lockedSlots.nextSetBit(bit+1)) >= 0; i++) {
locked[i] = bit;
}
nbtRoot.setIntArray("lockedSlots", locked);
}
nbtRoot.setInteger("slotLayoutVersion", 3);
}
}
|
package org.ovirt.engine.ui.webadmin.section.main.view.tab;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.network.NetworkView;
import org.ovirt.engine.core.common.queries.ConfigurationValues;
import org.ovirt.engine.core.searchbackend.NetworkConditionFieldAutoCompleter;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.uicommon.model.MainModelProvider;
import org.ovirt.engine.ui.common.widget.table.column.LinkColumnWithTooltip;
import org.ovirt.engine.ui.common.widget.table.column.SafeHtmlWithSafeHtmlTooltipColumn;
import org.ovirt.engine.ui.common.widget.table.column.TextColumnWithTooltip;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkListModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.ApplicationResources;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.MainTabNetworkPresenter;
import org.ovirt.engine.ui.webadmin.section.main.view.AbstractMainTabWithDetailsTableView;
import org.ovirt.engine.ui.webadmin.widget.action.WebAdminButtonDefinition;
import org.ovirt.engine.ui.webadmin.widget.table.column.CommentColumn;
import org.ovirt.engine.ui.webadmin.widget.table.column.NetworkRoleColumnHelper;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.inject.Inject;
public class MainTabNetworkView extends AbstractMainTabWithDetailsTableView<NetworkView, NetworkListModel> implements MainTabNetworkPresenter.ViewDef {
interface ViewIdHandler extends ElementIdHandler<MainTabNetworkView> {
ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
}
private final String ENGINE_NETWORK_NAME =
(String) AsyncDataProvider.getInstance().getConfigValuePreConverted(ConfigurationValues.ManagementNetwork);
private final ApplicationConstants constants;
private final SafeHtml mgmtImage;
private final SafeHtml vmImage;
private final SafeHtml emptyImage;
private LinkColumnWithTooltip<NetworkView> providerColumn;
@Inject
public MainTabNetworkView(MainModelProvider<NetworkView, NetworkListModel> modelProvider,
ApplicationConstants constants,
ApplicationResources resources) {
super(modelProvider);
this.constants = constants;
ViewIdHandler.idHandler.generateAndSetIds(this);
mgmtImage = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.mgmtNetwork()).getHTML());
vmImage = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.networkVm()).getHTML());
emptyImage = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.networkEmpty()).getHTML());
initTable();
initWidget(getTable());
}
void initTable() {
getTable().enableColumnResizing();
TextColumnWithTooltip<NetworkView> nameColumn = new TextColumnWithTooltip<NetworkView>() {
@Override
public String getValue(NetworkView object) {
return object.getName();
}
};
nameColumn.makeSortable(NetworkConditionFieldAutoCompleter.NAME);
getTable().addColumn(nameColumn, constants.nameNetwork(), "200px"); //$NON-NLS-1$
CommentColumn<NetworkView> commentColumn = new CommentColumn<NetworkView>();
getTable().addColumnWithHtmlHeader(commentColumn, commentColumn.getHeaderHtml(), "30px"); //$NON-NLS-1$
TextColumnWithTooltip<NetworkView> dcColumn = new TextColumnWithTooltip<NetworkView>() {
@Override
public String getValue(NetworkView object) {
return object.getDataCenterName();
}
};
dcColumn.makeSortable(NetworkConditionFieldAutoCompleter.DATA_CENTER);
getTable().addColumn(dcColumn, constants.dcNetwork(), "200px"); //$NON-NLS-1$
TextColumnWithTooltip<NetworkView> descriptionColumn = new TextColumnWithTooltip<NetworkView>() {
@Override
public String getValue(NetworkView object) {
return object.getDescription();
}
};
descriptionColumn.makeSortable(NetworkConditionFieldAutoCompleter.DESCRIPTION);
getTable().addColumn(descriptionColumn, constants.descriptionNetwork(), "300px"); //$NON-NLS-1$
SafeHtmlWithSafeHtmlTooltipColumn<NetworkView> roleColumn =
new SafeHtmlWithSafeHtmlTooltipColumn<NetworkView>() {
@Override
public SafeHtml getValue(NetworkView networkView) {
List<SafeHtml> images = new LinkedList<SafeHtml>();
if (ENGINE_NETWORK_NAME.equals(networkView.getName())) {
images.add(mgmtImage);
} else {
images.add(emptyImage);
}
if (networkView.isVmNetwork()) {
images.add(vmImage);
} else {
images.add(emptyImage);
}
return NetworkRoleColumnHelper.getValue(images);
}
@Override
public SafeHtml getTooltip(NetworkView networkView) {
Map<SafeHtml, String> imagesToText = new LinkedHashMap<SafeHtml, String>();
if (ENGINE_NETWORK_NAME.equals(networkView.getName())) {
imagesToText.put(mgmtImage, constants.managementItemInfo());
}
if (networkView.isVmNetwork()) {
imagesToText.put(vmImage, constants.vmItemInfo());
}
return NetworkRoleColumnHelper.getTooltip(imagesToText);
}
};
getTable().addColumn(roleColumn, constants.roleNetwork(), "60px"); //$NON-NLS-1$
TextColumnWithTooltip<NetworkView> vlanColumn = new TextColumnWithTooltip<NetworkView>() {
@Override
public String getValue(NetworkView object) {
return object.getVlanId() == null ? "-" : object.getVlanId().toString(); //$NON-NLS-1$
}
};
vlanColumn.makeSortable(NetworkConditionFieldAutoCompleter.VLAN_ID);
getTable().addColumn(vlanColumn, constants.vlanNetwork(), "60px"); //$NON-NLS-1$
TextColumnWithTooltip<NetworkView> labelColumn = new TextColumnWithTooltip<NetworkView>() {
@Override
public String getValue(NetworkView object) {
return object.getLabel() == null ? "-" : object.getLabel(); //$NON-NLS-1$
}
};
labelColumn.makeSortable(NetworkConditionFieldAutoCompleter.LABEL);
getTable().addColumn(labelColumn, constants.networkLabelNetworksTab(), "200px"); //$NON-NLS-1$
providerColumn = new LinkColumnWithTooltip<NetworkView>() {
@Override
public String getValue(NetworkView object) {
return object.getProvidedBy() == null ? "" : object.getProviderName(); //$NON-NLS-1$
}
};
getTable().addColumn(providerColumn, constants.providerNetwork(), "200px"); //$NON-NLS-1$
getTable().addActionButton(new WebAdminButtonDefinition<NetworkView>(constants.newNetwork()) {
@Override
protected UICommand resolveCommand() {
return getMainModel().getNewCommand();
}
});
getTable().addActionButton(new WebAdminButtonDefinition<NetworkView>(constants.importNetwork()) {
@Override
protected UICommand resolveCommand() {
return getMainModel().getImportCommand();
}
});
getTable().addActionButton(new WebAdminButtonDefinition<NetworkView>(constants.editNetwork()) {
@Override
protected UICommand resolveCommand() {
return getMainModel().getEditCommand();
}
});
getTable().addActionButton(new WebAdminButtonDefinition<NetworkView>(constants.removeNetwork()) {
@Override
protected UICommand resolveCommand() {
return getMainModel().getRemoveCommand();
}
});
}
@Override
public void setProviderClickHandler(final FieldUpdater<NetworkView, String> fieldUpdater) {
providerColumn.setFieldUpdater(new FieldUpdater<NetworkView, String>() {
@Override
public void update(int index, NetworkView object, String value) {
getTable().getSelectionModel().clear(); // this to avoid problems with a null active details model
fieldUpdater.update(index, object, value);
}
});
}
}
|
package eu.fbk.dkm.utils;
import ch.qos.logback.classic.Level;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import eu.fbk.rdfpro.util.Statements;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public final class CommandLine {
private final List<String> args;
private final List<String> options;
private final Map<String, List<String>> optionValues;
private CommandLine(final List<String> args, final Map<String, List<String>> optionValues) {
final List<String> options = Lists.newArrayList();
for (final String letterOrName : optionValues.keySet()) {
if (letterOrName.length() > 1) {
options.add(letterOrName);
}
}
this.args = args;
this.options = Ordering.natural().immutableSortedCopy(options);
this.optionValues = optionValues;
}
public <T> List<T> getArgs(final Class<T> type) {
return convert(this.args, type);
}
public <T> T getArg(final int index, final Class<T> type) {
return convert(this.args.get(index), type);
}
public <T> T getArg(final int index, final Class<T> type, final T defaultValue) {
try {
return convert(this.args.get(index), type);
} catch (final Throwable ex) {
return defaultValue;
}
}
public int getArgCount() {
return this.args.size();
}
public List<String> getOptions() {
return this.options;
}
public boolean hasOption(final String letterOrName) {
return this.optionValues.containsKey(letterOrName);
}
public <T> List<T> getOptionValues(final String letterOrName, final Class<T> type) {
final List<String> strings = Objects.firstNonNull(this.optionValues.get(letterOrName),
ImmutableList.<String>of());
return convert(strings, type);
}
@Nullable
public <T> T getOptionValue(final String letterOrName, final Class<T> type) {
final List<String> strings = this.optionValues.get(letterOrName);
if (strings == null || strings.isEmpty()) {
return null;
}
if (strings.size() > 1) {
throw new Exception("Multiple values for option '" + letterOrName + "': "
+ Joiner.on(", ").join(strings), null);
}
try {
return convert(strings.get(0), type);
} catch (final Throwable ex) {
throw new Exception("'" + strings.get(0) + "' is not a valid " + type.getSimpleName(),
ex);
}
}
@Nullable
public <T> T getOptionValue(final String letterOrName, final Class<T> type,
@Nullable final T defaultValue) {
final List<String> strings = this.optionValues.get(letterOrName);
if (strings == null || strings.isEmpty() || strings.size() > 1) {
return defaultValue;
}
try {
return convert(strings.get(0), type);
} catch (final Throwable ex) {
return defaultValue;
}
}
public int getOptionCount() {
return this.options.size();
}
@SuppressWarnings("unchecked")
private static <T> T convert(final String string, final Class<T> type) {
try {
if (Path.class.isAssignableFrom(type)) {
return (T) Paths.get(string);
}
return Statements.convert(string, type);
} catch (final Throwable ex) {
throw new Exception("'" + string + "' is not a valid " + type.getSimpleName(), ex);
}
}
@SuppressWarnings("unchecked")
private static <T> List<T> convert(final List<String> strings, final Class<T> type) {
if (type == String.class) {
return (List<T>) strings;
}
final List<T> list = Lists.newArrayList();
for (final String string : strings) {
list.add(convert(string, type));
}
return ImmutableList.copyOf(list);
}
public static void fail(final Throwable throwable) {
if (throwable instanceof Exception) {
if (throwable.getMessage() == null) {
System.exit(0);
} else {
System.err.println("SYNTAX ERROR: " + throwable.getMessage());
}
System.exit(-2);
} else {
System.err.println("EXECUTION FAILED: " + throwable.getMessage());
throwable.printStackTrace();
System.exit(-1);
}
}
public static Parser parser() {
return new Parser();
}
public static final class Parser {
@Nullable
private String name;
@Nullable
private String header;
@Nullable
private String footer;
@Nullable
private Logger logger;
private final Options options;
private final Set<String> mandatoryOptions;
public Parser() {
this.name = null;
this.header = null;
this.footer = null;
this.options = new Options();
this.mandatoryOptions = new HashSet<>();
}
public Parser withName(@Nullable final String name) {
this.name = name;
return this;
}
public Parser withHeader(@Nullable final String header) {
this.header = header;
return this;
}
public Parser withFooter(@Nullable final String footer) {
this.footer = footer;
return this;
}
public Parser withLogger(@Nullable final Logger logger) {
this.logger = logger;
return this;
}
public Parser withOption(@Nullable final String letter, final String name,
final String description) {
Preconditions.checkNotNull(name);
Preconditions.checkArgument(name.length() > 1);
Preconditions.checkNotNull(description);
final Option option = new Option(letter, name, false, description);
this.options.addOption(option);
return this;
}
public Parser withOption(@Nullable final String letter, final String name,
final String description, final String argName, @Nullable final Type argType,
final boolean argRequired, final boolean multiValue, final boolean mandatory) {
Preconditions.checkNotNull(name);
Preconditions.checkArgument(name.length() > 1);
Preconditions.checkNotNull(description);
Preconditions.checkNotNull(argName);
Preconditions.checkNotNull(argType);
final Option option = new Option(letter, name, true, description);
option.setArgName(argName);
option.setOptionalArg(!argRequired);
option.setArgs(multiValue ? Short.MAX_VALUE : 1);
option.setType(argType.toClass());
this.options.addOption(option);
if (mandatory) {
this.mandatoryOptions.add(name);
}
return this;
}
@SuppressWarnings("unchecked")
public CommandLine parse(final String... args) {
try {
// Add additional options
if (this.logger != null) {
this.options.addOption("D", "verbose", false, "enable verbose output");
this.options.addOption("V", "very verbose", false,
"enable very verbose output");
}
this.options.addOption("v", "version", false,
"display version information and terminate");
this.options.addOption("h", "help", false,
"display this help message and terminate");
// Parse options
org.apache.commons.cli.CommandLine cmd = null;
try {
cmd = new GnuParser().parse(this.options, args);
} catch (final Throwable ex) {
System.err.println("SYNTAX ERROR: " + ex.getMessage());
printHelp();
throw new Exception(null);
}
// Handle verbose mode
try {
((ch.qos.logback.classic.Logger) this.logger).setLevel(Level.INFO);
if (cmd.hasOption('D')) {
((ch.qos.logback.classic.Logger) this.logger).setLevel(Level.DEBUG);
}
if (cmd.hasOption('V')) {
((ch.qos.logback.classic.Logger) this.logger).setLevel(Level.TRACE);
}
} catch (final Throwable ex) {
// ignore
}
// Handle version and help commands. Throw an exception to halt execution
if (cmd.hasOption('v')) {
printVersion();
throw new Exception(null);
} else if (cmd.hasOption('h')) {
printHelp();
throw new Exception(null);
}
// Check that mandatory options have been specified
for (final String name : this.mandatoryOptions) {
if (!cmd.hasOption(name)) {
System.err.println("SYNTAX ERROR: missing mandatory option " + name);
printHelp();
throw new Exception(null);
}
}
// Extract options and their arguments
final Map<String, List<String>> optionValues = Maps.newHashMap();
for (final Option option : cmd.getOptions()) {
final List<String> valueList = Lists.newArrayList();
final String[] values = cmd.getOptionValues(option.getLongOpt());
if (values != null) {
for (final String value : values) {
if (option.getType() instanceof Type) {
Type.validate(value, (Type) option.getType());
}
valueList.add(value);
}
}
final List<String> valueSet = ImmutableList.copyOf(valueList);
optionValues.put(option.getLongOpt(), valueSet);
if (option.getOpt() != null) {
optionValues.put(option.getOpt(), valueSet);
}
}
// Create and return the resulting CommandLine object
return new CommandLine(ImmutableList.copyOf(cmd.getArgList()), optionValues);
} catch (final Throwable ex) {
throw new Exception(ex.getMessage(), ex);
}
}
private void printVersion() {
String version = "(development)";
final URL url = CommandLine.class.getClassLoader().getResource(
"META-INF/maven/eu.fbk.nafview/nafview/pom.properties");
if (url != null) {
try {
final InputStream stream = url.openStream();
try {
final Properties properties = new Properties();
properties.load(stream);
version = properties.getProperty("version").trim();
} finally {
stream.close();
}
} catch (final IOException ex) {
version = "(unknown)";
}
}
final String name = Objects.firstNonNull(this.name, "Version");
System.out.println(String.format("%s %s\nJava %s bit (%s) %s\n", name, version,
System.getProperty("sun.arch.data.model"), System.getProperty("java.vendor"),
System.getProperty("java.version")));
}
private void printHelp() {
final HelpFormatter formatter = new HelpFormatter();
final PrintWriter out = new PrintWriter(System.out);
final String name = Objects.firstNonNull(this.name, "java");
formatter.printUsage(out, 80, name, this.options);
if (this.header != null) {
out.println();
formatter.printWrapped(out, 80, this.header);
}
out.println();
formatter.printOptions(out, 80, this.options, 2, 2);
if (this.footer != null) {
out.println();
out.println(this.footer);
// formatter.printWrapped(out, 80, this.footer);
}
out.flush();
}
}
public static final class Exception extends RuntimeException {
private static final long serialVersionUID = 1L;
public Exception(final String message) {
super(message);
}
public Exception(final String message, final Throwable cause) {
super(message, cause);
}
}
public enum Type {
STRING,
INTEGER,
POSITIVE_INTEGER,
NON_NEGATIVE_INTEGER,
FLOAT,
POSITIVE_FLOAT,
NON_NEGATIVE_FLOAT,
FILE,
FILE_EXISTING,
DIRECTORY,
DIRECTORY_EXISTING;
public boolean validate(final String string) {
// Polymorphism not used for performance reasons
return validate(string, this);
}
public Class toClass() {
return toClass.get(this);
}
public static HashMap<Type, Class> toClass = new HashMap<>();
static {
toClass.put(Type.STRING, String.class);
toClass.put(Type.INTEGER, Integer.class);
toClass.put(Type.POSITIVE_INTEGER, Integer.class);
toClass.put(Type.NON_NEGATIVE_INTEGER, Integer.class);
toClass.put(Type.FLOAT, Float.class);
toClass.put(Type.POSITIVE_FLOAT, Float.class);
toClass.put(Type.NON_NEGATIVE_FLOAT, Float.class);
toClass.put(Type.FILE, File.class);
toClass.put(Type.FILE_EXISTING, File.class);
toClass.put(Type.DIRECTORY, File.class);
toClass.put(Type.DIRECTORY_EXISTING, File.class);
}
private static boolean validate(final String string, final Type type) {
if (type == Type.INTEGER || type == Type.POSITIVE_INTEGER
|| type == Type.NON_NEGATIVE_INTEGER) {
try {
final long n = Long.parseLong(string);
if (type == Type.POSITIVE_INTEGER) {
return n > 0L;
} else if (type == Type.NON_NEGATIVE_INTEGER) {
return n >= 0L;
}
} catch (final Throwable ex) {
return false;
}
} else if (type == Type.FLOAT || type == Type.POSITIVE_FLOAT
|| type == Type.NON_NEGATIVE_FLOAT) {
try {
final double n = Double.parseDouble(string);
if (type == Type.POSITIVE_FLOAT) {
return n > 0.0;
} else if (type == Type.NON_NEGATIVE_FLOAT) {
return n >= 0.0;
}
} catch (final Throwable ex) {
return false;
}
} else if (type == FILE) {
final File file = new File(string);
return !file.exists() || file.isFile();
} else if (type == FILE_EXISTING) {
final File file = new File(string);
return file.exists() && file.isFile();
} else if (type == DIRECTORY) {
final File dir = new File(string);
return !dir.exists() || dir.isDirectory();
} else if (type == DIRECTORY_EXISTING) {
final File dir = new File(string);
return dir.exists() && dir.isDirectory();
}
return true;
}
}
}
|
package com.hubspot.singularity.data;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.hubspot.singularity.WebExceptions.badRequest;
import static com.hubspot.singularity.WebExceptions.checkBadRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import javax.inject.Singleton;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.dmfs.rfc5545.recur.InvalidRecurrenceRuleException;
import org.dmfs.rfc5545.recur.RecurrenceRule;
import org.quartz.CronExpression;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.hash.Hashing;
import com.google.inject.Inject;
import com.hubspot.mesos.Resources;
import com.hubspot.mesos.SingularityContainerInfo;
import com.hubspot.mesos.SingularityContainerType;
import com.hubspot.mesos.SingularityDockerInfo;
import com.hubspot.mesos.SingularityDockerPortMapping;
import com.hubspot.mesos.SingularityPortMappingType;
import com.hubspot.mesos.SingularityVolume;
import com.hubspot.singularity.ScheduleType;
import com.hubspot.singularity.SingularityDeploy;
import com.hubspot.singularity.SingularityDeployBuilder;
import com.hubspot.singularity.SingularityRequest;
import com.hubspot.singularity.SingularityWebhook;
import com.hubspot.singularity.api.SingularityBounceRequest;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.history.DeployHistoryHelper;
@Singleton
public class SingularityValidator {
private static final Joiner JOINER = Joiner.on(" ");
private static final List<Character> DEPLOY_ID_ILLEGAL_CHARACTERS = Arrays.asList('@', '-', '\\', '/', '*', '?', '%', ' ', '[', ']', '#', '$'); // Characters that make Mesos or URL bars sad
private static final List<Character> REQUEST_ID_ILLEGAL_CHARACTERS = Arrays.asList('@', '\\', '/', '*', '?', '%', ' ', '[', ']', '#', '$'); // Characters that make Mesos or URL bars sad
private static final Pattern DAY_RANGE_REGEXP = Pattern.compile("[0-7]-[0-7]");
private static final Pattern COMMA_DAYS_REGEXP = Pattern.compile("([0-7],)+([0-7])?");
private final int maxDeployIdSize;
private final int maxRequestIdSize;
private final int maxCpusPerRequest;
private final int maxCpusPerInstance;
private final int maxInstancesPerRequest;
private final int defaultBounceExpirationMinutes;
private final int maxMemoryMbPerRequest;
private final int maxMemoryMbPerInstance;
private final boolean allowRequestsWithoutOwners;
private final boolean createDeployIds;
private final int deployIdLength;
private final DeployHistoryHelper deployHistoryHelper;
private final Resources defaultResources;
@Inject
public SingularityValidator(SingularityConfiguration configuration, DeployHistoryHelper deployHistoryHelper) {
this.maxDeployIdSize = configuration.getMaxDeployIdSize();
this.maxRequestIdSize = configuration.getMaxRequestIdSize();
this.allowRequestsWithoutOwners = configuration.isAllowRequestsWithoutOwners();
this.createDeployIds = configuration.isCreateDeployIds();
this.deployIdLength = configuration.getDeployIdLength();
this.deployHistoryHelper = deployHistoryHelper;
int defaultCpus = configuration.getMesosConfiguration().getDefaultCpus();
int defaultMemoryMb = configuration.getMesosConfiguration().getDefaultMemory();
int defaultDiskMb = configuration.getMesosConfiguration().getDefaultDisk();
this.defaultBounceExpirationMinutes = configuration.getDefaultBounceExpirationMinutes();
defaultResources = new Resources(defaultCpus, defaultMemoryMb, 0, defaultDiskMb);
this.maxCpusPerInstance = configuration.getMesosConfiguration().getMaxNumCpusPerInstance();
this.maxCpusPerRequest = configuration.getMesosConfiguration().getMaxNumCpusPerRequest();
this.maxMemoryMbPerInstance = configuration.getMesosConfiguration().getMaxMemoryMbPerInstance();
this.maxMemoryMbPerRequest = configuration.getMesosConfiguration().getMaxMemoryMbPerRequest();
this.maxInstancesPerRequest = configuration.getMesosConfiguration().getMaxNumInstancesPerRequest();
}
public SingularityRequest checkSingularityRequest(SingularityRequest request, Optional<SingularityRequest> existingRequest, Optional<SingularityDeploy> activeDeploy,
Optional<SingularityDeploy> pendingDeploy) {
checkBadRequest(request.getId() != null && !StringUtils.containsAny(request.getId(), JOINER.join(REQUEST_ID_ILLEGAL_CHARACTERS)), "Id can not be null or contain any of the following characters: %s", REQUEST_ID_ILLEGAL_CHARACTERS);
checkBadRequest(request.getRequestType() != null, "RequestType cannot be null or missing");
if (request.getOwners().isPresent()) {
checkBadRequest(!request.getOwners().get().contains(null), "Request owners cannot contain null values");
}
if (!allowRequestsWithoutOwners) {
checkBadRequest(request.getOwners().isPresent() && !request.getOwners().get().isEmpty(), "Request must have owners defined (this can be turned off in Singularity configuration)");
}
checkBadRequest(request.getId().length() < maxRequestIdSize, "Request id must be less than %s characters, it is %s (%s)", maxRequestIdSize, request.getId().length(), request.getId());
checkBadRequest(!request.getInstances().isPresent() || request.getInstances().get() > 0, "Instances must be greater than 0");
checkBadRequest(request.getInstancesSafe() <= maxInstancesPerRequest, "Instances (%s) be greater than %s (maxInstancesPerRequest in mesos configuration)", request.getInstancesSafe(), maxInstancesPerRequest);
if (existingRequest.isPresent()) {
checkForIllegalChanges(request, existingRequest.get());
}
if (activeDeploy.isPresent()) {
checkForIllegalResources(request, activeDeploy.get());
}
if (pendingDeploy.isPresent()) {
checkForIllegalResources(request, pendingDeploy.get());
}
String quartzSchedule = null;
if (request.isScheduled()) {
checkBadRequest(request.getQuartzSchedule().isPresent() || request.getSchedule().isPresent(), "Specify at least one of schedule or quartzSchedule");
String originalSchedule = request.getQuartzScheduleSafe();
if (request.getScheduleType().or(ScheduleType.QUARTZ) != ScheduleType.RFC5545) {
if (request.getQuartzSchedule().isPresent() && !request.getSchedule().isPresent()) {
checkBadRequest(request.getScheduleType().or(ScheduleType.QUARTZ) == ScheduleType.QUARTZ, "If using quartzSchedule specify scheduleType QUARTZ or leave it blank");
}
if (request.getQuartzSchedule().isPresent() || (request.getScheduleType().isPresent() && request.getScheduleType().get() == ScheduleType.QUARTZ)) {
quartzSchedule = originalSchedule;
} else {
checkBadRequest(request.getScheduleType().or(ScheduleType.CRON) == ScheduleType.CRON, "If not using quartzSchedule specify scheduleType CRON or leave it blank");
checkBadRequest(!request.getQuartzSchedule().isPresent(), "If using schedule type CRON do not specify quartzSchedule");
quartzSchedule = getQuartzScheduleFromCronSchedule(originalSchedule);
}
checkBadRequest(isValidCronSchedule(quartzSchedule), "Schedule %s (from: %s) is not valid", quartzSchedule, originalSchedule);
} else {
checkForValidRFC5545Schedule(request.getSchedule().get());
}
} else {
checkBadRequest(!request.getQuartzSchedule().isPresent() && !request.getSchedule().isPresent(), "Non-scheduled requests can not specify a schedule");
checkBadRequest(!request.getScheduleType().isPresent(), "ScheduleType can only be set for scheduled requests");
}
if (request.getScheduleTimeZone().isPresent()) {
if (!ArrayUtils.contains(TimeZone.getAvailableIDs(), request.getScheduleTimeZone().get())) {
badRequest("scheduleTimeZone %s does not map to a valid Java TimeZone object (e.g. 'US/Eastern' or 'GMT')", request.getScheduleTimeZone().get());
}
}
if (!request.isLongRunning()) {
checkBadRequest(!request.isLoadBalanced(), "non-longRunning (scheduled/oneoff) requests can not be load balanced");
checkBadRequest(!request.isRackSensitive(), "non-longRunning (scheduled/oneoff) requests can not be rack sensitive");
} else {
checkBadRequest(!request.getNumRetriesOnFailure().isPresent(), "NumRetriesOnFailure can only be set for non-long running requests");
checkBadRequest(!request.getKillOldNonLongRunningTasksAfterMillis().isPresent(), "longRunning requests can not define a killOldNonLongRunningTasksAfterMillis value");
}
if (request.isScheduled()) {
checkBadRequest(request.getInstances().or(1) == 1, "Scheduler requests can not be ran on more than one instance");
} else if (request.isOneOff()) {
checkBadRequest(!request.getInstances().isPresent(), "one-off requests can not define a # of instances");
}
return request.toBuilder().setQuartzSchedule(Optional.fromNullable(quartzSchedule)).build();
}
public SingularityWebhook checkSingularityWebhook(SingularityWebhook webhook) {
checkNotNull(webhook, "Webhook is null");
checkNotNull(webhook.getUri(), "URI is null");
try {
new URI(webhook.getUri());
} catch (URISyntaxException e) {
badRequest("Invalid URI provided");
}
return webhook;
}
public SingularityDeploy checkDeploy(SingularityRequest request, SingularityDeploy deploy) {
checkNotNull(request, "request is null");
checkNotNull(deploy, "deploy is null");
String deployId = deploy.getId();
if (deployId == null) {
checkBadRequest(createDeployIds, "Id must not be null");
SingularityDeployBuilder builder = deploy.toBuilder();
builder.setId(createUniqueDeployId());
deploy = builder.build();
deployId = deploy.getId();
}
checkBadRequest(deployId != null && !StringUtils.containsAny(deployId, JOINER.join(DEPLOY_ID_ILLEGAL_CHARACTERS)), "Id must not be null and can not contain any of the following characters: %s", DEPLOY_ID_ILLEGAL_CHARACTERS);
checkBadRequest(deployId.length() < maxDeployIdSize, "Deploy id must be less than %s characters, it is %s (%s)", maxDeployIdSize, deployId.length(), deployId);
checkBadRequest(deploy.getRequestId() != null && deploy.getRequestId().equals(request.getId()), "Deploy id must match request id");
if (request.isLoadBalanced()) {
checkBadRequest(deploy.getServiceBasePath().isPresent(), "Deploy for loadBalanced request must include serviceBasePath");
checkBadRequest(deploy.getLoadBalancerGroups().isPresent() && !deploy.getLoadBalancerGroups().get().isEmpty(), "Deploy for a loadBalanced request must include at least one load balacner group");
}
checkForIllegalResources(request, deploy);
if (deploy.getResources().isPresent()) {
if (deploy.getHealthcheckPortIndex().isPresent()) {
checkBadRequest(deploy.getHealthcheckPortIndex().get() >= 0, "healthcheckPortIndex must be greater than 0");
checkBadRequest(deploy.getResources().get().getNumPorts() > deploy.getHealthcheckPortIndex().get(), String
.format("Must request %s ports for healthcheckPortIndex %s, only requested %s", deploy.getHealthcheckPortIndex().get() + 1, deploy.getHealthcheckPortIndex().get(),
deploy.getResources().get().getNumPorts()));
}
if (deploy.getLoadBalancerPortIndex().isPresent()) {
checkBadRequest(deploy.getLoadBalancerPortIndex().get() >= 0, "loadBalancerPortIndex must be greater than 0");
checkBadRequest(deploy.getResources().get().getNumPorts() > deploy.getLoadBalancerPortIndex().get(), String
.format("Must request %s ports for loadBalancerPortIndex %s, only requested %s", deploy.getLoadBalancerPortIndex().get() + 1, deploy.getLoadBalancerPortIndex().get(),
deploy.getResources().get().getNumPorts()));
}
}
checkBadRequest(deploy.getCommand().isPresent() && !deploy.getExecutorData().isPresent() ||
deploy.getExecutorData().isPresent() && deploy.getCustomExecutorCmd().isPresent() && !deploy.getCommand().isPresent() ||
deploy.getContainerInfo().isPresent(),
"If not using custom executor, specify a command or containerInfo. If using custom executor, specify executorData and customExecutorCmd and no command.");
checkBadRequest(!deploy.getContainerInfo().isPresent() || deploy.getContainerInfo().get().getType() != null, "Container type must not be null");
if (deploy.getContainerInfo().isPresent()) {
SingularityContainerInfo containerInfo = deploy.getContainerInfo().get();
checkBadRequest(containerInfo.getType() != null, "container type may not be null");
if (containerInfo.getVolumes().isPresent() && !containerInfo.getVolumes().get().isEmpty()) {
for (SingularityVolume volume : containerInfo.getVolumes().get()) {
checkBadRequest(volume.getContainerPath() != null, "volume containerPath may not be null");
}
}
if (deploy.getContainerInfo().get().getType() == SingularityContainerType.DOCKER) {
checkDocker(deploy);
}
}
checkBadRequest(deployHistoryHelper.isDeployIdAvailable(request.getId(), deployId), "Can not deploy a deploy that has already been deployed");
return deploy;
}
/**
*
* Transforms unix cron into quartz compatible cron;
*
* - adds seconds if not included
* - switches either day of month or day of week to ?
*
* Field Name Allowed Values Allowed Special Characters
* Seconds 0-59 - * /
* Minutes 0-59 - * /
* Hours 0-23 - * /
* Day-of-month 1-31 - * ? / L W
* Month 1-12 or JAN-DEC - * /
* Day-of-Week 1-7 or SUN-SAT - * ? / L #
* Year (Optional), 1970-2199 - * /
*/
public String getQuartzScheduleFromCronSchedule(String schedule) {
if (schedule == null) {
return null;
}
String[] split = schedule.split(" ");
checkBadRequest(split.length >= 4, "Schedule %s is invalid because it contained only %s splits (looking for at least 4)", schedule, split.length);
List<String> newSchedule = Lists.newArrayListWithCapacity(6);
boolean hasSeconds = split.length > 5;
if (!hasSeconds) {
newSchedule.add("0");
} else {
newSchedule.add(split[0]);
}
int indexMod = hasSeconds ? 1 : 0;
newSchedule.add(split[indexMod]);
newSchedule.add(split[indexMod + 1]);
String dayOfMonth = split[indexMod + 2];
String dayOfWeek = split[indexMod + 4];
if (dayOfWeek.equals("*")) {
dayOfWeek = "?";
} else if (!dayOfWeek.equals("?")) {
dayOfMonth = "?";
}
if (isValidInteger(dayOfWeek)) {
dayOfWeek = getNewDayOfWeekValue(schedule, Integer.parseInt(dayOfWeek));
} else if (DAY_RANGE_REGEXP.matcher(dayOfWeek).matches() || COMMA_DAYS_REGEXP.matcher(dayOfWeek).matches()) {
String separator = ",";
if (DAY_RANGE_REGEXP.matcher(dayOfWeek).matches()) {
separator = "-";
}
final String[] dayOfWeekSplit = dayOfWeek.split(separator);
final List<String> dayOfWeekValues = new ArrayList<>(dayOfWeekSplit.length);
for (String dayOfWeekValue : dayOfWeekSplit) {
dayOfWeekValues.add(getNewDayOfWeekValue(schedule, Integer.parseInt(dayOfWeekValue)));
}
dayOfWeek = Joiner.on(separator).join(dayOfWeekValues);
}
newSchedule.add(dayOfMonth);
newSchedule.add(split[indexMod + 3]);
newSchedule.add(dayOfWeek);
return JOINER.join(newSchedule);
}
private void checkForIllegalChanges(SingularityRequest request, SingularityRequest existingRequest) {
checkBadRequest(request.getRequestType() == existingRequest.getRequestType(), String.format("Request can not change requestType from %s to %s", existingRequest.getRequestType(), request.getRequestType()));
checkBadRequest(request.isLoadBalanced() == existingRequest.isLoadBalanced(), "Request can not change whether it is load balanced");
}
private void checkForIllegalResources(SingularityRequest request, SingularityDeploy deploy) {
int instances = request.getInstancesSafe();
double cpusPerInstance = deploy.getResources().or(defaultResources).getCpus();
double memoryMbPerInstance = deploy.getResources().or(defaultResources).getMemoryMb();
checkBadRequest(cpusPerInstance > 0, "Request must have more than 0 cpus");
checkBadRequest(memoryMbPerInstance > 0, "Request must have more than 0 memoryMb");
checkBadRequest(cpusPerInstance <= maxCpusPerInstance, "Deploy %s uses too many cpus %s (maxCpusPerInstance %s in mesos configuration)", deploy.getId(), cpusPerInstance, maxCpusPerInstance);
checkBadRequest(cpusPerInstance * instances <= maxCpusPerRequest,
"Deploy %s uses too many cpus %s (%s*%s) (cpusPerRequest %s in mesos configuration)", deploy.getId(), cpusPerInstance * instances, cpusPerInstance, instances, maxCpusPerRequest);
checkBadRequest(memoryMbPerInstance <= maxMemoryMbPerInstance,
"Deploy %s uses too much memoryMb %s (maxMemoryMbPerInstance %s in mesos configuration)", deploy.getId(), memoryMbPerInstance, maxMemoryMbPerInstance);
checkBadRequest(memoryMbPerInstance * instances <= maxMemoryMbPerRequest, "Deploy %s uses too much memoryMb %s (%s*%s) (maxMemoryMbPerRequest %s in mesos configuration)", deploy.getId(),
memoryMbPerInstance * instances, memoryMbPerInstance, instances, maxMemoryMbPerRequest);
}
private void checkForValidRFC5545Schedule(String schedule) {
try {
new RecurrenceRule(schedule);
} catch (InvalidRecurrenceRuleException ex) {
badRequest("Schedule %s is not a valid RFC5545 schedule, error is: %s", schedule, ex);
}
}
private String createUniqueDeployId() {
UUID id = UUID.randomUUID();
String result = Hashing.sha256().newHasher().putLong(id.getLeastSignificantBits()).putLong(id.getMostSignificantBits()).hash().toString();
return result.substring(0, deployIdLength);
}
private void checkDocker(SingularityDeploy deploy) {
if (deploy.getResources().isPresent() && deploy.getContainerInfo().get().getDocker().isPresent()) {
final SingularityDockerInfo dockerInfo = deploy.getContainerInfo().get().getDocker().get();
final int numPorts = deploy.getResources().get().getNumPorts();
checkBadRequest(dockerInfo.getImage() != null, "docker image may not be null");
for (SingularityDockerPortMapping portMapping : dockerInfo.getPortMappings()) {
if (portMapping.getContainerPortType() == SingularityPortMappingType.FROM_OFFER) {
checkBadRequest(portMapping.getContainerPort() >= 0 && portMapping.getContainerPort() < numPorts,
"Index of port resource for containerPort must be between 0 and %d (inclusive)", numPorts - 1);
}
if (portMapping.getHostPortType() == SingularityPortMappingType.FROM_OFFER) {
checkBadRequest(portMapping.getHostPort() >= 0 && portMapping.getHostPort() < numPorts,
"Index of port resource for hostPort must be between 0 and %d (inclusive)", numPorts - 1);
}
}
}
}
private boolean isValidCronSchedule(String schedule) {
return CronExpression.isValidExpression(schedule);
}
/**
* Standard cron: day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
* Quartz: 1-7 or SUN-SAT
*/
private String getNewDayOfWeekValue(String schedule, int dayOfWeekValue) {
String newDayOfWeekValue = null;
checkBadRequest(dayOfWeekValue >= 0 && dayOfWeekValue <= 7, "Schedule %s is invalid, day of week (%s) is not 0-7", schedule, dayOfWeekValue);
switch (dayOfWeekValue) {
case 7:
case 0:
newDayOfWeekValue = "SUN";
break;
case 1:
newDayOfWeekValue = "MON";
break;
case 2:
newDayOfWeekValue = "TUE";
break;
case 3:
newDayOfWeekValue = "WED";
break;
case 4:
newDayOfWeekValue = "THU";
break;
case 5:
newDayOfWeekValue = "FRI";
break;
case 6:
newDayOfWeekValue = "SAT";
break;
default:
badRequest("Schedule %s is invalid, day of week (%s) is not 0-7", schedule, dayOfWeekValue);
break;
}
return newDayOfWeekValue;
}
private boolean isValidInteger(String strValue) {
try {
Integer.parseInt(strValue);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
public SingularityBounceRequest checkBounceRequest(SingularityBounceRequest defaultBounceRequest) {
if (defaultBounceRequest.getDurationMillis().isPresent()) {
return defaultBounceRequest;
}
final long durationMillis = TimeUnit.MINUTES.toMillis(defaultBounceExpirationMinutes);
return defaultBounceRequest
.toBuilder()
.setDurationMillis(Optional.of(durationMillis))
.build();
}
}
|
package org.innovateuk.ifs.project.core.transactional;
import org.apache.commons.lang3.StringUtils;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competitionsetup.domain.CompetitionDocument;
import org.innovateuk.ifs.finance.transactional.FinanceService;
import org.innovateuk.ifs.invite.domain.ProjectParticipantRole;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.project.bankdetails.domain.BankDetails;
import org.innovateuk.ifs.project.bankdetails.repository.BankDetailsRepository;
import org.innovateuk.ifs.project.constant.ProjectActivityStates;
import org.innovateuk.ifs.project.core.domain.PartnerOrganisation;
import org.innovateuk.ifs.project.core.domain.Project;
import org.innovateuk.ifs.project.core.domain.ProjectUser;
import org.innovateuk.ifs.project.core.mapper.ProjectMapper;
import org.innovateuk.ifs.project.core.mapper.ProjectUserMapper;
import org.innovateuk.ifs.project.core.repository.ProjectUserRepository;
import org.innovateuk.ifs.project.document.resource.DocumentStatus;
import org.innovateuk.ifs.project.documents.domain.ProjectDocument;
import org.innovateuk.ifs.project.finance.resource.EligibilityState;
import org.innovateuk.ifs.project.finance.resource.ViabilityState;
import org.innovateuk.ifs.project.financechecks.service.FinanceCheckService;
import org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration.EligibilityWorkflowHandler;
import org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration.ViabilityWorkflowHandler;
import org.innovateuk.ifs.project.grantofferletter.configuration.workflow.GrantOfferLetterWorkflowHandler;
import org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterState;
import org.innovateuk.ifs.project.monitoringofficer.domain.MonitoringOfficer;
import org.innovateuk.ifs.project.monitoringofficer.repository.MonitoringOfficerRepository;
import org.innovateuk.ifs.project.projectdetails.workflow.configuration.ProjectDetailsWorkflowHandler;
import org.innovateuk.ifs.project.spendprofile.configuration.workflow.SpendProfileWorkflowHandler;
import org.innovateuk.ifs.project.spendprofile.domain.SpendProfile;
import org.innovateuk.ifs.project.spendprofile.repository.SpendProfileRepository;
import org.innovateuk.ifs.transactional.BaseTransactionalService;
import org.innovateuk.ifs.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static org.innovateuk.ifs.commons.error.CommonErrors.forbiddenError;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.invite.domain.ProjectParticipantRole.PROJECT_PARTNER;
import static org.innovateuk.ifs.project.constant.ProjectActivityStates.*;
import static org.innovateuk.ifs.project.grantofferletter.resource.GrantOfferLetterState.SENT;
import static org.innovateuk.ifs.project.resource.ApprovalType.APPROVED;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFindFirst;
/**
* Abstract service for handling project service functionality.
*/
public class AbstractProjectServiceImpl extends BaseTransactionalService {
@Autowired
protected ProjectMapper projectMapper;
@Autowired
protected ProjectUserRepository projectUserRepository;
@Autowired
protected ProjectUserMapper projectUserMapper;
@Autowired
protected MonitoringOfficerRepository monitoringOfficerRepository;
@Autowired
protected BankDetailsRepository bankDetailsRepository;
@Autowired
protected SpendProfileRepository spendProfileRepository;
@Autowired
protected FinanceService financeService;
@Autowired
protected FinanceCheckService financeCheckService;
@Autowired
private ProjectDetailsWorkflowHandler projectDetailsWorkflowHandler;
@Autowired
private GrantOfferLetterWorkflowHandler golWorkflowHandler;
@Autowired
private ViabilityWorkflowHandler viabilityWorkflowHandler;
@Autowired
private EligibilityWorkflowHandler eligibilityWorkflowHandler;
@Autowired
private SpendProfileWorkflowHandler spendProfileWorkflowHandler;
List<ProjectUser> getProjectUsersByProjectId(Long projectId) {
return projectUserRepository.findByProjectId(projectId);
}
protected ProjectActivityStates createDocumentStatus(Project project) {
List<ProjectDocument> projectDocuments = project.getProjectDocuments();
int expectedNumberOfDocuments = expectedNumberOfDocuments(project);
int actualNumberOfDocuments = projectDocuments.size();
if (actualNumberOfDocuments == expectedNumberOfDocuments && projectDocuments.stream()
.allMatch(projectDocumentResource -> DocumentStatus.APPROVED.equals(projectDocumentResource.getStatus()))) {
return COMPLETE;
}
if (actualNumberOfDocuments != expectedNumberOfDocuments || projectDocuments.stream()
.anyMatch(projectDocumentResource -> DocumentStatus.UPLOADED.equals(projectDocumentResource.getStatus())
|| DocumentStatus.REJECTED.equals(projectDocumentResource.getStatus()))) {
return ACTION_REQUIRED;
}
return PENDING;
}
private int expectedNumberOfDocuments(Project project) {
List<PartnerOrganisation> partnerOrganisations = project.getPartnerOrganisations();
List<CompetitionDocument> expectedDocuments = project.getApplication().getCompetition().getCompetitionDocuments();
int expectedNumberOfDocuments = expectedDocuments.size();
if (partnerOrganisations.size() == 1) {
List<String> documentNames = expectedDocuments.stream().map(document -> document.getTitle()).collect(Collectors.toList());
if (documentNames.contains("Collaboration agreement")) {
expectedNumberOfDocuments = expectedDocuments.size() - 1;
}
}
return expectedNumberOfDocuments;
}
protected ProjectActivityStates createFinanceContactStatus(Project project, Organisation partnerOrganisation) {
return getFinanceContact(project, partnerOrganisation).map(existing -> COMPLETE).orElse(ACTION_REQUIRED);
}
protected ProjectActivityStates createPartnerProjectLocationStatus(Project project, Organisation organisation) {
boolean locationPresent = project.getPartnerOrganisations().stream()
.filter(partnerOrganisation -> partnerOrganisation.getOrganisation().getId().equals(organisation.getId()))
.findFirst()
.map(partnerOrganisation -> StringUtils.isNotBlank(partnerOrganisation.getPostcode()))
.orElse(false);
return locationPresent ? COMPLETE : ACTION_REQUIRED;
}
protected Optional<ProjectUser> getFinanceContact(final Project project, final Organisation organisation) {
return simpleFindFirst(project.getProjectUsers(), pu -> pu.getRole().isFinanceContact()
&& pu.getOrganisation().getId().equals(organisation.getId()));
}
protected ProjectActivityStates createProjectDetailsStatus(Project project) {
return projectDetailsWorkflowHandler.isSubmitted(project) ? COMPLETE : ACTION_REQUIRED;
}
protected ProjectActivityStates createMonitoringOfficerStatus(final Optional<MonitoringOfficer> monitoringOfficer, final ProjectActivityStates leadProjectDetailsSubmitted) {
if (leadProjectDetailsSubmitted.equals(COMPLETE)) {
return monitoringOfficer.isPresent() ? COMPLETE : PENDING;
} else {
return NOT_STARTED;
}
}
protected ProjectActivityStates createBankDetailStatus(Long projectId, Long applicationId, Long organisationId, final Optional<BankDetails> bankDetails, ProjectActivityStates financeContactStatus) {
if (bankDetails.isPresent()) {
return bankDetails.get().isApproved() ? COMPLETE : PENDING;
} else if (!isSeekingFunding(projectId, applicationId, organisationId)) {
return NOT_REQUIRED;
} else if (COMPLETE.equals(financeContactStatus)) {
return ACTION_REQUIRED;
} else {
return NOT_STARTED;
}
}
private boolean isSeekingFunding(Long projectId, Long applicationId, Long organisationId) {
return financeService.organisationSeeksFunding(projectId, applicationId, organisationId)
.getOptionalSuccessObject()
.map(Boolean::booleanValue)
.orElse(false);
}
protected ProjectActivityStates createFinanceCheckStatus(final Project project, final Organisation organisation, boolean isAwaitingResponse) {
PartnerOrganisation partnerOrg = partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation.getId());
if (financeChecksApproved(partnerOrg)) {
return COMPLETE;
} else if (isAwaitingResponse) {
return ACTION_REQUIRED;
} else {
return PENDING;
}
}
private boolean financeChecksApproved(PartnerOrganisation partnerOrg) {
return asList(EligibilityState.APPROVED, EligibilityState.NOT_APPLICABLE).contains(eligibilityWorkflowHandler.getState(partnerOrg)) &&
asList(ViabilityState.APPROVED, ViabilityState.NOT_APPLICABLE).contains(viabilityWorkflowHandler.getState(partnerOrg));
}
protected ProjectActivityStates createLeadSpendProfileStatus(final Project project, final ProjectActivityStates financeCheckStatus, final Optional<SpendProfile> spendProfile) {
ProjectActivityStates spendProfileStatus = createSpendProfileStatus(financeCheckStatus, spendProfile);
if (COMPLETE.equals(spendProfileStatus) && !APPROVED.equals(spendProfileWorkflowHandler.getApproval(project))) {
return project.getSpendProfileSubmittedDate() != null ? PENDING : ACTION_REQUIRED;
} else {
return spendProfileStatus;
}
}
protected ProjectActivityStates createSpendProfileStatus(final ProjectActivityStates financeCheckStatus, final Optional<SpendProfile> spendProfile) {
if (!spendProfile.isPresent()) {
return NOT_STARTED;
} else if (financeCheckStatus.equals(COMPLETE) && spendProfile.get().isMarkedAsComplete()) {
return COMPLETE;
} else {
return ACTION_REQUIRED;
}
}
protected ProjectActivityStates createLeadGrantOfferLetterStatus(final Project project) {
GrantOfferLetterState state = golWorkflowHandler.getState(project);
if (SENT.equals(state)) {
return ACTION_REQUIRED;
} else if (GrantOfferLetterState.PENDING.equals(state) && project.getGrantOfferLetter() != null) {
return PENDING;
} else {
return createGrantOfferLetterStatus(project);
}
}
protected ProjectActivityStates createGrantOfferLetterStatus(final Project project) {
GrantOfferLetterState state = golWorkflowHandler.getState(project);
if (GrantOfferLetterState.APPROVED.equals(state)) {
return COMPLETE;
} else if (GrantOfferLetterState.PENDING.equals(state)){
return NOT_REQUIRED;
} else {
return PENDING;
}
}
protected ServiceResult<ProjectUser> getCurrentlyLoggedInPartner(Project project) {
return getCurrentlyLoggedInProjectUser(project, PROJECT_PARTNER);
}
private ServiceResult<ProjectUser> getCurrentlyLoggedInProjectUser(Project project, ProjectParticipantRole role) {
return getCurrentlyLoggedInUser().andOnSuccess(currentUser ->
simpleFindFirst(project.getProjectUsers(), pu -> findUserAndRole(role, currentUser, pu)).
map(user -> serviceSuccess(user)).
orElse(serviceFailure(forbiddenError())));
}
private boolean findUserAndRole(ProjectParticipantRole role, User currentUser, ProjectUser pu) {
return pu.getUser().getId().equals(currentUser.getId()) && pu.getRole().equals(role);
}
}
|
package de.jowisoftware.sshclient.util;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.log4j.Logger;
import de.jowisoftware.sshclient.SSHApp;
public class ApplicationUtils {
private static final String UPDATE_URL = "http://jowisoftware.de/ssh/build.properties";
private static final Logger LOGGER = Logger
.getLogger(ApplicationUtils.class);
private ApplicationUtils() { /* Util classes will not be instanciated */ }
private static class VersionInformation {
public final String revision;
public final String branch;
public final String date;
public VersionInformation(final String revision, final String branch, final String date) {
this.revision = revision;
this.branch = branch;
this.date = date;
}
}
public static String getVersion() {
final VersionInformation version;
try {
version = readVersion();
} catch(final IOException e) {
return "(Error while reading jar file)";
}
return version.branch + "-" + version.revision + " " + version.date;
}
public static String getAvailableUpdateVersion() {
final VersionInformation updateVersion;
final VersionInformation thisVersion;
try {
thisVersion = readVersion();
} catch (final IOException e) {
LOGGER.info("Could not read Manifest. Broken jar file?", e);
return null;
}
if (thisVersion.revision.isEmpty()) {
LOGGER.info("No SCM-Build, skipping update check");
return null;
}
try {
updateVersion = readUpdateProperties();
} catch (final IOException e) {
LOGGER.warn("Error while fetching update information", e);
return "Error while fetching update information: " + e.getMessage();
}
if (!thisVersion.revision.equals(updateVersion.revision)) {
return "Build " + updateVersion.revision + " (built: " +
updateVersion.date + ")";
} else {
return null;
}
}
private static VersionInformation readUpdateProperties() throws IOException {
final URL url = new URL(UPDATE_URL);
final InputStream urlStream = url.openStream();
final VersionInformation result = readFromStream(urlStream, false);
urlStream.close();
return result;
}
private static VersionInformation readVersion() throws IOException {
final Enumeration<URL> resources = ApplicationUtils.class.getClassLoader()
.getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
final InputStream stream = resources.nextElement().openStream();
final VersionInformation result = readFromStream(stream, true);
stream.close();
if (result != null) {
return result;
}
}
return new VersionInformation("unknown", "unknown", "unknown");
}
private static VersionInformation readFromStream(final InputStream stream,
final boolean filter)
throws IOException {
final Properties manifest = new Properties();
manifest.load(stream);
final String revision = manifest.getProperty("SCM-Revision");
final String branch = manifest.getProperty("SCM-Branch");
final String date = manifest.getProperty("Build-Date");
final String mainClass = manifest.getProperty("Main-Class");
final boolean isSSHManifest = mainClass != null && SSHApp.class.getName().equals(mainClass);
final boolean containsVersionInformation = revision != null && branch != null && date != null;
if (!filter || (isSSHManifest && containsVersionInformation)) {
return new VersionInformation(revision, branch, date);
}
return null;
}
}
|
package eve.corp.manager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
@SpringBootApplication
public class Application {
@ControllerAdvice
static class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
super("callback");
}
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
package de.proteinms.xtandemparser.parser;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* This class extracts information from the xtandem output xml.
*
* @author Thilo Muth
*/
public class XTandemParser implements Serializable {
/**
* Pattern to extract the modification mass number if multiple modification
* masses are given
*/
private static Pattern resModificationMassPattern = Pattern.compile("label=\"residue, modification mass (\\d+)\"");
private static Pattern refPotModificationMassPattern = Pattern.compile("label=\"refine, potential modification mass (\\d+)\"");
private static Pattern refPotModificationMotifPattern = Pattern.compile("label=\"refine, potential modification motif (\\d+)\"");
/**
* This variable holds the total number of spectra in the xtandem file
*/
private int iNumberOfSpectra = 0;
/**
* This map contains the key/value pairs of the input parameters.
*/
private HashMap<String, String> iInputParamMap = null;
/**
* This map contains the key/value pairs of the perform parameters.
*/
private HashMap<String, String> iPerformParamMap = null;
/**
* This map contains the key/value pairs of the modification information.
*/
private HashMap<String, String> iRawModMap = null;
/**
* This map contains the key/value pairs of the spectra information.
*/
private HashMap<String, String> iRawSpectrumMap = null;
/**
* This map contains the key/value pairs of the protein information.
*/
private HashMap<String, String> iRawProteinMap = null;
/**
* This map contains the key/value pairs of the peptide information.
*/
private HashMap<String, String> iRawPeptideMap = null;
/**
* This map contains the key/value pairs of the support data information.
*/
private HashMap<String, String> iSupportDataMap = null;
/**
* This list contains a list with all the protein ids.
*/
private ArrayList<String> iProteinIDList = null;
private HashMap<String, Integer> iTitle2SpectrumIDMap;
/**
* Constructor for parsing a result file stored locally.
*
* @param aFile The input XML file.
* @exception IOException
* @exception SAXException
*/
public XTandemParser(File aFile) throws IOException, SAXException {
this.parseXTandemFile(aFile);
}
/**
* In this method the X!Tandem file gets parsed.
*
* @param aInputFile The file which will be parsed.
* @exception IOException
* @exception SAXException
*/
private void parseXTandemFile(File aInputFile) throws IOException, SAXException {
NodeList idNodes, proteinNodes, peptideNodes, nodes, parameterNodes, supportDataNodes, xDataNodes, yDataNodes;
NodeList hyperNodes, convolNodes, aIonNodes, bIonNodes, cIonNodes, xIonNodes, yIonNodes, zIonNodes, fragIonNodes;
DocumentBuilderFactory dbf;
DocumentBuilder db;
Document dom;
Element docEle;
// Modifications: Specific to residues within a domain
String modificationName;
double modificationMass;
NamedNodeMap modificationMap;
try {
// Get the document builder factory
dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setAttribute("http://xml.org/sax/features/validation", false);
// Using factory to get an instance of document builder
db = dbf.newDocumentBuilder();
// Parse using builder to get DOM representation of the XML file
dom = db.parse(aInputFile);
// Get the root elememt
docEle = dom.getDocumentElement();
// Get all the nodes
nodes = docEle.getChildNodes();
// Initialize the maps
iInputParamMap = new HashMap<String, String>();
iPerformParamMap = new HashMap<String, String>();
iRawModMap = new HashMap<String, String>();
iRawSpectrumMap = new HashMap<String, String>();
iRawPeptideMap = new HashMap<String, String>();
iRawProteinMap = new HashMap<String, String>();
iSupportDataMap = new HashMap<String, String>();
iTitle2SpectrumIDMap = new HashMap<String, Integer>();
// List of all the protein ids
iProteinIDList = new ArrayList<String>();
boolean aIonFlag = false;
boolean bIonFlag = false;
boolean cIonFlag = false;
boolean xIonFlag = false;
boolean yIonFlag = false;
boolean zIonFlag = false;
int spectraCounter = 0;
// Parse the parameters first
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i).getAttributes() != null) {
if (nodes.item(i).getAttributes().getNamedItem("type") != null) {
// Parse the input parameters
if (nodes.item(i).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("parameters")
&& (nodes.item(i).getAttributes().getNamedItem("label").getNodeValue().equalsIgnoreCase("input parameters")
|| nodes.item(i).getAttributes().getNamedItem("label").getNodeValue().equalsIgnoreCase("unused input parameters"))) {
parameterNodes = nodes.item(i).getChildNodes();
// Iterate over all the parameter nodes
for (int m = 0; m < parameterNodes.getLength(); m++) {
if (parameterNodes.item(m).getAttributes() != null) {
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"list path, default parameters\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("DEFAULTPARAMPATH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"list path, taxonomy information\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("TAXONOMYINFOPATH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, histogram column width\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("HISTOCOLWIDTH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, histograms\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("HISTOEXIST", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, logpath\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("LOGPATH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, maximum valid expectation value\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("MAXVALIDEXPECT", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, message\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTMESSAGE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, one sequence copy\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("ONESEQCOPY", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, parameters\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTPARAMS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, path\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTPATH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, path hashing\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTPATHHASH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, performance\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTPERFORMANCE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, proteins\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTPROTEINS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, results\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTRESULTS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, sequence path\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTSEQPATH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, sequences\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTSEQUENCES", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, sort results by\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTSORTRESULTS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, spectra\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTSPECTRA", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"output, xsl path\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("OUTPUTSXSLPATH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"protein, C-terminal residue modification mass\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("C_TERMRESMODMASS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"protein, N-terminal residue modification mass\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("N_TERMRESMODMASS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"protein, cleavage C-terminal mass change\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("C_TERMCLEAVMASSCHANGE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"protein, cleavage N-terminal mass change\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("N_TERMCLEAVMASSCHANGE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"protein, cleavage site\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("CLEAVAGESITE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"protein, homolog management\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("HOMOLOGMANAGE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"protein, modified residue mass file\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("MODRESMASSFILE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"protein, taxon\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("TAXON", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("REFINE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, maximum valid expectation value\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("REFINEMAXVALIDEXPECT", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, modification mass\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("REFINEMODMASS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, point mutations\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("POINTMUTATIONS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, potential C-terminus modifications\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("POTC_TERMMODS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, potential N-terminus modifications\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("POTN_TERMMODS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, potential modification mass\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("POTMODMASS", parameterNodes.item(m).getTextContent());
}
}
// parse refine, potential modification mass [1-n]
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().toLowerCase().startsWith(
"label=\"refine, potential modification mass ")) {
// get the mod number
Matcher matcher = refPotModificationMassPattern.matcher(parameterNodes.item(m).getAttributes().getNamedItem("label").toString().toLowerCase());
if (matcher.find() && !parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("POTMODMASS_" + matcher.group(1), parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, potential modification motif\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("POTMODMOTIF", parameterNodes.item(m).getTextContent());
}
}
// parse refine, potential modification motif [1-n]
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().toLowerCase().startsWith(
"label=\"refine, potential modification motif ")) {
// get the mod number
Matcher matcher = refPotModificationMotifPattern.matcher(parameterNodes.item(m).getAttributes().getNamedItem("label").toString().toLowerCase());
if (matcher.find() && !parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("POTMODMOTIF_" + matcher.group(1), parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, sequence path\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("REFINESEQPATH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, spectrum synthesis\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("REFINESPECSYTNH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, tic percent\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("REFINETIC", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, unanticipated cleavage\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("REFINEUNANTICLEAV", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refine, use potential modifications for full refinement\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("POTMODSFULLREFINE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"residue, modification mass\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("RESIDUEMODMASS", parameterNodes.item(m).getTextContent());
}
}
// parse residue, modification mass [1-n]
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().toLowerCase().startsWith(
"label=\"residue, modification mass ")) {
// get the mod number
Matcher matcher = resModificationMassPattern.matcher(parameterNodes.item(m).getAttributes().getNamedItem("label").toString().toLowerCase());
if (matcher.find() && !parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("RESIDUEMODMASS_" + matcher.group(1), parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"residue, potential modification mass\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("RESIDUEPOTMODMASS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"residue, potential modification motif\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("RESIDUEPOTMODMOTIV", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, a ions\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORING_AIONS", parameterNodes.item(m).getTextContent());
if (parameterNodes.item(m).getTextContent().equals("yes")) {
aIonFlag = true;
}
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, b ions\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORING_BIONS", parameterNodes.item(m).getTextContent());
if (parameterNodes.item(m).getTextContent().equals("yes")) {
bIonFlag = true;
}
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, c ions\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORING_CIONS", parameterNodes.item(m).getTextContent());
if (parameterNodes.item(m).getTextContent().equals("yes")) {
cIonFlag = true;
}
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, cyclic permutation\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORINGCYCLPERM", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, include reverse\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORINGINCREV", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, maximum missed cleavage sites\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORINGMISSCLEAV", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, minimum ion count\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORINGMINIONCOUNT", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, pluggable scoring\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORINGPLUGSCORING", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, x ions\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORING_XIONS", parameterNodes.item(m).getTextContent());
if (parameterNodes.item(m).getTextContent().equals("yes")) {
xIonFlag = true;
}
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, y ions\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORING_YIONS", parameterNodes.item(m).getTextContent());
if (parameterNodes.item(m).getTextContent().equals("yes")) {
yIonFlag = true;
}
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, z ions\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORING_ZIONS", parameterNodes.item(m).getTextContent());
if (parameterNodes.item(m).getTextContent().equals("yes")) {
zIonFlag = true;
}
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"scoring, algorithm\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SCORING_ALGORITHM", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, dynamic range\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECDYNRANGE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, fragment mass type\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECFRAGMASSTYPE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, fragment monoisotopic mass error\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECMONOISOMASSERROR", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, fragment monoisotopic mass error units\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECMONOISOMASSERRORUNITS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, maximum parent charge\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECMAXPRECURSORCHANGE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, minimum fragment mz\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECMINFRAGMZ", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, minimum parent m+h\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECMINPRECURSORMZ", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, minimum peaks\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECMINPEAKS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, parent monoisotopic mass error minus\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECPARENTMASSERRORMINUS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, parent monoisotopic mass error plus\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECPARENTMASSERRORPLUS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, parent monoisotopic mass error units\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECPARENTMASSERRORUNITS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, parent monoisotopic mass isotope error\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECPARENTMASSISOERROR", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, path\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECTRUMPATH", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, sequence batch size\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECBATCHSIZE", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, threads\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECTHREADS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, total peaks\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECTOTALPEAK", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"spectrum, use noise suppression\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iInputParamMap.put("SPECUSENOISECOMP", parameterNodes.item(m).getTextContent());
}
}
}
}
}
// Parse the performance parameters
if (nodes.item(i).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("parameters")
&& nodes.item(i).getAttributes().getNamedItem("label").getNodeValue().equalsIgnoreCase("performance parameters")) {
parameterNodes = nodes.item(i).getChildNodes();
// Iterate over all the parameter nodes
for (int m = 0; m < parameterNodes.getLength(); m++) {
if (parameterNodes.item(m).getAttributes() != null) {
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"list path, sequence source
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("SEQSRC1", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"list path, sequence source
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("SEQSRC2", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"list path, sequence source
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("SEQSRC3", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"list path, sequence source description
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("SEQSRCDESC1", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"list path, sequence source description
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("SEQSRCDESC2", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"list path, sequence source description
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("SEQSRCDESC3", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"modelling, estimated false positives\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("ESTFP", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"modelling, spectrum noise suppression ratio\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("NOISESUPP", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"modelling, total peptides used\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("TOTALPEPUSED", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"modelling, total proteins used\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("TOTALPROTUSED", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"modelling, total spectra assigned\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("TOTALSPECASS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"modelling, total spectra used\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("TOTALSPECUSED", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"modelling, total unique assigned\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("TOTALUNIQUEASS", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"process, start time\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("PROCSTART", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"process, version\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("PROCVER", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"quality values\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("QUALVAL", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refining, # input models\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("INPUTMOD", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refining, # input spectra\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("INPUTSPEC", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refining, # partial cleavage\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("PARTCLEAV", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refining, # point mutations\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("POINTMUT", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refining, # potential C-terminii\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("POTC_TERM", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refining, # potential N-terminii\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("POTN_TERM", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"refining, # unanticipated cleavage\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("UNANTICLEAV", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"timing, initial modelling total (sec)\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("INITMODELTOTALTIME", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"timing, initial modelling/spectrum (sec)\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("INITMODELSPECTIME", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"timing, load sequence models (sec)\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("LOADSEQMODELTIME", parameterNodes.item(m).getTextContent());
}
}
if (parameterNodes.item(m).getAttributes().getNamedItem("label").toString().equalsIgnoreCase(
"label=\"timing, refinement/spectrum (sec)\"")) {
if (!parameterNodes.item(m).getTextContent().equals("")) {
iPerformParamMap.put("REFINETIME", parameterNodes.item(m).getTextContent());
}
}
}
}
}
}
}
}
// Iterate over all the nodes
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i).getAttributes() != null) {
if (nodes.item(i).getAttributes().getNamedItem("type") != null) {
// The model group contains all information about a single peptide identification
if (nodes.item(i).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("model")) {
spectraCounter++;
// id is the number associated with the mass spectrum that was identified
if (nodes.item(i).getAttributes().getNamedItem("id") != null) {
iRawSpectrumMap.put("id" + spectraCounter, nodes.item(i).getAttributes().getNamedItem("id").getNodeValue());
}
// mh is the parent/precursor ion mass from the spectrum
if (nodes.item(i).getAttributes().getNamedItem("mh") != null) {
iRawSpectrumMap.put("mh" + spectraCounter, nodes.item(i).getAttributes().getNamedItem("mh").getNodeValue());
}
// z is the parent/precursor ion charge
if (nodes.item(i).getAttributes().getNamedItem("z") != null) {
iRawSpectrumMap.put("z" + spectraCounter, nodes.item(i).getAttributes().getNamedItem("z").getNodeValue());
}
// rt is the parent/precursor retention time
if (nodes.item(i).getAttributes().getNamedItem("rt") != null) {
iRawSpectrumMap.put("rt" + spectraCounter, nodes.item(i).getAttributes().getNamedItem("rt").getNodeValue());
}
// expect is the expectation value for the top ranked protein identfied with this spectrum
if (nodes.item(i).getAttributes().getNamedItem("expect") != null) {
iRawSpectrumMap.put("expect" + spectraCounter, nodes.item(i).getAttributes().getNamedItem("expect").getNodeValue());
}
// label is the text from the protein sequence FASTA file description line for the top ranked protein identified
if (nodes.item(i).getAttributes().getNamedItem("label") != null) {
iRawSpectrumMap.put("label" + spectraCounter, nodes.item(i).getAttributes().getNamedItem("label").getNodeValue());
}
// sumI is the log10-value of the sum of all of the fragment ion intensities
if (nodes.item(i).getAttributes().getNamedItem("sumI") != null) {
iRawSpectrumMap.put("sumI" + spectraCounter, nodes.item(i).getAttributes().getNamedItem("sumI").getNodeValue());
}
// maxI is the maximum fragment ion intensity
if (nodes.item(i).getAttributes().getNamedItem("maxI") != null) {
iRawSpectrumMap.put("maxI" + spectraCounter, nodes.item(i).getAttributes().getNamedItem("maxI").getNodeValue());
}
// fI is a multiplier to convert the normalized spectrum back to the original intensity values
if (nodes.item(i).getAttributes().getNamedItem("fI") != null) {
iRawSpectrumMap.put("fI" + spectraCounter, nodes.item(i).getAttributes().getNamedItem("fI").getNodeValue());
}
}
}
}
// Calculate the number of spectra.
iNumberOfSpectra = spectraCounter;
// Get the identifications
idNodes = nodes.item(i).getChildNodes();
int p_counter = 0;
// Iterate over all the child nodes
for (int j = 0; j < idNodes.getLength(); j++) {
if (idNodes.item(j).getNodeName().equalsIgnoreCase("protein")) {
p_counter++;
// the identifier of this particular identification (spectrum
String protID = idNodes.item(j).getAttributes().getNamedItem("id").getNodeValue();
iProteinIDList.add(protID);
// a unique number of this protein, calculated by the search engine
iRawProteinMap.put("uid" + protID, idNodes.item(j).getAttributes().getNamedItem("uid").getNodeValue());
// the log10 value of the expection value of the protein
iRawProteinMap.put("expect" + protID, idNodes.item(j).getAttributes().getNamedItem("expect").getNodeValue());
// the description line from the FASTA file
iRawProteinMap.put("label" + protID, idNodes.item(j).getAttributes().getNamedItem("label").getNodeValue());
// the sum of all of the fragment ions that identify this protein
iRawProteinMap.put("sumI" + protID, idNodes.item(j).getAttributes().getNamedItem("sumI").getNodeValue());
proteinNodes = idNodes.item(j).getChildNodes();
// Iterate over all the protein nodes
for (int k = 0; k < proteinNodes.getLength(); k++) {
if (proteinNodes.item(k).getNodeName().equalsIgnoreCase("file")) {
// the path used to the original fasta file
iRawPeptideMap.put("URL" + "_s" + spectraCounter + "_p" + p_counter, proteinNodes.item(k).getAttributes().getNamedItem("URL").getNodeValue());
}
// the the sum of all the fragment ions that identify this protein
if (proteinNodes.item(k).getNodeName().equalsIgnoreCase("peptide")) {
iRawPeptideMap.put("s" + spectraCounter + "_p" + p_counter, protID);
iRawPeptideMap.put("start" + "_s" + spectraCounter + "_p"
+ p_counter, proteinNodes.item(k).getAttributes().getNamedItem("start").getNodeValue());
iRawPeptideMap.put("end" + "_s" + spectraCounter + "_p"
+ p_counter, proteinNodes.item(k).getAttributes().getNamedItem("end").getNodeValue());
iRawPeptideMap.put("seq" + "_s" + spectraCounter + "_p"
+ p_counter, proteinNodes.item(k).getTextContent());
peptideNodes = proteinNodes.item(k).getChildNodes();
// Domain counter
int dCount = 0;
// Iterate over all the peptide nodes
for (int m = 0; m < peptideNodes.getLength(); m++) {
// Get the domain entries
if (peptideNodes.item(m).getNodeName().equalsIgnoreCase("domain")) {
dCount++;
// Get the domainid
String domainID = peptideNodes.item(m).getAttributes().getNamedItem("id").getNodeValue();
iRawPeptideMap.put("s" + spectraCounter + "_p" + p_counter + "_d" + dCount, domainID);
iRawPeptideMap.put("domainid" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("id").getNodeValue());
// the start position of the peptide
iRawPeptideMap.put("domainstart" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("start").getNodeValue());
// the end position of the peptide
iRawPeptideMap.put("domainend" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("end").getNodeValue());
// the expect value
iRawPeptideMap.put("expect" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("expect").getNodeValue());
// the mass + a proton
iRawPeptideMap.put("mh" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("mh").getNodeValue());
// the mass delta
iRawPeptideMap.put("delta" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("delta").getNodeValue());
// the hyper score
iRawPeptideMap.put("hyperscore" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("hyperscore").getNodeValue());
// the next score
iRawPeptideMap.put("nextscore" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("nextscore").getNodeValue());
if (xIonFlag) {
// the x score
iRawPeptideMap.put("x_score" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("x_score").getNodeValue());
// the x ion number
iRawPeptideMap.put("x_ions" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("x_ions").getNodeValue());
}
if (yIonFlag) {
// the y score
iRawPeptideMap.put("y_score" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("y_score").getNodeValue());
// the y ion number
iRawPeptideMap.put("y_ions" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("y_ions").getNodeValue());
}
if (zIonFlag) {
// the z score
iRawPeptideMap.put("z_score" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("z_score").getNodeValue());
// the z ion number
iRawPeptideMap.put("z_ions" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("z_ions").getNodeValue());
}
if (aIonFlag) {
// the a score
iRawPeptideMap.put("a_score" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("a_score").getNodeValue());
// the a ion number
iRawPeptideMap.put("a_ions" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("a_ions").getNodeValue());
}
if (bIonFlag) {
// the b score
iRawPeptideMap.put("b_score" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("b_score").getNodeValue());
// the b ion number
iRawPeptideMap.put("b_ions" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("b_ions").getNodeValue());
}
if (cIonFlag) {
// the c score
iRawPeptideMap.put("c_score" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("c_score").getNodeValue());
// the c ion number
iRawPeptideMap.put("c_ions" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("c_ions").getNodeValue());
}
// the upstream flanking sequence
iRawPeptideMap.put("pre" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("pre").getNodeValue());
// the downstream flanking sequence
iRawPeptideMap.put("post" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("post").getNodeValue());
// the domain sequence
iRawPeptideMap.put("domainseq" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("seq").getNodeValue());
// the number of missed cleavages
iRawPeptideMap.put("missed_cleavages" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount, peptideNodes.item(m).getAttributes().getNamedItem("missed_cleavages").getNodeValue());
int modCounter = 0;
for (int n = 0; n < peptideNodes.item(m).getChildNodes().getLength(); n++) {
// Get the specific modifications (aa)
if (peptideNodes.item(m).getChildNodes().item(n).getNodeName().equalsIgnoreCase("aa")) {
modCounter++;
modificationMap = peptideNodes.item(m).getChildNodes().item(n).getAttributes();
modificationName = modificationMap.getNamedItem("type").getNodeValue();
// use the old calculation with domainStart!
//modificationMap.getNamedItem("at").getNodeValue()) - domainStart + 1)
iRawModMap.put("at" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount + "_m" + modCounter, modificationMap.getNamedItem("at").getNodeValue());
// modified is the residue mass change caused by the modification
modificationMass = Double.parseDouble(modificationMap.getNamedItem("modified").getNodeValue());
iRawModMap.put("modified" + "_s" + spectraCounter + "_p"
+ p_counter + "_d" + dCount + "_m" + modCounter, modificationMap.getNamedItem("modified").getNodeValue());
modificationName = modificationMass + "@" + modificationName;
// type is the single letter abbreviation for the modified residue
iRawModMap.put("name" + "_s" + spectraCounter + "_p" + p_counter + "_d" + dCount + "_m" + modCounter, modificationName);
}
}
}
}
}
}
}
// Go to the group node inside the other group node (support)
if (idNodes.item(j).getNodeName().equalsIgnoreCase("group")) {
// Start parsing the support data part (GAML histograms)
if (idNodes.item(j).getAttributes().getNamedItem("label").getNodeValue().equalsIgnoreCase("supporting data")) {
supportDataNodes = idNodes.item(j).getChildNodes();
// Iterate over all the support data nodes
for (int a = 0; a < supportDataNodes.getLength(); a++) {
if (supportDataNodes.item(a).getNodeName().equalsIgnoreCase("GAML:trace")) {
// Parse the hyperscore expectation function values
if (supportDataNodes.item(a).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase(
"hyperscore expectation function")) {
iSupportDataMap.put("HYPERLABEL" + "_s" + spectraCounter,
supportDataNodes.item(a).getAttributes().getNamedItem("label").getNodeValue());
hyperNodes = supportDataNodes.item(a).getChildNodes();
// Iterate over the hyperscore nodes
for (int b = 0; b < hyperNodes.getLength(); b++) {
if (hyperNodes.item(b).getNodeName().equalsIgnoreCase("GAML:attribute")) {
// Get the a0 value
if (hyperNodes.item(b).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("a0")) {
iSupportDataMap.put("HYPER_A0" + "_s" + spectraCounter, hyperNodes.item(b).getTextContent());
}
// Get the a1 value
if (hyperNodes.item(b).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("a1")) {
iSupportDataMap.put("HYPER_A1" + "_s" + spectraCounter, hyperNodes.item(b).getTextContent());
}
}
// Get the Xdata
if (hyperNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Xdata")) {
xDataNodes = hyperNodes.item(b).getChildNodes();
for (int d = 0; d < xDataNodes.getLength(); d++) {
if (xDataNodes.item(d).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("XVAL_HYPER" + "_s" + spectraCounter, xDataNodes.item(d).getTextContent());
}
}
}
// Get the Ydata
if (hyperNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Ydata")) {
yDataNodes = hyperNodes.item(b).getChildNodes();
for (int e = 0; e < yDataNodes.getLength(); e++) {
if (yDataNodes.item(e).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("YVAL_HYPER" + "_s" + spectraCounter, yDataNodes.item(e).getTextContent());
}
}
}
}
}
// Parse the convolution survival funtion values
if (supportDataNodes.item(a).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase(
"convolution survival function")) {
iSupportDataMap.put("CONVOLLABEL" + "_s" + spectraCounter,
supportDataNodes.item(a).getAttributes().getNamedItem("label").getNodeValue());
supportDataNodes.item(a).getChildNodes();
convolNodes = supportDataNodes.item(a).getChildNodes();
// Iterate over the convolution nodes
for (int b = 0; b < convolNodes.getLength(); b++) {
// Get the Xdata
if (convolNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Xdata")) {
xDataNodes = convolNodes.item(b).getChildNodes();
for (int d = 0; d < xDataNodes.getLength(); d++) {
if (xDataNodes.item(d).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("XVAL_CONVOL" + "_s" + spectraCounter, xDataNodes.item(d).getTextContent());
}
}
}
// Get the Ydata
if (convolNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Ydata")) {
yDataNodes = convolNodes.item(b).getChildNodes();
for (int e = 0; e < yDataNodes.getLength(); e++) {
if (yDataNodes.item(e).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("YVAL_CONVOL" + "_s" + spectraCounter, yDataNodes.item(e).getTextContent());
}
}
}
}
}
// Parse the a ion histogram values
if (aIonFlag) {
if (supportDataNodes.item(a).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("a ion histogram")) {
iSupportDataMap.put("A_IONLABEL" + "_s" + spectraCounter,
supportDataNodes.item(a).getAttributes().getNamedItem("label").getNodeValue());
supportDataNodes.item(a).getChildNodes();
aIonNodes = supportDataNodes.item(a).getChildNodes();
// Iterate over the a ion nodes
for (int b = 0; b < aIonNodes.getLength(); b++) {
// Get the Xdata
if (aIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Xdata")) {
xDataNodes = aIonNodes.item(b).getChildNodes();
for (int d = 0; d < xDataNodes.getLength(); d++) {
if (xDataNodes.item(d).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("XVAL_AIONS" + "_s" + spectraCounter, xDataNodes.item(d).getTextContent());
}
}
}
// Get the Ydata
if (aIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Ydata")) {
yDataNodes = aIonNodes.item(b).getChildNodes();
for (int e = 0; e < yDataNodes.getLength(); e++) {
if (yDataNodes.item(e).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("YVAL_AIONS" + "_s"
+ spectraCounter, yDataNodes.item(e).getTextContent());
}
}
}
}
}
}
// Parse the b ion histogram values
if (bIonFlag) {
if (supportDataNodes.item(a).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("b ion histogram")) {
iSupportDataMap.put("B_IONLABEL" + "_s" + spectraCounter,
supportDataNodes.item(a).getAttributes().getNamedItem("label").getNodeValue());
supportDataNodes.item(a).getChildNodes();
bIonNodes = supportDataNodes.item(a).getChildNodes();
// Iterate over the b ion nodes
for (int b = 0; b < bIonNodes.getLength(); b++) {
// Get the Xdata
if (bIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Xdata")) {
xDataNodes = bIonNodes.item(b).getChildNodes();
for (int d = 0; d < xDataNodes.getLength(); d++) {
if (xDataNodes.item(d).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("XVAL_BIONS" + "_s"
+ spectraCounter, xDataNodes.item(d).getTextContent());
}
}
}
// Get the Ydata
if (bIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Ydata")) {
yDataNodes = bIonNodes.item(b).getChildNodes();
for (int e = 0; e < yDataNodes.getLength(); e++) {
if (yDataNodes.item(e).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("YVAL_BIONS" + "_s"
+ spectraCounter, yDataNodes.item(e).getTextContent());
}
}
}
}
}
}
// Parse the c ion histogram values
if (cIonFlag) {
if (supportDataNodes.item(a).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("c ion histogram")) {
iSupportDataMap.put("C_IONLABEL" + "_s" + spectraCounter,
supportDataNodes.item(a).getAttributes().getNamedItem("label").getNodeValue());
supportDataNodes.item(a).getChildNodes();
cIonNodes = supportDataNodes.item(a).getChildNodes();
// Iterate over the a ion nodes
for (int b = 0; b < cIonNodes.getLength(); b++) {
// Get the Xdata
if (cIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Xdata")) {
xDataNodes = cIonNodes.item(b).getChildNodes();
for (int d = 0; d < xDataNodes.getLength(); d++) {
if (xDataNodes.item(d).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("XVAL_CIONS" + "_s"
+ spectraCounter, xDataNodes.item(d).getTextContent());
}
}
}
// Get the Ydata
if (cIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Ydata")) {
yDataNodes = cIonNodes.item(b).getChildNodes();
for (int e = 0; e < yDataNodes.getLength(); e++) {
if (yDataNodes.item(e).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("YVAL_CIONS" + "_s"
+ spectraCounter, yDataNodes.item(e).getTextContent());
}
}
}
}
}
}
if (xIonFlag) {
// Parse the x ion histogram values
if (supportDataNodes.item(a).getAttributes().getNamedItem("type").getNodeValue().equals("x ion histogram")) {
iSupportDataMap.put("X_IONLABEL" + "_s" + spectraCounter,
supportDataNodes.item(a).getAttributes().getNamedItem("label").getNodeValue());
supportDataNodes.item(a).getChildNodes();
xIonNodes = supportDataNodes.item(a).getChildNodes();
// Iterate over the y ion nodes
for (int b = 0; b < xIonNodes.getLength(); b++) {
// Get the Xdata
if (xIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Xdata")) {
xDataNodes = xIonNodes.item(b).getChildNodes();
for (int d = 0; d < xDataNodes.getLength(); d++) {
if (xDataNodes.item(d).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("XVAL_XIONS" + "_s"
+ spectraCounter, xDataNodes.item(d).getTextContent());
}
}
}
// Get the Ydata
if (xIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Ydata")) {
yDataNodes = xIonNodes.item(b).getChildNodes();
for (int e = 0; e < yDataNodes.getLength(); e++) {
if (yDataNodes.item(e).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("YVAL_XIONS" + "_s"
+ spectraCounter, yDataNodes.item(e).getTextContent());
}
}
}
}
}
}
if (yIonFlag) {
// Parse the y ion histogram values
if (supportDataNodes.item(a).getAttributes().getNamedItem("type").getNodeValue().equals("y ion histogram")) {
iSupportDataMap.put("Y_IONLABEL" + "_s" + spectraCounter,
supportDataNodes.item(a).getAttributes().getNamedItem("label").getNodeValue());
supportDataNodes.item(a).getChildNodes();
yIonNodes = supportDataNodes.item(a).getChildNodes();
// Iterate over the y ion nodes
for (int b = 0; b < yIonNodes.getLength(); b++) {
// Get the Xdata
if (yIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Xdata")) {
xDataNodes = yIonNodes.item(b).getChildNodes();
for (int d = 0; d < xDataNodes.getLength(); d++) {
if (xDataNodes.item(d).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("XVAL_YIONS" + "_s"
+ spectraCounter, xDataNodes.item(d).getTextContent());
}
}
}
// Get the Ydata
if (yIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Ydata")) {
yDataNodes = yIonNodes.item(b).getChildNodes();
for (int e = 0; e < yDataNodes.getLength(); e++) {
if (yDataNodes.item(e).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("YVAL_YIONS" + "_s"
+ spectraCounter, yDataNodes.item(e).getTextContent());
}
}
}
}
}
}
if (zIonFlag) {
// Parse the x ion histogram values
if (supportDataNodes.item(a).getAttributes().getNamedItem("type").getNodeValue().equals("z ion histogram")) {
iSupportDataMap.put("Z_IONLABEL" + "_s" + spectraCounter,
supportDataNodes.item(a).getAttributes().getNamedItem("label").getNodeValue());
supportDataNodes.item(a).getChildNodes();
zIonNodes = supportDataNodes.item(a).getChildNodes();
// Iterate over the y ion nodes
for (int b = 0; b < zIonNodes.getLength(); b++) {
// Get the Xdata
if (zIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Xdata")) {
xDataNodes = zIonNodes.item(b).getChildNodes();
for (int d = 0; d < xDataNodes.getLength(); d++) {
if (xDataNodes.item(d).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("XVAL_ZIONS" + "_s"
+ spectraCounter, xDataNodes.item(d).getTextContent());
}
}
}
// Get the Ydata
if (zIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Ydata")) {
yDataNodes = zIonNodes.item(b).getChildNodes();
for (int e = 0; e < yDataNodes.getLength(); e++) {
if (yDataNodes.item(e).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("YVAL_ZIONS" + "_s"
+ spectraCounter, yDataNodes.item(e).getTextContent());
}
}
}
}
}
}
}
}
}
if (idNodes.item(j).getAttributes().getNamedItem("label").getNodeValue().equalsIgnoreCase("fragment ion mass spectrum")) {
supportDataNodes = idNodes.item(j).getChildNodes();
// Iterate over all the support data nodes
for (int a = 0; a < supportDataNodes.getLength(); a++) {
if (supportDataNodes.item(a).getNodeName().equalsIgnoreCase("note")) {
iSupportDataMap.put("FRAGIONSPECDESC" + "_s" + spectraCounter, supportDataNodes.item(a).getTextContent().trim());
iTitle2SpectrumIDMap.put(supportDataNodes.item(a).getTextContent().trim(), spectraCounter);
}
if (supportDataNodes.item(a).getNodeName().equalsIgnoreCase("GAML:trace")) {
// Parse the tandem mass spectrum values
if (supportDataNodes.item(a).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("tandem mass spectrum")) {
iSupportDataMap.put("SPECTRUMLABEL" + "_s" + spectraCounter,
supportDataNodes.item(a).getAttributes().getNamedItem("label").getNodeValue());
supportDataNodes.item(a).getChildNodes();
fragIonNodes = supportDataNodes.item(a).getChildNodes();
// Iterate over the fragment ion nodes
for (int b = 0; b < fragIonNodes.getLength(); b++) {
if (fragIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:attribute")) {
// Get the a0 value
if (fragIonNodes.item(b).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("M+H")) {
iSupportDataMap.put("FRAGIONMZ" + "_s"
+ spectraCounter, fragIonNodes.item(b).getTextContent());
}
// Get the a1 value
if (fragIonNodes.item(b).getAttributes().getNamedItem("type").getNodeValue().equalsIgnoreCase("charge")) {
iSupportDataMap.put("FRAGIONCHARGE" + "_s"
+ spectraCounter, fragIonNodes.item(b).getTextContent());
}
}
// Get the Xdata
if (fragIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Xdata")) {
xDataNodes = fragIonNodes.item(b).getChildNodes();
for (int d = 0; d < xDataNodes.getLength(); d++) {
if (xDataNodes.item(d).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("XVAL_FRAGIONMZ" + "_s"
+ spectraCounter, xDataNodes.item(d).getTextContent());
}
}
}
// Get the Ydata
if (fragIonNodes.item(b).getNodeName().equalsIgnoreCase("GAML:Ydata")) {
yDataNodes = fragIonNodes.item(b).getChildNodes();
for (int e = 0; e < yDataNodes.getLength(); e++) {
if (yDataNodes.item(e).getNodeName().equalsIgnoreCase("GAML:values")) {
iSupportDataMap.put("YVAL_FRAGIONMZ" + "_s"
+ spectraCounter, yDataNodes.item(e).getTextContent());
}
}
}
}
}
}
}
}
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
/**
* Returns the total number of spectra.
*
* @return iNumberOfSpectra
*/
public int getNumberOfSpectra() {
return iNumberOfSpectra;
}
/**
* Returns the raw spectrum map.
*
* @return iRawSpectrumMap
*/
public HashMap<String, String> getRawSpectrumMap() {
return iRawSpectrumMap;
}
/**
* Returns the raw peptide map.
*
* @return iRawPeptideMap
*/
public HashMap<String, String> getRawPeptideMap() {
return iRawPeptideMap;
}
/**
* Returns the raw protein map.
*
* @return iRawProteinMap
*/
public HashMap<String, String> getRawProteinMap() {
return iRawProteinMap;
}
/**
* Returns the protein id list
*
* @return iProteinIDList ArrayList<String>
*/
public ArrayList<String> getProteinIDList() {
return iProteinIDList;
}
/**
* Returns the raw modification map.
*
* @return iRawModMap
*/
public HashMap<String, String> getRawModMap() {
return iRawModMap;
}
/**
* Returns the performance parameters map.
*
* @return iPerformParamMap
*/
public HashMap<String, String> getPerformParamMap() {
return iPerformParamMap;
}
/**
* Returns the input parameter map.
*
* @return iInputParamMap
*/
public HashMap<String, String> getInputParamMap() {
return iInputParamMap;
}
/**
* Returns the support data map
*
* @return iSupportDataMap
*/
public HashMap<String, String> getSupportDataMap() {
return iSupportDataMap;
}
/**
* Returns the title2spectrum id map.
*
* @return iTitle2SpectrumIDMap.
*/
public HashMap<String, Integer> getTitle2SpectrumIDMap() {
return iTitle2SpectrumIDMap;
}
}
|
package edu.wustl.catissuecore.bizlogic;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import edu.wustl.catissuecore.dao.DAO;
import edu.wustl.catissuecore.domain.AbstractDomainObject;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.security.SecurityManager;
import edu.wustl.common.security.exceptions.SMException;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.logger.Logger;
/**
* UserHDAO is used to add user information into the database using Hibernate.
* @author kapil_kaveeshwar
*/
public class CollectionProtocolRegistrationBizLogic extends DefaultBizLogic
{
/**
* Saves the user object in the database.
* @param obj The user object to be saved.
* @param session The session in which the object is saved.
* @throws DAOException
*/
protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration) obj;
// check for closed Collection Protocol
checkStatus(dao, collectionProtocolRegistration.getCollectionProtocol(), "Collection Protocol" );
// Check for closed Participant
checkStatus(dao, collectionProtocolRegistration.getParticipant(), "Participant" );
registerParticipantAndProtocol(dao,collectionProtocolRegistration, sessionDataBean);
dao.insert(collectionProtocolRegistration, sessionDataBean, true, true);
try
{
SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null,getProtectionObjects(collectionProtocolRegistration),getDynamicGroups(collectionProtocolRegistration));
}
catch (SMException e)
{
Logger.out.error("Exception in Authorization: "+e.getMessage(),e);
}
}
/**
* Updates the persistent object in the database.
* @param obj The object to be updated.
* @param session The session in which the object is saved.
* @throws DAOException
*/
protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration) obj;
CollectionProtocolRegistration oldCollectionProtocolRegistration = (CollectionProtocolRegistration) oldObj;
// Check for different Collection Protocol
if(!collectionProtocolRegistration.getCollectionProtocol().getSystemIdentifier().equals( oldCollectionProtocolRegistration.getCollectionProtocol().getSystemIdentifier()))
{
checkStatus(dao,collectionProtocolRegistration.getCollectionProtocol(), "Collection Protocol" );
}
// -- Check for different Participants and closed participant
// old and new values are not null
if(collectionProtocolRegistration.getParticipant() != null &&
oldCollectionProtocolRegistration.getParticipant() != null &&
collectionProtocolRegistration.getParticipant().getSystemIdentifier() != null &&
oldCollectionProtocolRegistration.getParticipant().getSystemIdentifier() != null)
{
if(!collectionProtocolRegistration.getParticipant().getSystemIdentifier().equals( oldCollectionProtocolRegistration.getParticipant().getSystemIdentifier()))
{
checkStatus(dao,collectionProtocolRegistration.getParticipant(), "Participant" );
}
}
//when old participant is null and new is not null
if(collectionProtocolRegistration.getParticipant() != null && oldCollectionProtocolRegistration.getParticipant() == null)
{
if(collectionProtocolRegistration.getParticipant().getSystemIdentifier() != null )
{
checkStatus(dao, collectionProtocolRegistration.getParticipant(), "Participant" );
}
}
//Update registration
dao.update(collectionProtocolRegistration, sessionDataBean, true, true, false);
//Audit.
dao.audit(obj, oldObj, sessionDataBean, true);
//Disable all specimen Collection group under this registration.
Logger.out.debug("collectionProtocolRegistration.getActivityStatus() "+collectionProtocolRegistration.getActivityStatus());
if(collectionProtocolRegistration.getActivityStatus().equals(Constants.ACTIVITY_STATUS_DISABLED))
{
Logger.out.debug("collectionProtocolRegistration.getActivityStatus() "+collectionProtocolRegistration.getActivityStatus());
Long collectionProtocolRegistrationIDArr[] = {collectionProtocolRegistration.getSystemIdentifier()};
SpecimenCollectionGroupBizLogic bizLogic = (SpecimenCollectionGroupBizLogic)BizLogicFactory.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
bizLogic.disableRelatedObjects(dao,collectionProtocolRegistrationIDArr);
}
}
public Set getProtectionObjects(AbstractDomainObject obj)
{
Set protectionObjects = new HashSet();
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration) obj;
protectionObjects.add(collectionProtocolRegistration);
Participant participant = null;
//Case of registering Participant on its participant ID
if(collectionProtocolRegistration.getParticipant()!=null)
{
protectionObjects.add(collectionProtocolRegistration.getParticipant());
}
Logger.out.debug(protectionObjects.toString());
return protectionObjects;
}
public String[] getDynamicGroups(AbstractDomainObject obj)
{
String[] dynamicGroups=null;
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration) obj;
dynamicGroups = new String[1];
dynamicGroups[0] = Constants.getCollectionProtocolPGName(collectionProtocolRegistration.getCollectionProtocol().getSystemIdentifier());
return dynamicGroups;
}
private void registerParticipantAndProtocol(DAO dao, CollectionProtocolRegistration collectionProtocolRegistration, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
//Case of registering Participant on its participant ID
Participant participant = null;
if(collectionProtocolRegistration.getParticipant()!=null)
{
Object participantObj = dao.retrieve(Participant.class.getName(), collectionProtocolRegistration.getParticipant().getSystemIdentifier());
if (participantObj != null )
{
participant = (Participant)participantObj;
}
}
else
{
participant = new Participant();
participant.setLastName("");
participant.setFirstName("");
participant.setMiddleName("");
participant.setSocialSecurityNumber(null);
participant.setActivityStatus(Constants.ACTIVITY_STATUS_ACTIVE);
dao.insert(participant, sessionDataBean, true, true);
}
collectionProtocolRegistration.setParticipant(participant);
Object collectionProtocolObj = dao.retrieve(CollectionProtocol.class.getName(), collectionProtocolRegistration.getCollectionProtocol().getSystemIdentifier());
if (collectionProtocolObj != null)
{
CollectionProtocol collectionProtocol = (CollectionProtocol)collectionProtocolObj;
collectionProtocolRegistration.setCollectionProtocol(collectionProtocol);
}
}
/**
* Disable all the related collection protocol regitration for a given array of participant ids.
**/
public void disableRelatedObjectsForParticipant(DAO dao, Long participantIDArr[])throws DAOException
{
List listOfSubElement = super.disableObjects(dao, CollectionProtocolRegistration.class, "participant",
"CATISSUE_COLLECTION_PROTOCOL_REGISTRATION", "PARTICIPANT_ID", participantIDArr);
if(!listOfSubElement.isEmpty())
{
SpecimenCollectionGroupBizLogic bizLogic = (SpecimenCollectionGroupBizLogic)BizLogicFactory.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
bizLogic.disableRelatedObjects(dao,Utility.toLongArray(listOfSubElement));
}
}
/**
* Disable all the related collection protocol regitrations for a given array of collection protocol ids.
**/
public void disableRelatedObjectsForCollectionProtocol(DAO dao, Long collectionProtocolIDArr[])throws DAOException
{
List listOfSubElement = super.disableObjects(dao, CollectionProtocolRegistration.class, "collectionProtocol",
"CATISSUE_COLLECTION_PROTOCOL_REGISTRATION", "COLLECTION_PROTOCOL_ID", collectionProtocolIDArr);
if(!listOfSubElement.isEmpty())
{
SpecimenCollectionGroupBizLogic bizLogic = (SpecimenCollectionGroupBizLogic)BizLogicFactory.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
bizLogic.disableRelatedObjects(dao,Utility.toLongArray(listOfSubElement));
}
}
/**
* @param dao
* @param objectIds
* @param assignToUser
* @param roleId
* @throws DAOException
* @throws SMException
*/
public void assignPrivilegeToRelatedObjectsForParticipant(DAO dao, String privilegeName, Long[] objectIds, Long userId, String roleId, boolean assignToUser) throws SMException, DAOException
{
List listOfSubElement = super.getRelatedObjects(dao, CollectionProtocolRegistration.class, "participant",
objectIds);
if(!listOfSubElement.isEmpty())
{
super.setPrivilege(dao,privilegeName,CollectionProtocolRegistration.class,Utility.toLongArray(listOfSubElement),userId, roleId, assignToUser);
SpecimenCollectionGroupBizLogic bizLogic = (SpecimenCollectionGroupBizLogic)BizLogicFactory.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
bizLogic.assignPrivilegeToRelatedObjects(dao,privilegeName,Utility.toLongArray(listOfSubElement),userId, roleId, assignToUser);
}
}
/**
* @see AbstractBizLogic#setPrivilege(DAO, String, Class, Long[], Long, String, boolean)
* @param dao
* @param privilegeName
* @param objectIds
* @param userId
* @param roleId
* @param assignToUser
* @throws SMException
* @throws DAOException
*/
public void assignPrivilegeToRelatedObjectsForCP(DAO dao, String privilegeName, Long[] objectIds, Long userId, String roleId, boolean assignToUser)throws SMException, DAOException
{
List listOfSubElement = super.getRelatedObjects(dao, CollectionProtocolRegistration.class, "collectionProtocol",objectIds);
if(!listOfSubElement.isEmpty())
{
super.setPrivilege(dao,privilegeName,CollectionProtocolRegistration.class,Utility.toLongArray(listOfSubElement),userId,roleId, assignToUser);
SpecimenCollectionGroupBizLogic bizLogic = (SpecimenCollectionGroupBizLogic)BizLogicFactory.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
bizLogic.assignPrivilegeToRelatedObjects(dao,privilegeName,Utility.toLongArray(listOfSubElement),userId, roleId, assignToUser);
ParticipantBizLogic participantBizLogic = (ParticipantBizLogic)BizLogicFactory.getBizLogic(Constants.PARTICIPANT_FORM_ID);
participantBizLogic.assignPrivilegeToRelatedObjectsForCPR(dao,privilegeName,Utility.toLongArray(listOfSubElement),userId, roleId, assignToUser);
}
}
/**
* @see AbstractBizLogic#setPrivilege(DAO, String, Class, Long[], Long, String, boolean)
*/
public void setPrivilege(DAO dao, String privilegeName, Class objectType, Long[] objectIds, Long userId, String roleId, boolean assignToUser) throws SMException, DAOException
{
super.setPrivilege(dao,privilegeName,objectType,objectIds,userId, roleId, assignToUser);
SpecimenCollectionGroupBizLogic bizLogic = (SpecimenCollectionGroupBizLogic)BizLogicFactory.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
bizLogic.assignPrivilegeToRelatedObjects(dao,privilegeName,objectIds,userId, roleId, assignToUser);
ParticipantBizLogic participantBizLogic = (ParticipantBizLogic)BizLogicFactory.getBizLogic(Constants.PARTICIPANT_FORM_ID);
participantBizLogic.assignPrivilegeToRelatedObjectsForCPR(dao,privilegeName,objectIds,userId, roleId, assignToUser);
}
}
|
package dr.app.tracer.traces;
import dr.gui.chart.*;
import org.virion.jam.framework.Exportable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* A panel that displays information about traces
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: RawTracePanel.java,v 1.2 2006/11/30 17:39:29 rambaut Exp $
*/
public class RawTracePanel extends JPanel implements Exportable {
public static int COLOUR_BY_TRACE = 0;
public static int COLOUR_BY_FILE = 1;
public static int COLOUR_BY_ALL = 2;
private static final Paint[] paints = new Paint[] {
Color.BLACK,
new Color(64,35,225),
new Color(229,35,60),
new Color(255,174,34),
new Color(86,255,34),
new Color(35,141,148),
new Color(146,35,142),
new Color(255,90,34),
new Color(239,255,34),
Color.DARK_GRAY
};
private ChartSetupDialog chartSetupDialog = null;
private JTraceChart traceChart = new JTraceChart(
new LinearAxis(Axis.AT_ZERO, Axis.AT_DATA),
new LinearAxis());
private JChartPanel chartPanel = new JChartPanel(traceChart, null, "", "");
private JCheckBox sampleCheckBox = new JCheckBox("Sample only");
private JCheckBox linePlotCheckBox = new JCheckBox("Draw line plot");
private JComboBox legendCombo = new JComboBox(
new String[] { "None", "Top-Left", "Top", "Top-Right", "Left",
"Right", "Bottom-Left", "Bottom", "Bottom-Right" }
);
private JComboBox colourByCombo = new JComboBox(
new String[] { "Trace", "Trace File", "All" }
);
private JLabel messageLabel = new JLabel("No data loaded");
private int colourBy = COLOUR_BY_TRACE;
private boolean sampleOnly = true;
/** Creates new RawTracePanel */
public RawTracePanel(final JFrame frame) {
setOpaque(false);
setMinimumSize(new Dimension(300,150));
setLayout(new BorderLayout());
JToolBar toolBar = new JToolBar();
toolBar.setOpaque(false);
toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
toolBar.setFloatable(false);
JButton chartSetupButton = new JButton("Axes...");
chartSetupButton.putClientProperty(
"Quaqua.Button.style", "placard"
);
chartSetupButton.setFont(UIManager.getFont("SmallSystemFont"));
toolBar.add(chartSetupButton);
sampleCheckBox.setSelected(true);
sampleCheckBox.setFont(UIManager.getFont("SmallSystemFont"));
sampleCheckBox.setOpaque(false);
toolBar.add(sampleCheckBox);
toolBar.add(new JToolBar.Separator(new Dimension(8,8)));
linePlotCheckBox.setSelected(true);
linePlotCheckBox.setFont(UIManager.getFont("SmallSystemFont"));
linePlotCheckBox.setOpaque(false);
toolBar.add(linePlotCheckBox);
toolBar.add(new JToolBar.Separator(new Dimension(8,8)));
JLabel label = new JLabel("Legend:");
label.setFont(UIManager.getFont("SmallSystemFont"));
label.setLabelFor(legendCombo);
toolBar.add(label);
legendCombo.setFont(UIManager.getFont("SmallSystemFont"));
legendCombo.setOpaque(false);
toolBar.add(legendCombo);
toolBar.add(new JToolBar.Separator(new Dimension(8,8)));
label = new JLabel("Colour by:");
label.setFont(UIManager.getFont("SmallSystemFont"));
label.setLabelFor(colourByCombo);
toolBar.add(label);
colourByCombo.setFont(UIManager.getFont("SmallSystemFont"));
colourByCombo.setOpaque(false);
toolBar.add(colourByCombo);
toolBar.add(new JToolBar.Separator(new Dimension(8,8)));
add(messageLabel, BorderLayout.NORTH);
add(toolBar, BorderLayout.SOUTH);
add(chartPanel, BorderLayout.CENTER);
chartSetupButton.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if (chartSetupDialog == null) {
chartSetupDialog = new ChartSetupDialog(frame, false, true,
Axis.AT_ZERO, Axis.AT_MAJOR_TICK,
Axis.AT_MAJOR_TICK, Axis.AT_MAJOR_TICK);
}
chartSetupDialog.showDialog(traceChart);
validate();
repaint();
}
}
);
sampleCheckBox.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent ev) {
traceChart.setUseSample(sampleCheckBox.isSelected());
validate();
repaint();
}
}
);
linePlotCheckBox.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent ev) {
traceChart.setIsLinePlot(linePlotCheckBox.isSelected());
validate();
repaint();
}
}
);
legendCombo.addItemListener(
new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent ev) {
switch (legendCombo.getSelectedIndex()) {
case 0: break;
case 1: traceChart.setLegendAlignment(SwingConstants.NORTH_WEST); break;
case 2: traceChart.setLegendAlignment(SwingConstants.NORTH); break;
case 3: traceChart.setLegendAlignment(SwingConstants.NORTH_EAST); break;
case 4: traceChart.setLegendAlignment(SwingConstants.WEST); break;
case 5: traceChart.setLegendAlignment(SwingConstants.EAST); break;
case 6: traceChart.setLegendAlignment(SwingConstants.SOUTH_WEST); break;
case 7: traceChart.setLegendAlignment(SwingConstants.SOUTH); break;
case 8: traceChart.setLegendAlignment(SwingConstants.SOUTH_EAST); break;
}
traceChart.setShowLegend(legendCombo.getSelectedIndex() != 0);
validate();
repaint();
}
}
);
colourByCombo.addItemListener(
new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent ev) {
colourBy = colourByCombo.getSelectedIndex();
setupTraces(traceLists, traceIndices);
validate();
repaint();
}
}
);
}
private TraceList[] traceLists = null;
private int[] traceIndices = null;
public void setTraces(TraceList[] traceLists, int[] traceIndices) {
this.traceLists = traceLists;
this.traceIndices = traceIndices;
setupTraces(traceLists, traceIndices);
}
private void setupTraces(TraceList[] traceLists, int[] traceIndices) {
traceChart.removeAllTraces();
if (traceLists == null || traceIndices == null || traceIndices.length == 0) {
chartPanel.setXAxisTitle("");
chartPanel.setYAxisTitle("");
messageLabel.setText("No traces selected");
add(messageLabel, BorderLayout.NORTH);
return;
}
remove(messageLabel);
int i = 0;
for (TraceList tl : traceLists) {
int n = tl.getStateCount();
int stateStart = tl.getBurnIn();
int stateStep = tl.getStepSize();
for (int j = 0; j < traceIndices.length; j++) {
double values[] = new double[n];
tl.getValues(traceIndices[j], values);
String name = tl.getTraceName(traceIndices[j]);
if (traceLists.length > 1) {
name = tl.getName() + " - " + name;
}
traceChart.addTrace(name, stateStart, stateStep, values, paints[i]);
if (colourBy == COLOUR_BY_TRACE || colourBy == COLOUR_BY_ALL) {
i++;
}
if (i == paints.length) i = 0;
}
if (colourBy == COLOUR_BY_FILE) {
i++;
} else if (colourBy == COLOUR_BY_TRACE) {
i = 0;
}
if (i == paints.length) i = 0;
}
chartPanel.setXAxisTitle("State");
if (traceLists.length == 1) {
chartPanel.setYAxisTitle(traceLists[0].getName());
} else if (traceIndices.length == 1) {
chartPanel.setYAxisTitle(traceLists[0].getTraceName(traceIndices[0]));
} else {
chartPanel.setYAxisTitle("Multiple Traces");
}
validate();
repaint();
}
public JComponent getExportableComponent() {
return chartPanel;
}
public void copyToClipboard() {
java.awt.datatransfer.Clipboard clipboard =
Toolkit.getDefaultToolkit().getSystemClipboard();
java.awt.datatransfer.StringSelection selection =
new java.awt.datatransfer.StringSelection(this.toString());
clipboard.setContents(selection, selection);
}
public String toString() {
return "";
}
}
|
package fr.esiea.windmeal.model;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
public class Menu extends Model {
@Valid
private List<Meal> meals = new ArrayList<Meal>();
public Menu() {
generateId();
}
public List<Meal> getMeals() {
return meals;
}
public void setMeals(List<Meal> meals) {
this.meals = meals;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Menu)) return false;
Menu menu = (Menu) o;
if (meals != null ? !meals.equals(menu.meals) : menu.meals != null) return false;
return true;
}
@Override
public int hashCode() {
return meals != null ? meals.hashCode() : 0;
}
}
|
package com.canoo.dp.impl.server.event;
import com.canoo.platform.remoting.server.event.Topic;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.version.Version;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.Serializable;
import java.nio.ByteOrder;
import java.time.LocalDateTime;
import java.util.Iterator;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.CONTEXT_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.DATA_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.METADATA_KEY_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.METADATA_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.METADATA_VALUE_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.SPEC_1_0;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.SPEC_VERSION_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.TIMESTAMP_PARAM;
import static com.canoo.dp.impl.server.event.DistributedEventConstants.TOPIC_PARAM;
public class EventStreamSerializerTests {
@Test
public void testSimpleEventToJson() throws IOException, ClassNotFoundException {
//given
final Topic<String> topic = Topic.create("test-topic");
final long timestamp = System.currentTimeMillis();
final String data = "test-data";
final DolphinEvent<String> dolphinEvent = new DolphinEvent<>(topic, timestamp, data);
//when
final JsonElement root = convertToJson(dolphinEvent);
//then
checkJsonSchema(root);
Assert.assertEquals(Base64Utils.fromBase64(root.getAsJsonObject().getAsJsonPrimitive(DATA_PARAM).getAsString()), data);
final JsonObject context = root.getAsJsonObject().get(CONTEXT_PARAM).getAsJsonObject();
Assert.assertEquals(context.getAsJsonPrimitive(TIMESTAMP_PARAM).getAsNumber().longValue(), timestamp);
Assert.assertEquals(context.getAsJsonPrimitive(TOPIC_PARAM).getAsString(), topic.getName());
Assert.assertEquals(context.getAsJsonArray(METADATA_PARAM).size(), 0);
}
@Test
public void testEventWithNullDataToJson() throws IOException, ClassNotFoundException {
//given
final Topic<String> topic = Topic.create("test-topic");
final long timestamp = System.currentTimeMillis();
final String data = null;
final DolphinEvent<String> dolphinEvent = new DolphinEvent<>(topic, timestamp, data);
//when
final JsonElement root = convertToJson(dolphinEvent);
//then
checkJsonSchema(root);
Assert.assertTrue(root.getAsJsonObject().get(DATA_PARAM).isJsonNull());
}
@Test
public void testEventWithSerializedDataToJson() throws IOException, ClassNotFoundException {
//given
final Topic<LocalDateTime> topic = Topic.create("test-topic");
final long timestamp = System.currentTimeMillis();
final LocalDateTime data = LocalDateTime.now();
final DolphinEvent<LocalDateTime> dolphinEvent = new DolphinEvent<>(topic, timestamp, data);
//when
final JsonElement root = convertToJson(dolphinEvent);
//then
checkJsonSchema(root);
Assert.assertEquals(Base64Utils.fromBase64(root.getAsJsonObject().getAsJsonPrimitive(DATA_PARAM).getAsString()), data);
}
@Test
public void testEventWithMetadataToJson() throws IOException, ClassNotFoundException {
//given
final Topic<String> topic = Topic.create("test-topic");
final long timestamp = System.currentTimeMillis();
final String data = "test-data";
final DolphinEvent<String> dolphinEvent = new DolphinEvent<>(topic, timestamp, data);
final String key1 = "test-key-1";
final Serializable value1 = "test-value-1";
final String key2 = "test-key-2";
final Serializable value2 = null;
final String key3 = "test-key-3";
final Serializable value3 = LocalDateTime.now();
dolphinEvent.addMetadata(key1, value1);
dolphinEvent.addMetadata(key2, value2);
dolphinEvent.addMetadata(key3, value3);
//when
final JsonElement root = convertToJson(dolphinEvent);
//then
checkJsonSchema(root);
final JsonArray metadata = root.getAsJsonObject().getAsJsonObject(CONTEXT_PARAM).getAsJsonArray(METADATA_PARAM);
Assert.assertEquals(metadata.size(), 3);
Assert.assertEquals(getMetadataValueForKey(metadata, key1), value1);
Assert.assertEquals(getMetadataValueForKey(metadata, key2), value2);
Assert.assertEquals(getMetadataValueForKey(metadata, key3), value3);
}
@Test
public void testSimpleEventFromJson() throws IOException, ClassNotFoundException {
//given
final Topic<String> topic = Topic.create("test-topic");
final long timestamp = System.currentTimeMillis();
final String data = "test-data";
final JsonObject root = new JsonObject();
root.addProperty(SPEC_VERSION_PARAM, SPEC_1_0);
root.addProperty(DATA_PARAM, Base64Utils.toBase64(data));
final JsonObject context = new JsonObject();
context.addProperty(TIMESTAMP_PARAM, timestamp);
context.addProperty(TOPIC_PARAM, topic.getName());
context.add(METADATA_PARAM, new JsonArray());
root.add(CONTEXT_PARAM, context);
checkJsonSchema(root);
//when
final DolphinEvent<?> event = convertToEvent(root);
//then
Assert.assertNotNull(event);
Assert.assertEquals(event.getData(), data);
Assert.assertEquals(event.getMessageEventContext().getTimestamp(), timestamp);
Assert.assertEquals(event.getMessageEventContext().getTopic(), topic);
Assert.assertTrue(event.getMessageEventContext().getMetadata().isEmpty());
}
@Test
public void testEventWithNullDataFromJson() throws IOException, ClassNotFoundException {
//given
final Topic<String> topic = Topic.create("test-topic");
final long timestamp = System.currentTimeMillis();
final JsonObject root = new JsonObject();
root.addProperty(SPEC_VERSION_PARAM, SPEC_1_0);
root.add(DATA_PARAM, JsonNull.INSTANCE);
final JsonObject context = new JsonObject();
context.addProperty(TIMESTAMP_PARAM, timestamp);
context.addProperty(TOPIC_PARAM, topic.getName());
context.add(METADATA_PARAM, new JsonArray());
root.add(CONTEXT_PARAM, context);
checkJsonSchema(root);
//when
final DolphinEvent<?> event = convertToEvent(root);
//then
Assert.assertEquals(event.getData(), null);
}
private Serializable getMetadataValueForKey(final JsonArray metadataArray, final String key) throws IOException, ClassNotFoundException {
final Iterator<JsonElement> elementIterator = metadataArray.iterator();
while (elementIterator.hasNext()) {
final JsonObject metadata = elementIterator.next().getAsJsonObject();
if (metadata.getAsJsonPrimitive(METADATA_KEY_PARAM).getAsString().equals(key)) {
if (metadata.get(METADATA_VALUE_PARAM).isJsonNull()) {
return null;
} else {
return Base64Utils.fromBase64(metadata.getAsJsonPrimitive(METADATA_VALUE_PARAM).getAsString());
}
}
}
Assert.fail("metadata do not contain key '" + key + "'");
throw new IllegalStateException("metadata do not contain key '" + key + "'");
}
private <T extends Serializable> JsonElement convertToJson(DolphinEvent<T> event) throws IOException {
final EventStreamSerializer streamSerializer = new EventStreamSerializer();
final ObjectDataOutput output = new ByteObjectDataOutput();
streamSerializer.write(output, event);
final byte[] rawOutputData = output.toByteArray();
final String outputData = new String(rawOutputData);
return new JsonParser().parse(outputData);
}
private <T extends Serializable> DolphinEvent<T> convertToEvent(final JsonElement jsonElement) throws IOException {
final EventStreamSerializer streamSerializer = new EventStreamSerializer();
final ObjectDataInput input = new JsonBasedObjectDataInput(jsonElement);
return (DolphinEvent<T>) streamSerializer.read(input);
}
private void checkJsonSchema(final JsonElement root) {
Assert.assertNotNull(root);
Assert.assertTrue(root.isJsonObject());
Assert.assertTrue(root.getAsJsonObject().has(SPEC_VERSION_PARAM));
Assert.assertTrue(root.getAsJsonObject().get(SPEC_VERSION_PARAM).isJsonPrimitive());
Assert.assertTrue(root.getAsJsonObject().getAsJsonPrimitive(SPEC_VERSION_PARAM).isString());
Assert.assertEquals(root.getAsJsonObject().getAsJsonPrimitive(SPEC_VERSION_PARAM).getAsString(), SPEC_1_0);
Assert.assertTrue(root.getAsJsonObject().has(DATA_PARAM));
Assert.assertTrue(root.getAsJsonObject().get(DATA_PARAM).isJsonPrimitive() || root.getAsJsonObject().get(DATA_PARAM).isJsonNull());
if (root.getAsJsonObject().get(DATA_PARAM).isJsonPrimitive()) {
Assert.assertTrue(root.getAsJsonObject().getAsJsonPrimitive(DATA_PARAM).isString());
}
Assert.assertTrue(root.getAsJsonObject().has(CONTEXT_PARAM));
Assert.assertTrue(root.getAsJsonObject().get(CONTEXT_PARAM).isJsonObject());
final JsonObject context = root.getAsJsonObject().getAsJsonObject(CONTEXT_PARAM);
Assert.assertTrue(context.has(TIMESTAMP_PARAM));
Assert.assertTrue(context.get(TIMESTAMP_PARAM).isJsonPrimitive());
Assert.assertTrue(context.getAsJsonPrimitive(TIMESTAMP_PARAM).isNumber());
Assert.assertTrue(context.has(TOPIC_PARAM));
Assert.assertTrue(context.get(TOPIC_PARAM).isJsonPrimitive());
Assert.assertTrue(context.getAsJsonPrimitive(TOPIC_PARAM).isString());
Assert.assertTrue(context.has(METADATA_PARAM));
Assert.assertTrue(context.get(METADATA_PARAM).isJsonArray());
final JsonArray metadataArray = context.getAsJsonArray(METADATA_PARAM);
if (metadataArray.size() > 0) {
final Iterator<JsonElement> elementIterator = metadataArray.iterator();
while (elementIterator.hasNext()) {
final JsonElement metadataElem = elementIterator.next();
Assert.assertTrue(metadataElem.isJsonObject());
final JsonObject metadata = metadataElem.getAsJsonObject();
Assert.assertTrue(metadata.has(METADATA_KEY_PARAM));
Assert.assertTrue(metadata.get(METADATA_KEY_PARAM).isJsonPrimitive());
Assert.assertTrue(metadata.getAsJsonPrimitive(METADATA_KEY_PARAM).isString());
Assert.assertTrue(metadata.has(METADATA_VALUE_PARAM));
Assert.assertTrue(metadata.get(METADATA_VALUE_PARAM).isJsonPrimitive() ||
metadata.get(METADATA_VALUE_PARAM).isJsonNull());
if (metadata.get(METADATA_VALUE_PARAM).isJsonPrimitive()) {
Assert.assertTrue(metadata.getAsJsonPrimitive(METADATA_VALUE_PARAM).isString());
}
}
}
}
private class JsonBasedObjectDataInput implements ObjectDataInput {
private final JsonElement jsonElement;
public JsonBasedObjectDataInput(final JsonElement jsonElement) {
this.jsonElement = jsonElement;
}
@Override
public byte[] readByteArray() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public boolean[] readBooleanArray() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public char[] readCharArray() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public int[] readIntArray() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public long[] readLongArray() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public double[] readDoubleArray() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public float[] readFloatArray() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public short[] readShortArray() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public String[] readUTFArray() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public <T> T readObject() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public <T> T readDataAsObject() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public <T> T readObject(final Class aClass) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public Data readData() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public ClassLoader getClassLoader() {
throw new RuntimeException("Not needed for test");
}
@Override
public ByteOrder getByteOrder() {
throw new RuntimeException("Not needed for test");
}
@Override
public void readFully(byte[] b) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void readFully(byte[] b, int off, int len) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public int skipBytes(int n) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public boolean readBoolean() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public byte readByte() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public int readUnsignedByte() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public short readShort() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public int readUnsignedShort() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public char readChar() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public int readInt() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public long readLong() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public float readFloat() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public double readDouble() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public String readLine() throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public String readUTF() throws IOException {
return new GsonBuilder().serializeNulls().create().toJson(jsonElement);
}
@Override
public Version getVersion() {
return Version.UNKNOWN;
}
}
private class ByteObjectDataOutput implements ObjectDataOutput {
private final StringBuffer content = new StringBuffer();
@Override
public void writeByteArray(final byte[] bytes) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeBooleanArray(final boolean[] booleans) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeCharArray(final char[] chars) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeIntArray(final int[] ints) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeLongArray(final long[] longs) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeDoubleArray(final double[] values) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeFloatArray(final float[] values) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeShortArray(final short[] values) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeUTFArray(final String[] values) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeObject(final Object object) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeData(final Data data) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public byte[] toByteArray() {
return content.toString().getBytes();
}
@Override
public byte[] toByteArray(final int padding) {
return new byte[padding];
}
@Override
public ByteOrder getByteOrder() {
throw new RuntimeException("Not needed for test");
}
@Override
public void write(final int b) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void write(final byte[] b) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeBoolean(final boolean v) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeByte(final int v) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeShort(final int v) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeChar(final int v) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeInt(final int v) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeLong(final long v) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeFloat(final float v) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeDouble(final double v) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeBytes(final String s) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeChars(final String s) throws IOException {
throw new RuntimeException("Not needed for test");
}
@Override
public void writeUTF(final String s) throws IOException {
content.append(s);
}
@Override
public Version getVersion() {
return Version.UNKNOWN;
}
}
}
|
package dk.dbc.kafka.dispatch.sources;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
/**
* Source for reading InputStreams line-by-line
* @author Adam Tulinius
*/
public class InputStreamSource extends Source<String> {
private BufferedReader reader;
public InputStreamSource(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
}
@Override
public Optional next() throws IOException {
String line = reader.readLine();
if (line != null) {
return Optional.of(line);
} else {
return Optional.empty();
}
}
}
|
package com.gallatinsystems.survey.device.dao;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.gallatinsystems.survey.device.domain.FileTransmission;
import com.gallatinsystems.survey.device.domain.PointOfInterest;
import com.gallatinsystems.survey.device.domain.QuestionResponse;
import com.gallatinsystems.survey.device.domain.Survey;
import com.gallatinsystems.survey.device.util.ConstantUtil;
/**
* Database class for the survey db. It can create/upgrade the database as well
* as select/insert/update survey responses.
*
* TODO: break this up into separate DAOs
*
* @author Christopher Fagiani
*
*/
public class SurveyDbAdapter {
public static final String QUESTION_FK_COL = "question_id";
public static final String ANSWER_COL = "answer_value";
public static final String ANSWER_TYPE_COL = "answer_type";
public static final String SURVEY_RESPONDENT_ID_COL = "survey_respondent_id";
public static final String RESP_ID_COL = "survey_response_id";
public static final String SURVEY_FK_COL = "survey_id";
public static final String PK_ID_COL = "_id";
public static final String USER_FK_COL = "user_id";
public static final String DISP_NAME_COL = "display_name";
public static final String EMAIL_COL = "email";
public static final String SUBMITTED_FLAG_COL = "submitted_flag";
public static final String SUBMITTED_DATE_COL = "submitted_date";
public static final String DELIVERED_DATE_COL = "delivered_date";
public static final String CREATED_DATE_COL = "created_date";
public static final String UPDATED_DATE_COL = "updated_date";
public static final String PLOT_FK_COL = "plot_id";
public static final String LAT_COL = "lat";
public static final String LON_COL = "lon";
public static final String ELEVATION_COL = "elevation";
public static final String DESC_COL = "description";
public static final String STATUS_COL = "status";
public static final String VERSION_COL = "version";
public static final String TYPE_COL = "type";
public static final String LOCATION_COL = "location";
public static final String FILENAME_COL = "filename";
public static final String KEY_COL = "key";
public static final String VALUE_COL = "value";
public static final String DELETED_COL = "deleted_flag";
public static final String MEDIA_SENT_COL = "media_sent_flag";
public static final String HELP_DOWNLOADED_COL = "help_downloaded_flag";
public static final String LANGUAGE_COL = "language";
public static final String SAVED_DATE_COL = "saved_date";
public static final String COUNTRY_COL = "country";
public static final String PROP_NAME_COL = "property_names";
public static final String PROP_VAL_COL = "property_values";
public static final String INCLUDE_FLAG_COL = "include_flag";
public static final String SCORED_VAL_COL = "scored_val";
public static final String STRENGTH_COL = "strength";
public static final String TRANS_START_COL = "trans_start_date";
public static final String EXPORTED_FLAG_COL = "exported_flag";
public static final String UUID_COL = "uuid";
private static final String TAG = "SurveyDbAdapter";
private DatabaseHelper databaseHelper;
private SQLiteDatabase database;
/**
* Database creation sql statement
*/
private static final String SURVEY_TABLE_CREATE = "create table survey (_id integer primary key, "
+ "display_name text not null, version real, type text, location text, filename text, language, help_downloaded_flag text, deleted_flag text);";
private static final String SURVEY_RESPONDENT_CREATE = "create table survey_respondent (_id integer primary key autoincrement, "
+ "survey_id integer not null, submitted_flag text, submitted_date text,delivered_date text, user_id integer, media_sent_flag text, status text, saved_date long, exported_flag text, uuid text);";
private static final String SURVEY_RESPONSE_CREATE = "create table survey_response (survey_response_id integer primary key autoincrement, "
+ " survey_respondent_id integer not null, question_id text not null, answer_value text not null, answer_type text not null, include_flag text not null, scored_val text, strength text);";
private static final String USER_TABLE_CREATE = "create table user (_id integer primary key autoincrement, display_name text not null, email text not null);";
private static final String PLOT_TABLE_CREATE = "create table plot (_id integer primary key autoincrement, display_name text, description text, created_date text, user_id integer, status text);";
private static final String PLOT_POINT_TABLE_CREATE = "create table plot_point (_id integer primary key autoincrement, plot_id integer not null, lat text, lon text, elevation text, created_date text);";
private static final String PREFERENCES_TABLE_CREATE = "create table preferences (key text primary key, value text);";
private static final String POINT_OF_INTEREST_TABLE_CREATE = "create table point_of_interest (_id integer primary key, country text, display_name text, lat real, lon real, property_names text, property_values text, type text, updated_date integer);";
private static final String TRANSMISSION_HISTORY_TABLE_CREATE = "create table transmission_history (_id integer primary key, survey_respondent_id integer not null, status text, filename text, trans_start_date long, delivered_date long);";
private static final String[] DEFAULT_INSERTS = new String[] {
// "insert into survey values(999991,'Sample Survey', 1.0,'Survey','res','testsurvey','english','N','N')",
// "insert into survey values(1039101,'Houshold Interview', 1.0,'Survey','res','hh1039101','english','N','N')",
// "insert into survey values(1062135,'Public Institution', 1.0,'Survey','res','pi1062135','english','N','N')",
// "insert into survey values(1086117,'CommunityWaterPoint', 1.0,'Survey','res','cwp1086117','english','N','N')",
// "insert into survey values(943186,'Community Water Point', 1.0,'Survey','res','cw943186','english','N','N')",
// "insert into survey values(1007024,'Household Interview', 1.0,'Survey','res','hh1007024','english','N','N')",
// "insert into survey values(971189,'Public Institution', 1.0,'Survey','res','pi971189','english','N','N')",
"insert into preferences values('survey.language','0')",
"insert into preferences values('user.storelast','false')",
"insert into preferences values('data.cellular.upload','0')",
"insert into preferences values('plot.default.mode','manual')",
"insert into preferences values('plot.interval','60000')",
"insert into preferences values('user.lastuser.id','')",
"insert into preferences values('location.sendbeacon','true')",
"insert into preferences values('survey.precachehelp','1')",
"insert into preferences values('upload.server','0')",
"insert into preferences values('screen.keepon','true')",
"insert into preferences values('precache.points.countries','2')",
"insert into preferences values('precache.points.limit','200')",
"insert into preferences values('survey.textsize','LARGE')" };
private static final String DATABASE_NAME = "surveydata";
private static final String SURVEY_TABLE = "survey";
private static final String RESPONDENT_TABLE = "survey_respondent";
private static final String RESPONSE_TABLE = "survey_response";
private static final String USER_TABLE = "user";
private static final String PLOT_TABLE = "plot";
private static final String PLOT_POINT_TABLE = "plot_point";
private static final String PREFERENCES_TABLE = "preferences";
private static final String POINT_OF_INTEREST_TABLE = "point_of_interest";
private static final String TRANSMISSION_HISTORY_TABLE = "transmission_history";
private static final String RESPONSE_JOIN = "survey_respondent LEFT OUTER JOIN survey_response ON (survey_respondent._id = survey_response.survey_respondent_id) LEFT OUTER JOIN user ON (user._id = survey_respondent.user_id)";
private static final String PLOT_JOIN = "plot LEFT OUTER JOIN plot_point ON (plot._id = plot_point.plot_id) LEFT OUTER JOIN user ON (user._id = plot.user_id)";
private static final String RESPONDENT_JOIN = "survey_respondent LEFT OUTER JOIN survey ON (survey_respondent.survey_id = survey._id)";
private static final int DATABASE_VERSION = 69;
private final Context context;
/**
* Helper class for creating the database tables and loading reference data
*
* It is declared with package scope for VM optimizations
*
* @author Christopher Fagiani
*
*/
static class DatabaseHelper extends SQLiteOpenHelper {
private static SQLiteDatabase database;
private volatile static int instanceCount = 0;
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USER_TABLE_CREATE);
db.execSQL(SURVEY_TABLE_CREATE);
db.execSQL(SURVEY_RESPONDENT_CREATE);
db.execSQL(SURVEY_RESPONSE_CREATE);
db.execSQL(PLOT_TABLE_CREATE);
db.execSQL(PLOT_POINT_TABLE_CREATE);
db.execSQL(PREFERENCES_TABLE_CREATE);
db.execSQL(POINT_OF_INTEREST_TABLE_CREATE);
db.execSQL(TRANSMISSION_HISTORY_TABLE_CREATE);
for (int i = 0; i < DEFAULT_INSERTS.length; i++) {
db.execSQL(DEFAULT_INSERTS[i]);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion);
if (oldVersion < 57) {
db.execSQL("DROP TABLE IF EXISTS " + RESPONSE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + RESPONDENT_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + SURVEY_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + PLOT_POINT_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + PLOT_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + PREFERENCES_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + POINT_OF_INTEREST_TABLE);
db
.execSQL("DROP TABLE IF EXISTS "
+ TRANSMISSION_HISTORY_TABLE);
onCreate(db);
} else {
// changes made in version 57
try {
db.execSQL(TRANSMISSION_HISTORY_TABLE_CREATE);
} catch (Exception e) {
// swallow since this fails if the update is already applied
}
// changes made in version 58
try {
String value = null;
Cursor cursor = database.query(PREFERENCES_TABLE,
new String[] { KEY_COL, VALUE_COL }, KEY_COL
+ " = ?",
new String[] { "survey.textsize" }, null, null,
null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
value = cursor.getString(cursor
.getColumnIndexOrThrow(VALUE_COL));
}
cursor.close();
}
if (value == null) {
db
.execSQL("insert into preferences values('survey.textsize','LARGE')");
}
} catch (Exception e) {
// swallow
}
// changes in version 63
try {
db
.execSQL("alter table survey_respondent add column exported_flag text");
} catch (Exception e) {
// swallow
}
// changes in version 68
try {
db
.execSQL("alter table survey_respondent add column uuid text");
// also generate a uuid for all in-flight responses
Cursor cursor = db.query(RESPONDENT_JOIN, new String[] {
RESPONDENT_TABLE + "." + PK_ID_COL, DISP_NAME_COL,
SAVED_DATE_COL, SURVEY_FK_COL, USER_FK_COL,
SUBMITTED_DATE_COL, DELIVERED_DATE_COL, UUID_COL },
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
do {
String uuid = cursor.getString(cursor
.getColumnIndex(UUID_COL));
if (uuid == null || uuid.trim().length() == 0) {
db.execSQL("update " + RESPONDENT_TABLE
+ " set " + UUID_COL + "= '"
+ UUID.randomUUID().toString() + "'");
}
} while (cursor.moveToNext());
}
} catch (Exception e) {
//swallow
}
}
}
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
if (database == null) {
database = super.getWritableDatabase();
}
instanceCount++;
return database;
}
@Override
public synchronized void close() {
instanceCount
if (instanceCount <= 0) {
super.close();
database = null;
}
}
}
/**
* Constructor - takes the context to allow the database to be
* opened/created
*
* @param ctx
* the Context within which to work
*/
public SurveyDbAdapter(Context ctx) {
this.context = ctx;
}
/**
* Open or create the db
*
* @throws SQLException
* if the database could be neither opened or created
*/
public SurveyDbAdapter open() throws SQLException {
databaseHelper = new DatabaseHelper(context);
database = databaseHelper.getWritableDatabase();
return this;
}
/**
* close the db
*/
public void close() {
databaseHelper.close();
}
/**
* Create a new survey using the title and body provided. If the survey is
* successfully created return the new id, otherwise return a -1 to indicate
* failure.
*
* @param name
* survey name
*
* @return rowId or -1 if failed
*/
public long createSurvey(String name) {
ContentValues initialValues = new ContentValues();
initialValues.put(DISP_NAME_COL, name);
initialValues.put(HELP_DOWNLOADED_COL, "N");
return database.insert(SURVEY_TABLE, null, initialValues);
}
/**
* returns a cursor that lists all unsent (sentFlag = false) survey data
*
* @return
*/
public Cursor fetchUnsentData() {
Cursor cursor = database.query(RESPONSE_JOIN, new String[] {
RESPONDENT_TABLE + "." + PK_ID_COL, RESP_ID_COL, ANSWER_COL,
ANSWER_TYPE_COL, QUESTION_FK_COL, DISP_NAME_COL, EMAIL_COL,
DELIVERED_DATE_COL, SUBMITTED_DATE_COL,
RESPONDENT_TABLE + "." + SURVEY_FK_COL, SCORED_VAL_COL,
STRENGTH_COL, UUID_COL }, SUBMITTED_FLAG_COL + "= 'true' AND "
+ INCLUDE_FLAG_COL + "='true' AND" + "(" + DELIVERED_DATE_COL
+ " is null OR " + MEDIA_SENT_COL + " <> 'true')", null, null,
null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* returns a cursor that lists all unexported (sentFlag = false) survey data
*
* @return
*/
public Cursor fetchUnexportedData() {
Cursor cursor = database.query(RESPONSE_JOIN, new String[] {
RESPONDENT_TABLE + "." + PK_ID_COL, RESP_ID_COL, ANSWER_COL,
ANSWER_TYPE_COL, QUESTION_FK_COL, DISP_NAME_COL, EMAIL_COL,
DELIVERED_DATE_COL, SUBMITTED_DATE_COL,
RESPONDENT_TABLE + "." + SURVEY_FK_COL, SCORED_VAL_COL,
STRENGTH_COL, UUID_COL }, SUBMITTED_FLAG_COL + "= 'true' AND "
+ INCLUDE_FLAG_COL + "='true' AND " + EXPORTED_FLAG_COL
+ " <> 'true' AND " + "(" + DELIVERED_DATE_COL + " is null OR "
+ MEDIA_SENT_COL + " <> 'true')", null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* marks the data as submitted in the respondent table (submittedFlag =
* true) thereby making it ready for transmission
*
* @param respondentId
*/
public void submitResponses(String respondentId) {
ContentValues vals = new ContentValues();
vals.put(SUBMITTED_FLAG_COL, "true");
vals.put(SUBMITTED_DATE_COL, System.currentTimeMillis());
vals.put(STATUS_COL, ConstantUtil.SUBMITTED_STATUS);
database.update(RESPONDENT_TABLE, vals,
PK_ID_COL + "= " + respondentId, null);
}
/**
* updates the respondent table by recording the sent date stamp
*
* @param idList
*/
public void markDataAsSent(HashSet<String> idList, String mediaSentFlag) {
if (idList != null) {
ContentValues updatedValues = new ContentValues();
updatedValues.put(DELIVERED_DATE_COL, System.currentTimeMillis()
+ "");
updatedValues.put(MEDIA_SENT_COL, mediaSentFlag);
// enhanced FOR ok here since we're dealing with an implicit
// iterator anyway
for (String id : idList) {
if (database.update(RESPONDENT_TABLE, updatedValues, PK_ID_COL
+ " = ?", new String[] { id }) < 1) {
Log.e(TAG,
"Could not update record for Survey_respondent_id "
+ id);
}
}
}
}
/**
* updates the respondent table by recording the sent date stamp
*
* @param idList
*/
public void markDataAsExported(HashSet<String> idList) {
if (idList != null && idList.size() > 0) {
ContentValues updatedValues = new ContentValues();
updatedValues.put(EXPORTED_FLAG_COL, "true");
// enhanced FOR ok here since we're dealing with an implicit
// iterator anyway
for (String id : idList) {
if (database.update(RESPONDENT_TABLE, updatedValues, PK_ID_COL
+ " = ?", new String[] { id }) < 1) {
Log.e(TAG,
"Could not update record for Survey_respondent_id "
+ id);
}
}
}
}
/**
* updates the status of a survey response to the string passed in
*
* @param surveyRespondentId
* @param status
*/
public void updateSurveyStatus(String surveyRespondentId, String status) {
if (surveyRespondentId != null) {
ContentValues updatedValues = new ContentValues();
updatedValues.put(STATUS_COL, status);
updatedValues.put(SAVED_DATE_COL, System.currentTimeMillis());
if (database.update(RESPONDENT_TABLE, updatedValues, PK_ID_COL
+ " = ?", new String[] { surveyRespondentId }) < 1) {
Log.e(TAG, "Could not update status for Survey_respondent_id "
+ surveyRespondentId);
}
}
}
/**
* returns a cursor listing all users
*
* @return
*/
public Cursor listUsers() {
Cursor cursor = database.query(USER_TABLE, new String[] { PK_ID_COL,
DISP_NAME_COL, EMAIL_COL }, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* retrieves a user by ID
*
* @param id
* @return
*/
public Cursor findUser(Long id) {
Cursor cursor = database.query(USER_TABLE, new String[] { PK_ID_COL,
DISP_NAME_COL, EMAIL_COL }, PK_ID_COL + "=?", new String[] { id
.toString() }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* if the ID is populated, this will update a user record. Otherwise, it
* will be inserted
*
* @param id
* @param name
* @param email
* @return
*/
public long createOrUpdateUser(Long id, String name, String email) {
ContentValues initialValues = new ContentValues();
Long idVal = id;
initialValues.put(DISP_NAME_COL, name);
initialValues.put(EMAIL_COL, email);
if (idVal == null) {
idVal = database.insert(USER_TABLE, null, initialValues);
} else {
if (database.update(USER_TABLE, initialValues, PK_ID_COL + "=?",
new String[] { idVal.toString() }) > 0) {
}
}
return idVal;
}
/**
* Return a Cursor over the list of all responses for a particular survey
* respondent
*
* @return Cursor over all responses
*/
public Cursor fetchResponsesByRespondent(String respondentID) {
return database.query(RESPONSE_TABLE, new String[] { RESP_ID_COL,
QUESTION_FK_COL, ANSWER_COL, ANSWER_TYPE_COL,
SURVEY_RESPONDENT_ID_COL, INCLUDE_FLAG_COL, SCORED_VAL_COL,
STRENGTH_COL }, SURVEY_RESPONDENT_ID_COL + "=?",
new String[] { respondentID }, null, null, null);
}
/**
* loads a single question response
*
* @param respondentId
* @param questionId
* @return
*/
public QuestionResponse findSingleResponse(Long respondentId,
String questionId) {
QuestionResponse resp = null;
Cursor cursor = database.query(RESPONSE_TABLE, new String[] {
RESP_ID_COL, QUESTION_FK_COL, ANSWER_COL, ANSWER_TYPE_COL,
SURVEY_RESPONDENT_ID_COL, INCLUDE_FLAG_COL, SCORED_VAL_COL,
STRENGTH_COL }, SURVEY_RESPONDENT_ID_COL + "=? and "
+ QUESTION_FK_COL + "=?", new String[] {
respondentId.toString(), questionId }, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
resp = new QuestionResponse();
resp.setQuestionId(questionId);
resp.setRespondentId(respondentId);
resp.setType(cursor.getString(cursor
.getColumnIndexOrThrow(ANSWER_TYPE_COL)));
resp.setValue(cursor.getString(cursor
.getColumnIndexOrThrow(ANSWER_COL)));
resp.setId(cursor.getLong(cursor
.getColumnIndexOrThrow(RESP_ID_COL)));
resp.setIncludeFlag(cursor.getString(cursor
.getColumnIndexOrThrow(INCLUDE_FLAG_COL)));
resp.setScoredValue(cursor.getString(cursor
.getColumnIndexOrThrow(SCORED_VAL_COL)));
resp.setStrength(cursor.getString(cursor
.getColumnIndexOrThrow(STRENGTH_COL)));
}
cursor.close();
}
return resp;
}
/**
* inserts or updates a question response after first looking to see if it
* already exists in the database.
*
* @param resp
* @return
*/
public QuestionResponse createOrUpdateSurveyResponse(QuestionResponse resp) {
QuestionResponse responseToSave = findSingleResponse(resp
.getRespondentId(), resp.getQuestionId());
if (responseToSave != null) {
responseToSave.setValue(resp.getValue());
responseToSave.setStrength(resp.getStrength());
responseToSave.setScoredValue(resp.getScoredValue());
} else {
responseToSave = resp;
}
long id = -1;
ContentValues initialValues = new ContentValues();
initialValues.put(ANSWER_COL, responseToSave.getValue());
initialValues.put(ANSWER_TYPE_COL, responseToSave.getType());
initialValues.put(QUESTION_FK_COL, responseToSave.getQuestionId());
initialValues.put(SURVEY_RESPONDENT_ID_COL, responseToSave
.getRespondentId());
initialValues.put(SCORED_VAL_COL, responseToSave.getScoredValue());
initialValues.put(INCLUDE_FLAG_COL, resp.getIncludeFlag());
initialValues.put(STRENGTH_COL, responseToSave.getStrength());
if (responseToSave.getId() == null) {
id = database.insert(RESPONSE_TABLE, null, initialValues);
} else {
if (database.update(RESPONSE_TABLE, initialValues, RESP_ID_COL
+ "=?", new String[] { responseToSave.getId().toString() }) > 0) {
id = responseToSave.getId();
}
}
responseToSave.setId(id);
return responseToSave;
}
/**
* this method will get the max survey respondent ID that has an unsubmitted
* survey or, if none exists, will create a new respondent
*
* @param surveyId
* @return
*/
public long createOrLoadSurveyRespondent(String surveyId, String userId) {
Cursor results = database.query(RESPONDENT_TABLE, new String[] { "max("
+ PK_ID_COL + ")" }, SUBMITTED_FLAG_COL + "='false' and "
+ SURVEY_FK_COL + "=? and " + STATUS_COL + " =?", new String[] {
surveyId, ConstantUtil.CURRENT_STATUS }, null, null, null);
long id = -1;
if (results != null && results.getCount() > 0) {
results.moveToFirst();
id = results.getLong(0);
}
if (results != null) {
results.close();
}
if (id <= 0) {
id = createSurveyRespondent(surveyId, userId);
}
return id;
}
/**
* creates a new unsubmitted survey respondent record
*
* @param surveyId
* @return
*/
public long createSurveyRespondent(String surveyId, String userId) {
ContentValues initialValues = new ContentValues();
initialValues.put(SURVEY_FK_COL, surveyId);
initialValues.put(SUBMITTED_FLAG_COL, "false");
initialValues.put(EXPORTED_FLAG_COL, "false");
initialValues.put(USER_FK_COL, userId);
initialValues.put(STATUS_COL, ConstantUtil.CURRENT_STATUS);
initialValues.put(UUID_COL, UUID.randomUUID().toString());
return database.insert(RESPONDENT_TABLE, null, initialValues);
}
/**
* creates a new plot point in the database for the plot and coordinates
* sent in
*
* @param plotId
* @param lat
* @param lon
* @return
*/
public long savePlotPoint(String plotId, String lat, String lon,
double currentElevation) {
ContentValues initialValues = new ContentValues();
initialValues.put(PLOT_FK_COL, plotId);
initialValues.put(LAT_COL, lat);
initialValues.put(LON_COL, lon);
initialValues.put(ELEVATION_COL, currentElevation);
initialValues.put(CREATED_DATE_COL, System.currentTimeMillis());
return database.insert(PLOT_POINT_TABLE, null, initialValues);
}
/**
* returns a cursor listing all plots with the status passed in or all plots
* if status is null
*
* @return
*/
public Cursor listPlots(String status) {
Cursor cursor = database.query(PLOT_TABLE, new String[] { PK_ID_COL,
DISP_NAME_COL, DESC_COL, CREATED_DATE_COL, STATUS_COL },
status == null ? null : STATUS_COL + " = ?",
status == null ? null : new String[] { status }, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* retrieves a plot by ID
*
* @param id
* @return
*/
public Cursor findPlot(Long id) {
Cursor cursor = database.query(PLOT_TABLE, new String[] { PK_ID_COL,
DISP_NAME_COL, DESC_COL, CREATED_DATE_COL, STATUS_COL },
PK_ID_COL + "=?", new String[] { id.toString() }, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* if the ID is populated, this will update a plot record. Otherwise, it
* will be inserted
*
* @param id
* @param name
* @param email
* @return
*/
public long createOrUpdatePlot(Long id, String name, String desc,
String userId) {
ContentValues initialValues = new ContentValues();
Long idVal = id;
initialValues.put(DISP_NAME_COL, name);
initialValues.put(DESC_COL, desc);
initialValues.put(CREATED_DATE_COL, System.currentTimeMillis());
initialValues.put(USER_FK_COL, userId);
initialValues.put(STATUS_COL, ConstantUtil.IN_PROGRESS_STATUS);
if (idVal == null) {
idVal = database.insert(PLOT_TABLE, null, initialValues);
} else {
if (database.update(PLOT_TABLE, initialValues, PK_ID_COL + "=?",
new String[] { idVal.toString() }) > 0) {
}
}
return idVal;
}
/**
* retrieves all the points for a given plot
*
* @param plotId
* @return
*/
public Cursor listPlotPoints(String plotId, String afterTime) {
Cursor cursor = database
.query(PLOT_POINT_TABLE, new String[] { PK_ID_COL, LAT_COL,
LON_COL, CREATED_DATE_COL }, PLOT_FK_COL + " = ? and "
+ CREATED_DATE_COL + " > ?", new String[] { plotId,
afterTime != null ? afterTime : "0" }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* updates the status of a plot in the db
*
* @param plotId
* @param status
*/
public long updatePlotStatus(String plotId, String status) {
ContentValues initialValues = new ContentValues();
initialValues.put(STATUS_COL, status);
return database.update(PLOT_TABLE, initialValues, PK_ID_COL + " = ?",
new String[] { plotId });
}
/**
* updates the status of all the plots identified by the ids sent in to the
* value of status
*
* @param idList
* @param status
*/
public void updatePlotStatus(HashSet<String> idList, String status) {
if (idList != null) {
ContentValues updatedValues = new ContentValues();
updatedValues.put(STATUS_COL, status);
// enhanced FOR ok here since we're dealing with an implicit
// iterator anyway
for (String id : idList) {
if (updatePlotStatus(id, status) < 1) {
Log.e(TAG, "Could not update plot status for plot " + id);
}
}
}
}
/**
* lists all plot points for plots that are in the COMPLETED state
*
* @return
*/
public Cursor listCompletePlotPoints() {
Cursor cursor = database
.query(PLOT_JOIN, new String[] {
PLOT_TABLE + "." + PK_ID_COL + " as plot_id",
PLOT_TABLE + "." + DISP_NAME_COL,
PLOT_POINT_TABLE + "." + PK_ID_COL, LAT_COL, LON_COL,
ELEVATION_COL,
PLOT_POINT_TABLE + "." + CREATED_DATE_COL }, STATUS_COL
+ "= ?", new String[] { ConstantUtil.COMPLETE_STATUS },
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* deletes the plot_point row denoted by the ID passed in
*
* @param id
*/
public void deletePlotPoint(String id) {
database.delete(PLOT_POINT_TABLE, PK_ID_COL + " = ?",
new String[] { id });
}
/**
* returns a list of survey objects that are out of date (missing from the
* db or with a lower version number). If a survey is present but marked as
* deleted, it will not be listed as out of date (and thus won't be updated)
*
* @param surveys
* @return
*/
public ArrayList<Survey> checkSurveyVersions(ArrayList<Survey> surveys) {
ArrayList<Survey> outOfDateSurveys = new ArrayList<Survey>();
for (int i = 0; i < surveys.size(); i++) {
Cursor cursor = database.query(SURVEY_TABLE,
new String[] { PK_ID_COL },
PK_ID_COL + " = ? and (" + VERSION_COL + " >= ? or "
+ DELETED_COL + " = ?)", new String[] {
surveys.get(i).getId(),
surveys.get(i).getVersion() + "",
ConstantUtil.IS_DELETED }, null, null, null);
if (cursor == null || cursor.getCount() <= 0) {
outOfDateSurveys.add(surveys.get(i));
}
if (cursor != null) {
cursor.close();
}
}
return outOfDateSurveys;
}
/**
* updates the survey table by recording the help download flag
*
* @param idList
*/
public void markSurveyHelpDownloaded(String surveyId, boolean isDownloaded) {
ContentValues updatedValues = new ContentValues();
updatedValues.put(HELP_DOWNLOADED_COL, isDownloaded ? "Y" : "N");
if (database.update(SURVEY_TABLE, updatedValues, PK_ID_COL + " = ?",
new String[] { surveyId }) < 1) {
Log.e(TAG, "Could not update record for Survey " + surveyId);
}
}
/**
* updates a survey in the db and resets the deleted flag to "N"
*
* @param survey
* @return
*/
public void saveSurvey(Survey survey) {
Cursor cursor = database.query(SURVEY_TABLE,
new String[] { PK_ID_COL }, PK_ID_COL + " = ?",
new String[] { survey.getId(), }, null, null, null);
ContentValues updatedValues = new ContentValues();
updatedValues.put(PK_ID_COL, survey.getId());
updatedValues.put(VERSION_COL, survey.getVersion());
updatedValues.put(TYPE_COL, survey.getType());
updatedValues.put(LOCATION_COL, survey.getLocation());
updatedValues.put(FILENAME_COL, survey.getFileName());
updatedValues.put(DISP_NAME_COL, survey.getName());
updatedValues.put(LANGUAGE_COL, survey.getLanguage() != null ? survey
.getLanguage().toLowerCase() : survey.getLanguage());
updatedValues.put(HELP_DOWNLOADED_COL, survey.isHelpDownloaded() ? "Y"
: "N");
updatedValues.put(DELETED_COL, ConstantUtil.NOT_DELETED);
if (cursor != null && cursor.getCount() > 0) {
// if we found an item, it's an update, otherwise, it's an insert
database.update(SURVEY_TABLE, updatedValues, PK_ID_COL + " = ?",
new String[] { survey.getId() });
} else {
database.insert(SURVEY_TABLE, null, updatedValues);
}
if (cursor != null) {
cursor.close();
}
}
/**
* Gets a single survey from the db using its primary key
*/
public Survey findSurvey(String surveyId) {
Survey survey = null;
Cursor cursor = database.query(SURVEY_TABLE, new String[] { PK_ID_COL,
DISP_NAME_COL, LOCATION_COL, FILENAME_COL, TYPE_COL,
LANGUAGE_COL, HELP_DOWNLOADED_COL }, PK_ID_COL + " = ?",
new String[] { surveyId }, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
survey = new Survey();
survey.setId(surveyId);
survey.setName(cursor.getString(cursor
.getColumnIndexOrThrow(DISP_NAME_COL)));
survey.setLocation(cursor.getString(cursor
.getColumnIndexOrThrow(LOCATION_COL)));
survey.setFileName(cursor.getString(cursor
.getColumnIndexOrThrow(FILENAME_COL)));
survey.setType(cursor.getString(cursor
.getColumnIndexOrThrow(TYPE_COL)));
survey.setHelpDownloaded(cursor.getString(cursor
.getColumnIndexOrThrow(HELP_DOWNLOADED_COL)));
survey.setLanguage(cursor.getString(cursor
.getColumnIndexOrThrow(LANGUAGE_COL)));
}
cursor.close();
}
return survey;
}
/**
* lists all survey respondents by status
*
* @param status
* @return
*/
public Cursor listSurveyRespondent(String status) {
String[] whereParams = { status };
Cursor cursor = database.query(RESPONDENT_JOIN, new String[] {
RESPONDENT_TABLE + "." + PK_ID_COL, DISP_NAME_COL,
SAVED_DATE_COL, SURVEY_FK_COL, USER_FK_COL, SUBMITTED_DATE_COL,
DELIVERED_DATE_COL, UUID_COL }, "status = ?", whereParams,
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* Lists all non-deleted surveys from the database
*/
public ArrayList<Survey> listSurveys(String language) {
ArrayList<Survey> surveys = new ArrayList<Survey>();
String whereClause = DELETED_COL + " <> ?";
String[] whereParams = null;
if (language != null) {
whereClause += " and " + LANGUAGE_COL + " = ?";
whereParams = new String[] { ConstantUtil.IS_DELETED,
language.toLowerCase().trim() };
} else {
whereParams = new String[] { ConstantUtil.IS_DELETED };
}
Cursor cursor = database.query(SURVEY_TABLE, new String[] { PK_ID_COL,
DISP_NAME_COL, LOCATION_COL, FILENAME_COL, TYPE_COL,
LANGUAGE_COL, HELP_DOWNLOADED_COL, VERSION_COL }, whereClause,
whereParams, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
Survey survey = new Survey();
survey.setId(cursor.getString(cursor
.getColumnIndexOrThrow(PK_ID_COL)));
survey.setName(cursor.getString(cursor
.getColumnIndexOrThrow(DISP_NAME_COL)));
survey.setLocation(cursor.getString(cursor
.getColumnIndexOrThrow(LOCATION_COL)));
survey.setFileName(cursor.getString(cursor
.getColumnIndexOrThrow(FILENAME_COL)));
survey.setType(cursor.getString(cursor
.getColumnIndexOrThrow(TYPE_COL)));
survey.setHelpDownloaded(cursor.getString(cursor
.getColumnIndexOrThrow(HELP_DOWNLOADED_COL)));
survey.setLanguage(cursor.getString(cursor
.getColumnIndexOrThrow(LANGUAGE_COL)));
survey.setVersion(cursor.getDouble(cursor
.getColumnIndexOrThrow(VERSION_COL)));
surveys.add(survey);
} while (cursor.moveToNext());
}
cursor.close();
}
return surveys;
}
/**
* marks a survey record identified by the ID passed in as deleted.
*
* @param surveyId
*/
public void deleteSurvey(String surveyId, boolean physicalDelete) {
if (!physicalDelete) {
ContentValues updatedValues = new ContentValues();
updatedValues.put(DELETED_COL, ConstantUtil.IS_DELETED);
database.update(SURVEY_TABLE, updatedValues, PK_ID_COL + " = ?",
new String[] { surveyId });
} else {
database.delete(SURVEY_TABLE, PK_ID_COL + " = ? ",
new String[] { surveyId });
}
}
/**
* returns the value of a single setting identified by the key passed in
*/
public String findPreference(String key) {
String value = null;
Cursor cursor = database.query(PREFERENCES_TABLE, new String[] {
KEY_COL, VALUE_COL }, KEY_COL + " = ?", new String[] { key },
null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
value = cursor.getString(cursor
.getColumnIndexOrThrow(VALUE_COL));
}
cursor.close();
}
return value;
}
/**
* Lists all settings from the database
*/
public HashMap<String, String> listPreferences() {
HashMap<String, String> settings = new HashMap<String, String>();
Cursor cursor = database.query(PREFERENCES_TABLE, new String[] {
KEY_COL, VALUE_COL }, null, null, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
settings
.put(cursor.getString(cursor
.getColumnIndexOrThrow(KEY_COL)), cursor
.getString(cursor
.getColumnIndexOrThrow(VALUE_COL)));
} while (cursor.moveToNext());
}
cursor.close();
}
return settings;
}
/**
* persists setting to the db
*
* @param surveyId
*/
public void savePreference(String key, String value) {
ContentValues updatedValues = new ContentValues();
updatedValues.put(VALUE_COL, value);
int updated = database.update(PREFERENCES_TABLE, updatedValues, KEY_COL
+ " = ?", new String[] { key });
if (updated <= 0) {
updatedValues.put(KEY_COL, key);
database.insert(PREFERENCES_TABLE, null, updatedValues);
}
}
/**
* deletes all the surveys from the database
*/
public void deleteAllSurveys() {
database.delete(SURVEY_TABLE, null, null);
}
/**
* deletes all the points of interest
*/
public void deleteAllPoints() {
database.delete(POINT_OF_INTEREST_TABLE, null, null);
}
/**
* deletes all survey responses from the database
*/
public void deleteAllResponses() {
database.delete(RESPONSE_TABLE, null, null);
database.delete(RESPONDENT_TABLE, null, null);
}
/**
* deletes all survey responses from the database for a specific respondent
*/
public void deleteResponses(String respondentId) {
database.delete(RESPONSE_TABLE, SURVEY_RESPONDENT_ID_COL + "=?",
new String[] { respondentId });
}
/**
* deletes the respondent record and any responses it contains
*
* @param respondentId
*/
public void deleteRespondent(String respondentId) {
deleteResponses(respondentId);
database.delete(RESPONDENT_TABLE, PK_ID_COL + "=?",
new String[] { respondentId });
}
/**
* deletes a single response
*
* @param respondentId
* @param questionId
*/
public void deleteResponse(String respondentId, String questionId) {
database.delete(RESPONSE_TABLE, SURVEY_RESPONDENT_ID_COL + "=? AND "
+ QUESTION_FK_COL + "=?", new String[] { respondentId,
questionId });
}
/**
* saves or updates a PointOfInterests
*
* @param id
* @param country
* @param jsonString
*/
public void saveOrUpdatePointOfInterest(PointOfInterest point) {
Cursor cursor = database.query(POINT_OF_INTEREST_TABLE,
new String[] { PK_ID_COL }, PK_ID_COL + "=?",
new String[] { point.getId().toString() }, null, null, null);
boolean isUpdate = false;
if (cursor != null && cursor.getCount() > 0) {
isUpdate = true;
}
if (cursor != null) {
cursor.close();
}
ContentValues updatedValues = new ContentValues();
updatedValues.put(PK_ID_COL, point.getId());
updatedValues.put(COUNTRY_COL, point.getCountry() != null ? point
.getCountry() : "unknown");
updatedValues.put(DISP_NAME_COL, point.getName() != null ? point
.getName() : "unknown");
updatedValues.put(TYPE_COL, point.getType() != null ? point.getType()
: "unknown");
updatedValues.put(UPDATED_DATE_COL, System.currentTimeMillis());
String temp = point.getPropertyNamesString();
if (temp != null) {
updatedValues.put(PROP_NAME_COL, temp);
}
temp = point.getPropertyValuesString();
if (temp != null) {
updatedValues.put(PROP_VAL_COL, temp);
}
if (point.getLatitude() != null) {
updatedValues.put(LAT_COL, point.getLatitude());
}
if (point.getLongitude() != null) {
updatedValues.put(LON_COL, point.getLongitude());
}
if (isUpdate) {
database.update(POINT_OF_INTEREST_TABLE, updatedValues, PK_ID_COL
+ "=?", new String[] { point.getId().toString() });
} else {
database.insert(POINT_OF_INTEREST_TABLE, null, updatedValues);
}
}
/**
* lists all points of interest, optionally filtering by country code
*
* @param country
* @return
*/
public ArrayList<PointOfInterest> listPointsOfInterest(String country,
String prefix) {
ArrayList<PointOfInterest> points = null;
String whereClause = null;
String[] whereValues = null;
if (country != null) {
whereClause = COUNTRY_COL + "=?";
whereValues = new String[] { country };
}
if (prefix != null && prefix.trim().length() > 0) {
if (country != null) {
whereClause = whereClause + " AND " + DISP_NAME_COL + " like ?";
whereValues = new String[2];
whereValues[0] = country;
whereValues[1] = prefix + "%";
} else {
whereClause = DISP_NAME_COL + " like ?";
whereValues = new String[] { prefix + "%" };
}
}
Cursor cursor = database.query(POINT_OF_INTEREST_TABLE, new String[] {
PK_ID_COL, COUNTRY_COL, DISP_NAME_COL, UPDATED_DATE_COL,
LAT_COL, LON_COL, PROP_NAME_COL, PROP_VAL_COL, TYPE_COL },
whereClause, whereValues, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
cursor.moveToFirst();
points = new ArrayList<PointOfInterest>();
do {
PointOfInterest point = new PointOfInterest();
point.setName(cursor.getString(cursor
.getColumnIndexOrThrow(DISP_NAME_COL)));
point.setType(cursor.getString(cursor
.getColumnIndexOrThrow(TYPE_COL)));
point.setCountry(cursor.getString(cursor
.getColumnIndexOrThrow(COUNTRY_COL)));
point.setId(cursor.getLong(cursor
.getColumnIndexOrThrow(PK_ID_COL)));
point.setPropertyNames(cursor.getString(cursor
.getColumnIndexOrThrow(PROP_NAME_COL)));
point.setPropertyValues(cursor.getString(cursor
.getColumnIndexOrThrow(PROP_VAL_COL)));
point.setLatitude(cursor.getDouble(cursor
.getColumnIndexOrThrow(LAT_COL)));
point.setLongitude(cursor.getDouble(cursor
.getColumnIndexOrThrow(LON_COL)));
points.add(point);
} while (cursor.moveToNext());
}
cursor.close();
}
return points;
}
/**
* inserts a transmissionHistory row into the db
*
* @param respId
* @param fileName
* @return
*/
public Long createTransmissionHistory(Long respId, String fileName,
String status) {
ContentValues initialValues = new ContentValues();
Long idVal = null;
initialValues.put(SURVEY_RESPONDENT_ID_COL, respId);
initialValues.put(FILENAME_COL, fileName);
if (status != null) {
initialValues.put(STATUS_COL, status);
if (ConstantUtil.IN_PROGRESS_STATUS.equals(status)) {
initialValues.put(TRANS_START_COL, System.currentTimeMillis());
}
} else {
initialValues.put(TRANS_START_COL, (Long) null);
initialValues.put(STATUS_COL, ConstantUtil.QUEUED_STATUS);
}
idVal = database
.insert(TRANSMISSION_HISTORY_TABLE, null, initialValues);
return idVal;
}
/**
* updates the transmisson history record with the status passed in. If the
* status == Completed, the completion date is updated.
*
* @param respondId
* @param fileName
* @param status
*/
public void updateTransmissionHistory(Long respondId, String fileName,
String status) {
ArrayList<FileTransmission> transList = listFileTransmission(respondId,
fileName, true);
Long idVal = null;
if (transList != null && transList.size() > 0) {
idVal = transList.get(0).getId();
if (idVal != null) {
ContentValues vals = new ContentValues();
vals.put(STATUS_COL, status);
if (ConstantUtil.COMPLETE_STATUS.equals(status)) {
vals.put(DELIVERED_DATE_COL, System.currentTimeMillis()
+ "");
} else if (ConstantUtil.IN_PROGRESS_STATUS.equals(status)) {
vals.put(TRANS_START_COL, System.currentTimeMillis() + "");
}
database.update(TRANSMISSION_HISTORY_TABLE, vals, PK_ID_COL
+ " = ?", new String[] { idVal.toString() });
}
}
}
/**
* lists all the file transmissions for the values passed in.
*
* @param respondentId
* - MANDATORY id of the survey respondent
* @param fileName
* - OPTIONAL file name
* @param incompleteOnly
* - if true, only rows without a complete status will be
* returned
* @return
*/
public ArrayList<FileTransmission> listFileTransmission(Long respondentId,
String fileName, boolean incompleteOnly) {
ArrayList<FileTransmission> transList = null;
String whereClause = SURVEY_RESPONDENT_ID_COL + "=?";
if (incompleteOnly) {
whereClause = whereClause + " AND " + STATUS_COL + " <> '"
+ ConstantUtil.COMPLETE_STATUS + "'";
}
String[] whereValues = null;
if (fileName != null && fileName.trim().length() > 0) {
whereClause = whereClause + " AND " + FILENAME_COL + " = ?";
whereValues = new String[2];
whereValues[0] = respondentId.toString();
whereValues[1] = fileName;
} else {
whereValues = new String[] { respondentId.toString() };
}
Cursor cursor = database.query(TRANSMISSION_HISTORY_TABLE,
new String[] { PK_ID_COL, FILENAME_COL, STATUS_COL,
TRANS_START_COL, DELIVERED_DATE_COL,
SURVEY_RESPONDENT_ID_COL }, whereClause, whereValues,
null, null, TRANS_START_COL + " desc");
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
cursor.moveToFirst();
transList = new ArrayList<FileTransmission>();
do {
FileTransmission trans = new FileTransmission();
trans.setId(cursor.getLong(cursor
.getColumnIndexOrThrow(PK_ID_COL)));
trans.setRespondentId(respondentId);
trans.setFileName(cursor.getString(cursor
.getColumnIndexOrThrow(FILENAME_COL)));
Long startDateMillis = cursor.getLong(cursor
.getColumnIndexOrThrow(TRANS_START_COL));
if (startDateMillis != null && startDateMillis > 0) {
trans.setStartDate(new Date(startDateMillis));
}
Long delivDateMillis = cursor.getLong(cursor
.getColumnIndexOrThrow(DELIVERED_DATE_COL));
if (delivDateMillis != null && delivDateMillis > 0) {
trans.setEndDate(new Date(delivDateMillis));
}
trans.setStatus(cursor.getString(cursor
.getColumnIndexOrThrow(STATUS_COL)));
transList.add(trans);
} while (cursor.moveToNext());
}
cursor.close();
}
return transList;
}
/**
* marks submitted data as unsent. If an ID is passed in, only that
* submission will be updated. If id is null, ALL data will be marked as
* unsent.
*/
public void markDataUnsent(Long id) {
if (id == null) {
executeSql("update survey_respondent set media_sent_flag = 'false', delivered_date = null;");
} else {
executeSql("update survey_respondent set media_sent_flag = 'false', delivered_date = null where _id = "
+ id);
}
}
/**
* executes a single insert/update/delete DML or any DDL statement without
* any bind arguments.
*
* @param sql
*/
public void executeSql(String sql) {
database.execSQL(sql);
}
/**
* reinserts the test survey into the database. For debugging purposes only.
* The survey xml must exist in the APK
*/
public void reinstallTestSurvey() {
executeSql("insert into survey values(999991,'Sample Survey', 1.0,'Survey','res','testsurvey','english','N','N')");
}
/**
* permanently deletes all surveys, responses, users and transmission
* history from the database
*/
public void clearAllData() {
executeSql("delete from survey");
executeSql("delete from survey_respondent");
executeSql("delete from survey_response");
executeSql("delete from user");
executeSql("delete from transmission_history");
executeSql("update preferences set value = '' where key = 'user.lastuser.id'");
}
}
|
package com.intellij.openapi.externalSystem.model.task;
import com.intellij.openapi.extensions.ExtensionPointName;
import org.jetbrains.annotations.NotNull;
/**
* Defines contract for callback to listen external task notifications.
*
* @author Denis Zhdanov
* @since 11/10/11 11:57 AM
*/
public interface ExternalSystemTaskNotificationListener {
ExtensionPointName<ExternalSystemTaskNotificationListener> EP_NAME
= ExtensionPointName.create("com.intellij.externalSystemTaskNotificationListener");
/**
* @deprecated use {@link #onStart(ExternalSystemTaskId, String)}
*/
void onQueued(@NotNull ExternalSystemTaskId id, String workingDir);
/**
* Notifies that task with the given id is about to be started.
*
* @param id target task's id
* @param workingDir working directory
*/
default void onStart(@NotNull ExternalSystemTaskId id, String workingDir) {
onQueued(id, workingDir);
onStart(id);
}
/**
* @deprecated use {@link #onStart(ExternalSystemTaskId, String)}
*/
void onStart(@NotNull ExternalSystemTaskId id);
/**
* Notifies about processing state change of task with the given id.
*
* @param event event that holds information about processing change state of the
* {@link ExternalSystemTaskNotificationEvent#getId() target task}
*/
void onStatusChange(@NotNull ExternalSystemTaskNotificationEvent event);
/**
* Notifies about text written to stdout/stderr during the task execution
*
* @param id id of the task being executed
* @param text text produced by external system during the target task execution
* @param stdOut flag which identifies output type (stdout or stderr)
*/
void onTaskOutput(@NotNull ExternalSystemTaskId id, @NotNull String text, boolean stdOut);
/**
* Notifies that task with the given id is finished.
*
* @param id target task's id
*/
void onEnd(@NotNull ExternalSystemTaskId id);
/**
* Notifies that task with the given id is finished successfully.
*
* @param id target task's id
*/
void onSuccess(@NotNull ExternalSystemTaskId id);
/**
* Notifies that task with the given id is failed.
*
* @param id target task's id
* @param e failure exception
*/
void onFailure(@NotNull ExternalSystemTaskId id, @NotNull Exception e);
/**
* Notifies that task with the given id is queued for the cancellation.
* <p/>
* 'Queued' here means that intellij process-local codebase receives request to cancel the target task and even has not been
* sent it to the slave gradle api process.
*
* @param id target task's id
*/
void beforeCancel(@NotNull ExternalSystemTaskId id);
/**
* Notifies that task with the given id is cancelled.
*
* @param id target task's id
*/
void onCancel(@NotNull ExternalSystemTaskId id);
}
|
package edu.csh.chase.RestfulAPIConnector;
import org.json.JSONArray;
import org.json.JSONObject;
import java.lang.Double;
import java.lang.Integer;
import java.lang.String;
public class JSONParameter extends Parameter{
public static final int JSONSTRINGBODY = 0;
public static final int JSONOBJECTPARAMETER = 1;
public static final int JSONARRAYPARAMETER = 2;
public static final int JSONINTPARAMETER = 3;
public static final int JSONBOOLEANPARAMETER = 4;
public static final int JSONDOUBLEPARAMETER = 5;
public static final int JSONLONGPARAMETER = 6;
Object value;//either JSONObject or JSONArray;
private int jsonParameterType = 0;
public JSONParameter(final String key, String value) throws RestAPIParemeterException{
super(key, value, Parameter.JSONBODY);
}
public JSONParameter(final String key, JSONObject value) throws RestAPIParemeterException{
super(key, "", Parameter.JSONBODY);
jsonParameterType = JSONOBJECTPARAMETER;
this.value = value;
}
public JSONParameter(final String key, JSONArray value) throws RestAPIParemeterException{
super(key, "", Parameter.JSONBODY);
jsonParameterType = JSONARRAYPARAMETER;
this.value = value;
}
public JSONParameter(final String key, boolean value) throws RestAPIParemeterException{
super(key, "", Parameter.JSONBODY);
this.value = new Boolean(value);
jsonParameterType = JSONBOOLEANPARAMETER;
}
public JSONParameter(final String key, int value) throws RestAPIParemeterException{
super(key, "", Parameter.JSONBODY);
this.value = new Integer(value);
jsonParameterType = JSONINTPARAMETER;
}
public JSONParameter(final String key, double value) throws RestAPIParemeterException{
super(key, "", Parameter.JSONBODY);
this.value = new Double(value);
jsonParameterType = JSONDOUBLEPARAMETER;
}
public JSONParameter(final String key, long value) throws RestAPIParemeterException{
super(key, "", Parameter.JSONBODY);
this.value = new Long(value);
jsonParameterType = JSONLONGPARAMETER;
}
public int getJsonParameterType(){
return jsonParameterType;
}
public Object getObjectValue(){
return value;
}
}
|
package edu.icom4029.cool.cgen;
// This is a project skeleton file
import java.io.PrintStream;
import java.util.Enumeration;
import edu.icom4029.cool.ast.Expression;
import edu.icom4029.cool.ast.Expressions;
import edu.icom4029.cool.core.Flags;
import edu.icom4029.cool.lexer.AbstractSymbol;
import edu.icom4029.cool.lexer.AbstractTable;
import edu.icom4029.cool.lexer.BoolConst;
import edu.icom4029.cool.lexer.IntSymbol;
import edu.icom4029.cool.lexer.StringSymbol;
/** This class aggregates all kinds of support routines and constants
for the code generator; all routines are statics, so no instance of
this class is even created. */
public class CgenSupport {
/** Runtime constants for controlling the garbage collector. */
public final static String[] gcInitNames = {
"_NoGC_Init", "_GenGC_Init", "_ScnGC_Init"
};
/** Runtime constants for controlling the garbage collector. */
public final static String[] gcCollectNames = {
"_NoGC_Collect", "_GenGC_Collect", "_ScnGC_Collect"
};
public final static int MAXINT = 100000000;
public final static int WORD_SIZE = 4;
public final static int LOG_WORD_SIZE = 2; // for logical shifts
// Global names
public final static String CLASSNAMETAB = "class_nameTab";
public final static String CLASSOBJTAB = "class_objTab";
public final static String INTTAG = "_int_tag";
public final static String BOOLTAG = "_bool_tag";
public final static String STRINGTAG = "_string_tag";
public final static String HEAP_START = "heap_start";
public final static String DISP_ABORT = "_dispatch_abort";
public final static String CASE_ABORT = "_case_abort";
public final static String CASE_ABORT2 = "_case_abort2";
// Naming conventions
public final static String DISPTAB_SUFFIX = "_dispTab";
public final static String METHOD_SEP = ".";
public final static String PARAM_SEP = ".";
public final static String CLASSINIT_SUFFIX = "_init";
public final static String PROTOBJ_SUFFIX = "_protObj";
public final static String OBJECTPROTOBJ = "Object" + PROTOBJ_SUFFIX;
public final static String INTCONST_PREFIX = "int_const";
public final static String STRCONST_PREFIX = "str_const";
public final static String BOOLCONST_PREFIX = "bool_const";
public final static int EMPTYSLOT = 0;
public final static String LABEL = ":\n";
// information about object headers
public final static int DEFAULT_OBJFIELDS = 3;
public final static int TAG_OFFSET = 0;
public final static int SIZE_OFFSET = 1;
public final static int DISPTABLE_OFFSET = 2;
public final static int STRING_SLOTS = 1;
public final static int INT_SLOTS = 1;
public final static int BOOL_SLOTS = 1;
public final static String GLOBAL = "\t.globl\t";
public final static String ALIGN = "\t.align\t2\n";
public final static String WORD = "\t.word\t";
// register names,
public final static String ZERO= "$zero"; // Zero register
public final static String ACC = "$a0"; // Accumulator
public final static String A1 = "$a1"; // For arguments to prim funcs
public final static String SELF= "$s0"; // Ptr to self (callee saves)
public final static String T1 = "$t1"; // Temporary 1
public final static String T2 = "$t2"; // Temporary 2
public final static String T3 = "$t3"; // Temporary 3
public final static String SP = "$sp"; // Stack pointer
public final static String FP = "$fp"; // Frame pointer
public final static String RA = "$ra"; // Return address
// Opcodes
public final static String JALR = "\tjalr\t";
public final static String JAL = "\tjal\t";
public final static String RET = "\tjr\t" + RA + "\t";
public final static String SW = "\tsw\t";
public final static String LW = "\tlw\t";
public final static String LI = "\tli\t";
public final static String LA = "\tla\t";
public final static String MOVE = "\tmove\t";
public final static String NEG = "\tneg\t";
public final static String ADD = "\tadd\t";
public final static String ADDI = "\taddi\t";
public final static String ADDU = "\taddu\t";
public final static String ADDIU= "\taddiu\t";
public final static String DIV = "\tdiv\t";
public final static String MUL = "\tmul\t";
public final static String SUB = "\tsub\t";
public final static String SLL = "\tsll\t";
public final static String BEQZ = "\tbeqz\t";
public final static String BRANCH = "\tb\t";
public final static String BEQ = "\tbeq\t";
public final static String BNE = "\tbne\t";
public final static String BLEQ = "\tble\t";
public final static String BLT = "\tblt\t";
public final static String BGT = "\tbgt\t";
public static AbstractSymbol currentFilename;
public static CgenNode currentClass;
private static int labelNum = 0;
/** Emits an LW instruction.
* @param dest_reg the destination register
* @param offset the word offset from source register
* @param source_reg the source register
* @param s the output stream
* */
public static void emitLoad(String dest_reg, int offset, String source_reg,
PrintStream s) {
s.println(LW + dest_reg + " "
+ offset * WORD_SIZE
+ "(" + source_reg + ")");
}
/** Emits an SW instruction.
* @param dest_reg the destination register
* @param offset the word offset from source register
* @param source_reg the source register
* @param s the output stream
* */
public static void emitStore(String source_reg, int offset, String dest_reg,
PrintStream s) {
s.println(SW + source_reg + " "
+ offset * WORD_SIZE
+ "(" + dest_reg + ")");
}
/** Emits the LI instruction.
* @param dest_reg the destination register
* @param val the integer value
* @param s the output stream
* */
public static void emitLoadImm(String dest_reg, int val, PrintStream s) {
s.println(LI + dest_reg + " " + val);
}
/** Emits an LA instruction.
* @param dest_reg the destination register
* @param address the address from which a word is loaded
* @param s the output stream
* */
public static void emitLoadAddress(String dest_reg, String address,PrintStream s){
s.println(LA + dest_reg + " " + address);
}
/** Emits an LA instruction without the address part.
* @param dest_reg the destination register
* @param s the output stream
* */
public static void emitPartialLoadAddress(String dest_reg, PrintStream s) {
s.print(LA + dest_reg + " ");
}
/** Emits an instruction to load a boolean constant into a register.
* @param dest_reg the destination register
* @param b the boolean constant
* @param s the output stream
* */
public static void emitLoadBool(String dest_reg, BoolConst b, PrintStream s) {
emitPartialLoadAddress(dest_reg, s);
b.codeRef(s);
s.println("");
}
/** Emits an instruction to load a string constant into a register.
* @param dest_reg the destination register
* @param str the string constant
* @param s the output stream
* */
public static void emitLoadString(String dest_reg, StringSymbol str,
PrintStream s) {
emitPartialLoadAddress(dest_reg, s);
str.codeRef(s);
s.println("");
}
/** Emits an instruction to load an integer constant into a register.
* @param dest_reg the destination register
* @param i the integer constant
* @param s the output stream
* */
public static void emitLoadInt(String dest_reg, IntSymbol i, PrintStream s) {
emitPartialLoadAddress(dest_reg, s);
i.codeRef(s);
s.println("");
}
/** Emits a MOVE instruction.
* @param dest_reg the destination register
* @param source_reg the source register
* @param s the output stream
* */
public static void emitMove(String dest_reg, String source_reg, PrintStream s) {
s.println(MOVE + dest_reg + " " + source_reg);
}
/** Emits a NEG instruction.
* @param dest_reg the destination register
* @param source_reg the source register
* @param s the output stream
* */
public static void emitNeg(String dest_reg, String source_reg, PrintStream s) {
s.println(NEG + dest_reg + " " + source_reg);
}
/** Emits an ADD instruction.
* @param dest_reg the destination register
* @param src1 the source register 1
* @param src2 the source register 2
* @param s the output stream
* */
public static void emitAdd(String dest_reg, String src1, String src2,
PrintStream s) {
s.println(ADD + dest_reg + " " + src1 + " " + src2);
}
/** Emits an ADDU instruction.
* @param dest_reg the destination register
* @param src1 the source register 1
* @param src2 the source register 2
* @param s the output stream
* */
public static void emitAddu(String dest_reg, String src1, String src2,
PrintStream s) {
s.println(ADDU + dest_reg + " " + src1 + " " + src2);
}
/** Emits an ADDIU instruction.
* @param dest_reg the destination register
* @param src the source register
* @param imm the immediate
* @param s the output stream
* */
public static void emitAddiu(String dest_reg, String src, int imm,
PrintStream s) {
s.println(ADDIU + dest_reg + " " + src + " " + imm);
}
/** Emits a DIV instruction.
* @param dest_reg the destination register
* @param src1 the source register 1
* @param src2 the source register 2
* @param s the output stream
* */
public static void emitDiv(String dest_reg, String src1, String src2,
PrintStream s) {
s.println(DIV + dest_reg + " " + src1 + " " + src2);
}
/** Emits a MUL instruction.
* @param dest_reg the destination register
* @param src1 the source register 1
* @param src2 the source register 2
* @param s the output stream
* */
public static void emitMul(String dest_reg, String src1, String src2,
PrintStream s) {
s.println(MUL + dest_reg + " " + src1 + " " + src2);
}
/** Emits a SUB instruction.
* @param dest_reg the destination register
* @param src1 the source register 1
* @param src2 the source register 2
* @param s the output stream
* */
public static void emitSub(String dest_reg, String src1, String src2,
PrintStream s) {
s.println(SUB + dest_reg + " " + src1 + " " + src2);
}
/** Emits an SLL instruction.
* @param dest_reg the destination register
* @param src1 the source register 1
* @param num the number of bits to shift
* @param s the output stream
* */
public static void emitSll(String dest_reg, String src1, int num, PrintStream s) {
s.println(SLL + dest_reg + " " + src1 + " " + num);
}
/** Emits a JALR instruction.
* @param dest_reg the register with target address
* @param s the output stream
* */
public static void emitJalr(String dest_reg, PrintStream s) {
s.println(JALR + dest_reg);
}
/** Emits a JAL instruction.
* @param dest the target address or label
* @param s the output stream
* */
public static void emitJal(String dest, PrintStream s) {
s.println(JAL + dest);
}
/** Emits a RET instruction.
* @param s the output stream
* */
public static void emitReturn(PrintStream s) {
s.println(RET);
}
/** Emits a call to gc_assign.
* @param s the output stream
* */
public static void emitGCAssign(PrintStream s) {
s.println(JAL + "_GenGC_Assign");
}
/** Emits a reference to dispatch table.
* @param sym the name of the class
* @param s the output stream
* */
public static void emitDispTableRef(AbstractSymbol sym, PrintStream s) {
s.print(sym + DISPTAB_SUFFIX);
}
/** Emits a reference to class' init() method.
* @param sym the name of the class
* @param s the output stream
* */
public static void emitInitRef(AbstractSymbol sym, PrintStream s) {
s.print(sym + CLASSINIT_SUFFIX);
}
/** Emits a reference to class' prototype object.
* @param sym the name of the class
* @param s the output stream
* */
public static void emitProtObjRef(AbstractSymbol sym, PrintStream s) {
s.print(sym + PROTOBJ_SUFFIX);
}
/** Emits a reference to a method in a class
* @param classname the name of the class
* @param methodname the name of the method
* @param s the output stream
* */
public static void emitMethodRef(AbstractSymbol classname,
AbstractSymbol methodname,
PrintStream s) {
s.print(classname + METHOD_SEP + methodname);
}
/** Emits a reference to a label
* @param label the label number
* @param s the output stream
* */
public static void emitLabelRef(int label, PrintStream s) {
s.print("label" + label);
}
/** Emits a definition of a label
* @param label the label number
* @param s the output stream
* */
public static void emitLabelDef(int label, PrintStream s) {
emitLabelRef(label, s);
s.println(":");
}
/** Emits a BEQZ instruction.
* @param src the source register
* @param label the label number
* @param s the output stream
* */
public static void emitBeqz(String src, int label, PrintStream s) {
s.print(BEQZ + src + " ");
emitLabelRef(label, s);
s.println("");
}
/** Emits a BEQ instruction.
* @param src1 the source register 1
* @param src2 the source register 2
* @param label the label number
* @param s the output stream
* */
public static void emitBeq(String src1, String src2, int label, PrintStream s) {
s.print(BEQ + src1 + " " + src2 + " ");
emitLabelRef(label, s);
s.println("");
}
/** Emits a BNE instruction.
* @param src1 the source register 1
* @param src2 the source register 2
* @param label the label number
* @param s the output stream
* */
public static void emitBne(String src1, String src2, int label, PrintStream s) {
s.print(BNE + src1 + " " + src2 + " ");
emitLabelRef(label, s);
s.println("");
}
/** Emits a BLEQ instruction.
* @param src1 the source register 1
* @param src2 the source register 2
* @param label the label number
* @param s the output stream
* */
public static void emitBleq(String src1, String src2, int label, PrintStream s) {
s.print(BLEQ + src1 + " " + src2 + " ");
emitLabelRef(label, s);
s.println("");
}
/** Emits a BLT instruction.
* @param src1 the source register 1
* @param src2 the source register 2
* @param label the label number
* @param s the output stream
* */
public static void emitBlt(String src1, String src2, int label, PrintStream s) {
s.print(BLT + src1 + " " + src2 + " ");
emitLabelRef(label, s);
s.println("");
}
/** Emits a BLTI instruction.
* @param src the source register
* @param imm the immediate
* @param label the label number
* @param s the output stream
* */
public static void emitBlti(String src, int imm, int label, PrintStream s) {
s.print(BLT + src + " " + imm + " ");
emitLabelRef(label, s);
s.println("");
}
/** Emits a BGTI instruction.
* @param src the source register
* @param imm the immediate
* @param label the label number
* @param s the output stream
* */
public static void emitBgti(String src, int imm, int label, PrintStream s) {
s.print(BGT + src + " " + imm + " ");
emitLabelRef(label, s);
s.println("");
}
/** Emits a BRANCH instruction.
* @param label the label number
* @param s the output stream
* */
public static void emitBranch(int label, PrintStream s) {
s.print(BRANCH);
emitLabelRef(label, s);
s.println("");
}
/** Emit a sequence of instructions to push a register onto stack.
* Stack grows toward smaller addresses.
* @param reg the register
* @param s the output stream
* */
public static void emitPush(String reg, PrintStream s) {
emitStore(reg, 0, SP, s);
emitAddiu(SP, SP, -4, s);
}
public static void emitPop(String reg, PrintStream s) {
emitPop(s);
emitLoad(reg, 0, SP, s);
}
public static void emitPop(PrintStream s) {
emitAddiu(SP, SP, 4, s);
}
/** Emits code to fetch the integer value of the Integer object.
* @param source a pointer to the Integer object
* @param dest the destination register for the value
* @param s the output stream
* */
public static void emitFetchInt(String dest, String source, PrintStream s) {
emitLoad(dest, DEFAULT_OBJFIELDS, source, s);
}
/** Emits code to store the integer value of the Integer object.
* @param source an integer value
* @param dest the pointer to an Integer object
* @param s the output stream
* */
public static void emitStoreInt(String source, String dest, PrintStream s) {
emitStore(source, DEFAULT_OBJFIELDS, dest, s);
}
/** Emits code to manipulate garbage collector
* @param s the output stream
* */
public static void emitTestCollector(PrintStream s) {
emitPush(ACC, s);
emitMove(ACC, SP, s);
emitMove(A1, ZERO, s);
s.println(JAL + gcCollectNames[Flags.cgen_Memmgr]);
emitAddiu(SP, SP, 4, s);
emitLoad(ACC, 0, SP, s);
}
/** Emits code to check the garbage collector
* @param s the output stream
* */
public static void emitGCCheck(String source, PrintStream s) {
if (source != A1) emitMove(A1, source, s);
s.println(JAL + "_gc_check");
}
private static boolean ascii = false;
/** Switch output mode to ASCII.
* @param s the output stream
* */
public static void asciiMode(PrintStream s) {
if (!ascii) {
s.print("\t.ascii\t\"");
ascii = true;
}
}
/** Switch output mode to BYTE
* @param s the output stream
* */
public static void byteMode(PrintStream s) {
if (ascii) {
s.println("\"");
ascii = false;
}
}
/** Emits a string constant.
* @param str the string constant
* @param s the output stream
* */
public static void emitStringConstant(String str, PrintStream s) {
ascii = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '\n':
asciiMode(s);
s.print("\\n");
break;
case '\t':
asciiMode(s);
s.print("\\t");
break;
case '\\':
byteMode(s);
s.println("\t.byte\t" + (byte) '\\');
break;
case '"':
asciiMode(s);
s.print("\\\"");
break;
default:
if (c >= 0x20 && c <= 0x7f) {
asciiMode(s);
s.print(c);
} else {
byteMode(s);
s.println("\t.byte\t" + (byte) c);
}
}
}
byteMode(s);
s.println("\t.byte\t0\t");
}
public static void emitStartMethod(PrintStream s) {
emitPush(FP, s);
emitPush(SELF, s);
emitMove(FP, SP, s);
emitPush(RA, s);
}
public static void emitEndMethod(int args, PrintStream s) {
emitPop(RA, s);
emitPop(SELF, s);
emitPop(FP, s);
for (int i = 0; i < args; ++i) {
emitPop(s);
}
emitReturn(s);
}
public static void emitDispatchAbort(PrintStream s) {
emitJal(DISP_ABORT, s);
}
public static void emitCaseAbort(PrintStream s) {
emitJal(CASE_ABORT, s);
}
public static void emitCaseAbort2(PrintStream s) {
emitJal(CASE_ABORT2, s);
}
public static String getStringRef(String s) {
StringSymbol sym = (StringSymbol) AbstractTable.stringtable.lookup(s);
return STRCONST_PREFIX + sym.getIndex();
}
public static String getStringRef(AbstractSymbol s) {
return getStringRef(s.getString());
}
public static String getIntRef(Integer n) {
IntSymbol sym = (IntSymbol) AbstractTable.inttable.lookup(n.toString());
return INTCONST_PREFIX + sym.getIndex();
}
public static int genLabelNum() {
return labelNum++;
}
public static void emitArith(Expression e1, Expression e2, String action, PrintStream s) {
e1.code(s);
CgenSupport.emitFetchInt(CgenSupport.T1, CgenSupport.ACC, s);
CgenSupport.emitPush(CgenSupport.T1, s);
e2.code(s);
CgenSupport.emitJal("Object.copy", s);
CgenSupport.emitFetchInt(CgenSupport.T2, CgenSupport.ACC, s);
CgenSupport.emitPop(CgenSupport.T1, s);
s.println(action + T1 + " " + T1 + " " + T2);
CgenSupport.emitStoreInt(CgenSupport.T1, CgenSupport.ACC, s);
}
public static void emitLoadFalse(String dest, PrintStream s) {
emitPartialLoadAddress(dest, s);
BoolConst.falsebool.codeRef(s);
s.println("");
}
public static void emitLoadTrue(String dest, PrintStream s) {
emitPartialLoadAddress(dest, s);
BoolConst.truebool.codeRef(s);
s.println("");
}
public static void emitComparison(Expression e1, Expression e2, String op, PrintStream s) {
e1.code(s);
emitPush(ACC, s);
e2.code(s);
emitPop(T1, s);
emitMove(T2, ACC, s);
emitLoadTrue(ACC, s);
int labelEnd = genLabelNum();
emitFetchInt(T1, T1, s);
emitFetchInt(T2, T2, s);
s.print(op + T1 + " " + T2 + " ");
emitLabelRef(labelEnd, s);
s.println("");
emitLoadFalse(ACC, s);
emitLabelDef(labelEnd, s);
}
public static void emitCheckVoidCallDispAbort(int lineNumber, PrintStream s) {
int label = genLabelNum();
emitBne(ACC, ZERO, label, s);
emitLoadAddress(ACC, getStringRef(currentFilename), s);
emitLoadImm(T1, lineNumber, s);
emitDispatchAbort(s);
emitLabelDef(label, s);
}
public static void emitCheckVoidCallCaseAbort2(int lineNumber, PrintStream s) {
int label = genLabelNum();
emitBne(ACC, ZERO, label, s);
emitLoadAddress(ACC, getStringRef(currentFilename), s);
emitLoadImm(T1, lineNumber, s);
emitCaseAbort2(s);
emitLabelDef(label, s);
}
public static void codeActuals(Expressions actuals, PrintStream s) {
for (Enumeration e = actuals.getElements(); e.hasMoreElements();) {
Expression actual = (Expression) e.nextElement();
actual.code(s);
CgenSupport.emitPush(CgenSupport.ACC, s);
}
}
}
|
package org.eclipse.jdt.internal.core;
import org.eclipse.che.api.project.shared.Constants;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelStatus;
import org.eclipse.jdt.core.IJavaModelStatusConstants;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IRegion;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.WorkingCopyOwner;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.eval.IEvaluationContext;
import org.eclipse.jdt.internal.compiler.util.ObjectVector;
import org.eclipse.jdt.internal.compiler.util.SuffixConstants;
import org.eclipse.jdt.internal.core.util.JavaElementFinder;
import org.eclipse.jdt.internal.core.util.MementoTokenizer;
import org.eclipse.jdt.internal.core.util.Messages;
import org.eclipse.jdt.internal.core.util.Util;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.osgi.service.prefs.BackingStoreException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import static org.eclipse.jdt.internal.core.JavaModelManager.PerProjectInfo;
import static org.eclipse.jdt.internal.core.JavaModelManager.getJavaModelManager;
import static org.eclipse.jdt.internal.core.JavaModelManager.getTarget;
import static org.eclipse.jdt.internal.core.JavaModelManager.isFile;
/**
* @author Evgen Vidolob
*/
public class JavaProject extends Openable implements IJavaProject, SuffixConstants {
/**
* Name of file containing project classpath
*/
public static final String INNER_DIR = Constants.CODENVY_DIR;
public static final String CLASSPATH_FILENAME = INNER_DIR + "/classpath";
/**
* Whether the underlying file system is case sensitive.
*/
protected static final boolean IS_CASE_SENSITIVE = !new File("Temp").equals(new File("temp"));
/**
* An empty array of strings indicating that a project doesn't have any prerequesite projects.
*/
protected static final String[] NO_PREREQUISITES = CharOperation.NO_STRINGS;
/**
* Value of the project's raw classpath if the .classpath file contains invalid entries.
*/
public static final IClasspathEntry[] INVALID_CLASSPATH = new IClasspathEntry[0];
private static final Logger LOG = LoggerFactory.getLogger(JavaProject.class);
protected IProject project;
public JavaProject(IProject project, JavaElement parent) {
super(parent);
this.project = project;
//create
if(project.exists()) {
IFolder folder = project.getFolder(INNER_DIR);
if (!folder.exists()) {
try {
folder.create(true, true, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
}
/**
* Returns true if the given project is accessible and it has
* a java nature, otherwise false.
*
* @param project
* IProject
* @return boolean
*/
public static boolean hasJavaNature(IProject project) {
try {
return project.hasNature(JavaCore.NATURE_ID);
} catch (CoreException e) {
if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(project.getName()))
return true;
// project does not exist or is not open
}
return false;
}
public static boolean areClasspathsEqual(
IClasspathEntry[] firstClasspath, IClasspathEntry[] secondClasspath,
IPath firstOutputLocation, IPath secondOutputLocation) {
int length = firstClasspath.length;
if (length != secondClasspath.length) return false;
for (int i = 0; i < length; i++) {
if (!firstClasspath[i].equals(secondClasspath[i]))
return false;
}
if (firstOutputLocation == null)
return secondOutputLocation == null;
return firstOutputLocation.equals(secondOutputLocation);
}
/**
* Computes the package fragment roots identified by the given entry.
* Only works with resolved entry
* @param resolvedEntry IClasspathEntry
* @return IPackageFragmentRoot[]
*/
public IPackageFragmentRoot[] computePackageFragmentRoots(IClasspathEntry resolvedEntry) {
try {
return
computePackageFragmentRoots(
new IClasspathEntry[]{ resolvedEntry },
false, // don't retrieve exported roots
null /* no reverse map */
);
} catch (JavaModelException e) {
return new IPackageFragmentRoot[] {};
}
}
/**
* Returns the raw classpath for the project, as a list of classpath
* entries. This corresponds to the exact set of entries which were assigned
* using <code>setRawClasspath</code>, in particular such a classpath may
* contain classpath variable and classpath container entries. Classpath
* variable and classpath container entries can be resolved using the
* helper method <code>getResolvedClasspath</code>; classpath variable
* entries also can be resolved individually using
* <code>JavaCore#getClasspathVariable</code>).
* <p>
* Both classpath containers and classpath variables provides a level of
* indirection that can make the <code>.classpath</code> file stable across
* workspaces.
* As an example, classpath variables allow a classpath to no longer refer
* directly to external JARs located in some user specific location.
* The classpath can simply refer to some variables defining the proper
* locations of these external JARs. Similarly, classpath containers
* allows classpath entries to be computed dynamically by the plug-in that
* defines that kind of classpath container.
* </p>
* <p>
* Note that in case the project isn't yet opened, the classpath will
* be read directly from the associated <tt>.classpath</tt> file.
* </p>
*
* @return the raw classpath for the project, as a list of classpath entries
* @throws org.eclipse.jdt.core.JavaModelException
* if this element does not exist or if an
* exception occurs while accessing its corresponding resource
* @see org.eclipse.jdt.core.IClasspathEntry
*/
public IClasspathEntry[] getRawClasspath() throws JavaModelException {
PerProjectInfo perProjectInfo = getPerProjectInfo();
IClasspathEntry[] classpath = perProjectInfo.rawClasspath;
if (classpath != null) return classpath;
classpath = perProjectInfo.readAndCacheClasspath(this)[0];
if (classpath == JavaProject.INVALID_CLASSPATH)
return defaultClasspath();
return classpath;
}
@Override
public String[] getRequiredProjectNames() throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public boolean hasBuildState() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasClasspathCycle(IClasspathEntry[] entries) {
throw new UnsupportedOperationException();
}
@Override
public boolean isOnClasspath(IJavaElement element) {
throw new UnsupportedOperationException();
}
@Override
public boolean isOnClasspath(IResource resource) {
throw new UnsupportedOperationException();
}
@Override
public IEvaluationContext newEvaluationContext() {
throw new UnsupportedOperationException();
}
@Override
public ITypeHierarchy newTypeHierarchy(IRegion region, IProgressMonitor monitor) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public ITypeHierarchy newTypeHierarchy(IRegion region, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public ITypeHierarchy newTypeHierarchy(IType type, IRegion region, IProgressMonitor monitor) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public ITypeHierarchy newTypeHierarchy(IType type, IRegion region, WorkingCopyOwner owner, IProgressMonitor monitor)
throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public IPath readOutputLocation() {
throw new UnsupportedOperationException();
}
@Override
public IClasspathEntry[] readRawClasspath() {
throw new UnsupportedOperationException();
}
@Override
public void setOption(String optionName, String optionValue) {
// Store option value
IEclipsePreferences projectPreferences = getEclipsePreferences();
boolean modified = getJavaModelManager().storePreference(optionName, optionValue, projectPreferences, null);
// Write changes
if (modified) {
try {
projectPreferences.flush();
} catch (BackingStoreException e) {
// problem with pref store - quietly ignore
}
}
getJavaModelManager().resetProjectOptions(JavaProject.this);
JavaProject.this.resetCaches();
}
@Override
public void setOptions(Map newOptions) {
IEclipsePreferences projectPreferences = getEclipsePreferences();
if (projectPreferences == null) return;
try {
if (newOptions == null){
projectPreferences.clear();
} else {
Iterator entries = newOptions.entrySet().iterator();
JavaModelManager javaModelManager = getJavaModelManager();
while (entries.hasNext()){
Map.Entry entry = (Map.Entry) entries.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
javaModelManager.storePreference(key, value, projectPreferences, newOptions);
}
// reset to default all options not in new map
String[] pNames = projectPreferences.keys();
int ln = pNames.length;
for (int i=0; i<ln; i++) {
String key = pNames[i];
if (!newOptions.containsKey(key)) {
projectPreferences.remove(key); // old preferences => remove from preferences table
}
}
}
// persist options
projectPreferences.flush();
// flush cache immediately
try {
getPerProjectInfo().options = null;
} catch (JavaModelException e) {
// do nothing
}
} catch (BackingStoreException e) {
// problem with pref store - quietly ignore
}
}
@Override
public void setOutputLocation(IPath path, IProgressMonitor monitor) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public void setRawClasspath(IClasspathEntry[] entries, IPath outputLocation, boolean canModifyResources, IProgressMonitor monitor)
throws JavaModelException {
setRawClasspath(entries, null, outputLocation, canModifyResources, monitor);
}
@Override
public void setRawClasspath(IClasspathEntry[] entries, boolean canModifyResources, IProgressMonitor monitor) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public void setRawClasspath(IClasspathEntry[] entries, IClasspathEntry[] referencedEntries, IPath outputLocation,
IProgressMonitor monitor) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public IClasspathEntry[] getReferencedClasspathEntries() throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public void setRawClasspath(IClasspathEntry[] entries, IProgressMonitor monitor) throws JavaModelException {
setRawClasspath(
entries,
// getOutputLocation()/*don't change output*/,
null,
true/*can change resource (as per API contract)*/,
monitor);
}
@Override
public void setRawClasspath(IClasspathEntry[] entries, IPath outputLocation, IProgressMonitor monitor) throws JavaModelException {
setRawClasspath(
entries,
outputLocation,
true/*can change resource (as per API contract)*/,
monitor);
}
protected void setRawClasspath(IClasspathEntry[] newRawClasspath, IClasspathEntry[] referencedEntries, IPath newOutputLocation,
boolean canModifyResources, IProgressMonitor monitor) throws JavaModelException {
try {
if (newRawClasspath == null) //are we already with the default classpath
newRawClasspath = defaultClasspath();
SetClasspathOperation op =
new SetClasspathOperation(
this,
newRawClasspath,
referencedEntries,
newOutputLocation,
canModifyResources);
op.runOperation(monitor);
} catch (JavaModelException e) {
getJavaModelManager().getDeltaProcessor().flush();
throw e;
}
}
public String[] projectPrerequisites(IClasspathEntry[] resolvedClasspath)
throws JavaModelException {
ArrayList prerequisites = new ArrayList();
for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
IClasspathEntry entry = resolvedClasspath[i];
if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
prerequisites.add(entry.getPath().lastSegment());
}
}
int size = prerequisites.size();
if (size == 0) {
return NO_PREREQUISITES;
} else {
String[] result = new String[size];
prerequisites.toArray(result);
return result;
}
}
/**
* This is a helper method returning the resolved classpath for the project
* as a list of simple (non-variable, non-container) classpath entries.
* All classpath variable and classpath container entries in the project's
* raw classpath will be replaced by the simple classpath entries they
* resolve to.
* <p>
* The resulting resolved classpath is accurate for the given point in time.
* If the project's raw classpath is later modified, or if classpath
* variables are changed, the resolved classpath can become out of date.
* Because of this, hanging on resolved classpath is not recommended.
* </p>
* <p>
* Note that if the resolution creates duplicate entries
* (i.e. {@link IClasspathEntry entries} which are {@link Object#equals(Object)}),
* only the first one is added to the resolved classpath.
* </p>
*
* @see IClasspathEntry
*/
public IClasspathEntry[] getResolvedClasspath() throws JavaModelException {
PerProjectInfo perProjectInfo = getPerProjectInfo();
IClasspathEntry[] resolvedClasspath = perProjectInfo.getResolvedClasspath();
if (resolvedClasspath == null) {
resolveClasspath(perProjectInfo, false/*don't use previous session values*/, true/*add classpath change*/);
resolvedClasspath = perProjectInfo.getResolvedClasspath();
if (resolvedClasspath == null) {
// another thread reset the resolved classpath, use a temporary PerProjectInfo
PerProjectInfo temporaryInfo = newTemporaryInfo();
resolveClasspath(temporaryInfo, false/*don't use previous session values*/, true/*add classpath change*/);
resolvedClasspath = temporaryInfo.getResolvedClasspath();
}
}
return resolvedClasspath;
}
/*
* Resolve the given perProjectInfo's raw classpath and store the resolved classpath in the perProjectInfo.
*/
public void resolveClasspath(PerProjectInfo perProjectInfo, boolean usePreviousSession, boolean addClasspathChange) throws JavaModelException {
JavaModelManager manager = getJavaModelManager();
boolean isClasspathBeingResolved = manager.isClasspathBeingResolved(this);
try {
if (!isClasspathBeingResolved) {
manager.setClasspathBeingResolved(this, true);
}
// get raw info inside a synchronized block to ensure that it is consistent
IClasspathEntry[][] classpath = new IClasspathEntry[2][];
int timeStamp;
synchronized (perProjectInfo) {
classpath[0] = perProjectInfo.rawClasspath;
classpath[1] = perProjectInfo.referencedEntries;
// Checking null only for rawClasspath enough
if (classpath[0] == null)
classpath = perProjectInfo.readAndCacheClasspath(this);
timeStamp = perProjectInfo.rawTimeStamp;
}
ResolvedClasspath result = resolveClasspath(classpath[0], classpath[1], usePreviousSession, true/*resolve chained libraries*/);
// store resolved info along with the raw info to ensure consistency
perProjectInfo.setResolvedClasspath(result.resolvedClasspath, result.referencedEntries, result.rawReverseMap, result.rootPathToResolvedEntries, usePreviousSession ? PerProjectInfo.NEED_RESOLUTION : result.unresolvedEntryStatus, timeStamp, addClasspathChange);
} finally {
if (!isClasspathBeingResolved) {
manager.setClasspathBeingResolved(this, false);
}
}
}
public ResolvedClasspath resolveClasspath(IClasspathEntry[] rawClasspath, IClasspathEntry[] referencedEntries, boolean usePreviousSession, boolean resolveChainedLibraries) throws JavaModelException {
JavaModelManager manager = getJavaModelManager();
// ExternalFoldersManager externalFoldersManager = JavaModelManager.getExternalManager();
ResolvedClasspath result = new ResolvedClasspath();
Map knownDrives = new HashMap();
Map referencedEntriesMap = new HashMap();
List rawLibrariesPath = new ArrayList();
LinkedHashSet resolvedEntries = new LinkedHashSet();
if(resolveChainedLibraries) {
for (int index = 0; index < rawClasspath.length; index++) {
IClasspathEntry currentEntry = rawClasspath[index];
if (currentEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
rawLibrariesPath.add(ClasspathEntry.resolveDotDot(getProject().getLocation(), currentEntry.getPath()));
}
}
if (referencedEntries != null) {
// The Set is required to keep the order intact while the referencedEntriesMap (Map)
// is used to map the referenced entries with path
LinkedHashSet referencedEntriesSet = new LinkedHashSet();
for (int index = 0; index < referencedEntries.length; index++) {
IPath path = referencedEntries[index].getPath();
if (!rawLibrariesPath.contains(path) && referencedEntriesMap.get(path) == null) {
referencedEntriesMap.put(path, referencedEntries[index]);
referencedEntriesSet.add(referencedEntries[index]);
}
}
if (referencedEntriesSet.size() > 0) {
result.referencedEntries = new IClasspathEntry[referencedEntriesSet.size()];
referencedEntriesSet.toArray(result.referencedEntries);
}
}
}
int length = rawClasspath.length;
for (int i = 0; i < length; i++) {
IClasspathEntry rawEntry = rawClasspath[i];
IClasspathEntry resolvedEntry = rawEntry;
switch (rawEntry.getEntryKind()){
case IClasspathEntry.CPE_VARIABLE :
try {
resolvedEntry = manager.resolveVariableEntry(rawEntry, usePreviousSession);
} catch (ClasspathEntry.AssertionFailedException e) {
// Catch the assertion failure and set status instead
result.unresolvedEntryStatus = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage());
break;
}
if (resolvedEntry == null) {
result.unresolvedEntryStatus = new JavaModelStatus(IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, this, rawEntry.getPath());
} else {
// If the entry is already present in the rawReversetMap, it means the entry and the chained libraries
// have already been processed. So, skip it.
if (resolveChainedLibraries && resolvedEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY
&& result.rawReverseMap.get(resolvedEntry.getPath()) == null) {
// resolve Class-Path: in manifest
ClasspathEntry[] extraEntries = ((ClasspathEntry) resolvedEntry).resolvedChainedLibraries();
for (int j = 0, length2 = extraEntries.length; j < length2; j++) {
if (!rawLibrariesPath.contains(extraEntries[j].getPath())) {
// referenced entries for variable entries could also be persisted with extra attributes, so addAsChainedEntry = true
addToResult(rawEntry, extraEntries[j], result, resolvedEntries, /*externalFoldersManager*/ referencedEntriesMap, true, knownDrives);
}
}
}
addToResult(rawEntry, resolvedEntry, result, resolvedEntries, /*externalFoldersManager,*/ referencedEntriesMap, false, knownDrives);
}
break;
case IClasspathEntry.CPE_CONTAINER :
IClasspathContainer container = usePreviousSession ? manager.getPreviousSessionContainer(rawEntry.getPath(), this) : JavaCore.getClasspathContainer(rawEntry.getPath(), this);
if (container == null){
result.unresolvedEntryStatus = new JavaModelStatus(IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND, this, rawEntry.getPath());
break;
}
IClasspathEntry[] containerEntries = container.getClasspathEntries();
if (containerEntries == null) {
if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
// JavaModelManager.getJavaModelManager().verbose_missbehaving_container_null_entries(this, rawEntry.getPath());
}
break;
}
// container was bound
for (int j = 0, containerLength = containerEntries.length; j < containerLength; j++){
ClasspathEntry cEntry = (ClasspathEntry) containerEntries[j];
if (cEntry == null) {
if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
// JavaModelManager.getJavaModelManager().verbose_missbehaving_container(this, rawEntry.getPath(), containerEntries);
}
break;
}
// if container is exported or restricted, then its nested entries must in turn be exported (21749) and/or propagate restrictions
cEntry = cEntry.combineWith((ClasspathEntry) rawEntry);
if (cEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
// resolve ".." in library path
cEntry = cEntry.resolvedDotDot(getProject().getLocation());
// Do not resolve if the system attribute is set to false
if (resolveChainedLibraries
&& getJavaModelManager().resolveReferencedLibrariesForContainers
&& result.rawReverseMap.get(cEntry.getPath()) == null) {
// resolve Class-Path: in manifest
ClasspathEntry[] extraEntries = cEntry.resolvedChainedLibraries();
for (int k = 0, length2 = extraEntries.length; k < length2; k++) {
if (!rawLibrariesPath.contains(extraEntries[k].getPath())) {
addToResult(rawEntry, extraEntries[k], result, resolvedEntries, /*externalFoldersManager,*/ referencedEntriesMap, false, knownDrives);
}
}
}
}
addToResult(rawEntry, cEntry, result, resolvedEntries, /*externalFoldersManager,*/ referencedEntriesMap, false, knownDrives);
}
break;
case IClasspathEntry.CPE_LIBRARY:
// resolve ".." in library path
resolvedEntry = ((ClasspathEntry) rawEntry).resolvedDotDot(getProject().getLocation());
if (resolveChainedLibraries && result.rawReverseMap.get(resolvedEntry.getPath()) == null) {
// resolve Class-Path: in manifest
ClasspathEntry[] extraEntries = ((ClasspathEntry) resolvedEntry).resolvedChainedLibraries();
for (int k = 0, length2 = extraEntries.length; k < length2; k++) {
if (!rawLibrariesPath.contains(extraEntries[k].getPath())) {
addToResult(rawEntry, extraEntries[k], result, resolvedEntries, /*externalFoldersManager,*/ referencedEntriesMap, true, knownDrives);
}
}
}
addToResult(rawEntry, resolvedEntry, result, resolvedEntries, /*externalFoldersManager,*/ referencedEntriesMap, false, knownDrives);
break;
default :
addToResult(rawEntry, resolvedEntry, result, resolvedEntries,/* externalFoldersManager,*/ referencedEntriesMap, false, knownDrives);
break;
}
}
result.resolvedClasspath = new IClasspathEntry[resolvedEntries.size()];
resolvedEntries.toArray(result.resolvedClasspath);
return result;
}
/*
* Returns a PerProjectInfo that doesn't register classpath change
* and that should be used as a temporary info.
*/
public PerProjectInfo newTemporaryInfo() {
return
new PerProjectInfo(this.project.getProject()) {
protected ClasspathChange addClasspathChange() {
return null;
}
};
}
/**
* Returns the classpath entry that refers to the given path
* or <code>null</code> if there is no reference to the path.
*
* @param path
* IPath
* @return IClasspathEntry
* @throws JavaModelException
*/
public IClasspathEntry getClasspathEntryFor(IPath path) throws JavaModelException {
getResolvedClasspath(); // force resolution
PerProjectInfo perProjectInfo = getPerProjectInfo();
if (perProjectInfo == null)
return null;
Map rootPathToResolvedEntries = perProjectInfo.rootPathToResolvedEntries;
if (rootPathToResolvedEntries == null)
return null;
IClasspathEntry classpathEntry = (IClasspathEntry) rootPathToResolvedEntries.get(path);
if (classpathEntry == null) {
path = getProject().getWorkspace().getRoot().getLocation().append(path);
classpathEntry = (IClasspathEntry) rootPathToResolvedEntries.get(path);
}
return classpathEntry;
}
@Override
public IJavaElement findElement(IPath path) throws JavaModelException {
return findElement(path, DefaultWorkingCopyOwner.PRIMARY);
}
@Override
public IJavaElement findElement(IPath path, WorkingCopyOwner owner) throws JavaModelException {
if (path == null || path.isAbsolute()) {
throw new JavaModelException(
new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, path));
}
try {
String extension = path.getFileExtension();
if (extension == null) {
String packageName = path.toString().replace(IPath.SEPARATOR, '.');
return findPackageFragment(packageName);
} else if (Util.isJavaLikeFileName(path.lastSegment())
|| extension.equalsIgnoreCase(SuffixConstants.EXTENSION_class)) {
IPath packagePath = path.removeLastSegments(1);
String packageName = packagePath.toString().replace(IPath.SEPARATOR, '.');
String typeName = path.lastSegment();
typeName = typeName.substring(0, typeName.length() - extension.length() - 1);
String qualifiedName = null;
if (packageName.length() > 0) {
qualifiedName = packageName + "." + typeName; //$NON-NLS-1$
} else {
qualifiedName = typeName;
}
// lookup type
NameLookup lookup = newNameLookup(owner);
NameLookup.Answer answer = lookup.findType(
qualifiedName,
false,
NameLookup.ACCEPT_ALL,
true/* consider secondary types */,
false/* do NOT wait for indexes */,
false/*don't check restrictions*/,
null);
if (answer != null) {
return answer.type.getParent();
} else {
return null;
}
} else {
// unsupported extension
return null;
}
} catch (JavaModelException e) {
if (e.getStatus().getCode()
== IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) {
return null;
} else {
throw e;
}
}
}
@Override
public IJavaElement findElement(String bindingKey, WorkingCopyOwner owner) throws JavaModelException {
JavaElementFinder elementFinder = new JavaElementFinder(bindingKey, this, owner);
elementFinder.parse();
if (elementFinder.exception != null)
throw elementFinder.exception;
return elementFinder.element;
}
public IJavaElement findPackageFragment(String packageName)
throws JavaModelException {
NameLookup lookup = newNameLookup((WorkingCopyOwner)null/*no need to look at working copies for pkgs*/);
IPackageFragment[] pkgFragments = lookup.findPackageFragments(packageName, false);
if (pkgFragments == null) {
return null;
} else {
// try to return one that is a child of this project
for (int i = 0, length = pkgFragments.length; i < length; i++) {
IPackageFragment pkgFragment = pkgFragments[i];
if (equals(pkgFragment.getParent().getParent())) {
return pkgFragment;
}
}
// default to the first one
return pkgFragments[0];
}
}
@Override
public IPackageFragment findPackageFragment(IPath path) throws JavaModelException {
return findPackageFragment0(path);
}
private IPackageFragment findPackageFragment0(IPath path)
throws JavaModelException {
NameLookup lookup = newNameLookup((WorkingCopyOwner)null/*no need to look at working copies for pkgs*/);
return lookup.findPackageFragment(path);
}
@Override
public IPackageFragmentRoot findPackageFragmentRoot(IPath path) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public IPackageFragmentRoot[] findPackageFragmentRoots(IClasspathEntry entry) {
throw new UnsupportedOperationException();
}
@Override
public IType findType(String fullyQualifiedName) throws JavaModelException {
return findType(fullyQualifiedName, DefaultWorkingCopyOwner.PRIMARY);
}
@Override
public IType findType(String fullyQualifiedName, IProgressMonitor progressMonitor) throws JavaModelException {
return findType(fullyQualifiedName, DefaultWorkingCopyOwner.PRIMARY, progressMonitor);
}
/*
* Internal findType with instanciated name lookup
*/
IType findType(String fullyQualifiedName, NameLookup lookup, boolean considerSecondaryTypes, IProgressMonitor progressMonitor)
throws JavaModelException {
NameLookup.Answer answer = lookup.findType(
fullyQualifiedName,
false,
org.eclipse.jdt.internal.core.NameLookup.ACCEPT_ALL,
considerSecondaryTypes,
true, /* wait for indexes (only if consider secondary types)*/
false/*don't check restrictions*/,
progressMonitor);
if (answer == null) {
// try to find enclosing type
int lastDot = fullyQualifiedName.lastIndexOf('.');
if (lastDot == -1) return null;
IType type = findType(fullyQualifiedName.substring(0, lastDot), lookup, considerSecondaryTypes, progressMonitor);
if (type != null) {
type = type.getType(fullyQualifiedName.substring(lastDot + 1));
if (!type.exists()) {
return null;
}
}
return type;
}
return answer.type;
}
@Override
public IType findType(String fullyQualifiedName, WorkingCopyOwner owner) throws JavaModelException {
NameLookup lookup = newNameLookup(owner);
return findType(fullyQualifiedName, lookup, false, null);
}
@Override
public IType findType(String fullyQualifiedName, WorkingCopyOwner owner, IProgressMonitor progressMonitor) throws JavaModelException {
NameLookup lookup = newNameLookup(owner);
return findType(fullyQualifiedName, lookup, true, progressMonitor);
}
@Override
public IType findType(String packageName, String typeQualifiedName) throws JavaModelException {
return findType(packageName, typeQualifiedName, DefaultWorkingCopyOwner.PRIMARY);
}
@Override
public IType findType(String packageName, String typeQualifiedName, IProgressMonitor progressMonitor) throws JavaModelException {
return findType(packageName, typeQualifiedName, DefaultWorkingCopyOwner.PRIMARY, progressMonitor);
}
@Override
public IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner) throws JavaModelException {
NameLookup lookup = newNameLookup(owner);
return findType(
packageName,
typeQualifiedName,
lookup,
false, // do not consider secondary types
null);
}
@Override
public IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner, IProgressMonitor progressMonitor)
throws JavaModelException {
NameLookup lookup = newNameLookup(owner);
return findType(
packageName,
typeQualifiedName,
lookup,
true, // consider secondary types
progressMonitor);
}
/*
* Internal findType with instanciated name lookup
*/
IType findType(String packageName, String typeQualifiedName, NameLookup lookup, boolean considerSecondaryTypes,
IProgressMonitor progressMonitor) throws JavaModelException {
NameLookup.Answer answer = lookup.findType(
typeQualifiedName,
packageName,
false,
NameLookup.ACCEPT_ALL,
considerSecondaryTypes,
true, // wait for indexes (in case we need to consider secondary types)
false/*don't check restrictions*/,
progressMonitor);
return answer == null ? null : answer.type;
}
/*
* Returns a new name lookup. This name lookup first looks in the working copies of the given owner.
*/
public NameLookup newNameLookup(WorkingCopyOwner owner) throws JavaModelException {
JavaModelManager manager = getJavaModelManager();
ICompilationUnit[] workingCopies = owner == null ? null : manager.getWorkingCopies(owner, true/*add primary WCs*/);
return newNameLookup(workingCopies);
}
@Override
public IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException {
return getAllPackageFragmentRoots(null /*no reverse map*/);
}
public IPackageFragmentRoot[] getAllPackageFragmentRoots(Map rootToResolvedEntries) throws JavaModelException {
return computePackageFragmentRoots(getResolvedClasspath(), true/*retrieveExportedRoots*/, rootToResolvedEntries);
}
/**
* Returns (local/all) the package fragment roots identified by the given project's classpath.
* Note: this follows project classpath references to find required project contributions,
* eliminating duplicates silently.
* Only works with resolved entries
*
* @param resolvedClasspath
* IClasspathEntry[]
* @param retrieveExportedRoots
* boolean
* @return IPackageFragmentRoot[]
* @throws JavaModelException
*/
public IPackageFragmentRoot[] computePackageFragmentRoots(
IClasspathEntry[] resolvedClasspath,
boolean retrieveExportedRoots,
Map rootToResolvedEntries) throws JavaModelException {
ObjectVector accumulatedRoots = new ObjectVector();
computePackageFragmentRoots(
resolvedClasspath,
accumulatedRoots,
new HashSet(5), // rootIDs
null, // inside original project
retrieveExportedRoots,
rootToResolvedEntries);
IPackageFragmentRoot[] rootArray = new IPackageFragmentRoot[accumulatedRoots.size()];
accumulatedRoots.copyInto(rootArray);
return rootArray;
}
/**
* Returns (local/all) the package fragment roots identified by the given project's classpath.
* Note: this follows project classpath references to find required project contributions,
* eliminating duplicates silently.
* Only works with resolved entries
*
* @param resolvedClasspath
* IClasspathEntry[]
* @param accumulatedRoots
* ObjectVector
* @param rootIDs
* HashSet
* @param referringEntry
* project entry referring to this CP or null if initial project
* @param retrieveExportedRoots
* boolean
* @throws JavaModelException
*/
public void computePackageFragmentRoots(
IClasspathEntry[] resolvedClasspath,
ObjectVector accumulatedRoots,
HashSet rootIDs,
IClasspathEntry referringEntry,
boolean retrieveExportedRoots,
Map rootToResolvedEntries) throws JavaModelException {
if (referringEntry == null) {
rootIDs.add(rootID());
}
for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
computePackageFragmentRoots(
resolvedClasspath[i],
accumulatedRoots,
rootIDs,
referringEntry,
retrieveExportedRoots,
rootToResolvedEntries);
}
}
/**
* Reads the classpath file entries of this project's .classpath file.
* Returns a two-dimensional array, where the number of elements in the row is fixed to 2.
* The first element is an array of raw classpath entries, which includes the output entry,
* and the second element is an array of referenced entries that may have been stored
* by the client earlier.
* See {@link IJavaProject#getReferencedClasspathEntries()} for more details.
* As a side effect, unknown elements are stored in the given map (if not null)
* Throws exceptions if the file cannot be accessed or is malformed.
*/
public IClasspathEntry[][] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, ClasspathEntry.AssertionFailedException {
IFile rscFile = this.project.getFile(org.eclipse.jdt.internal.core.JavaProject.CLASSPATH_FILENAME);
byte[] bytes;
if (rscFile.exists()) {
bytes = Util.getResourceContentsAsByteArray(rscFile);
} else {
// when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible
// so default to using java.io.File
URI location = rscFile.getLocationURI();
if (location == null)
throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$
File file = Util.toLocalFile(location, null/*no progress monitor available*/);
if (file == null)
throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$
try {
bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file);
} catch (IOException e) {
if (!file.exists())
return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES};
throw e;
}
}
if (hasUTF8BOM(bytes)) {
int length = bytes.length- IContentDescription.BOM_UTF_8.length;
System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length);
}
String xmlClasspath;
try {
xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8
} catch (UnsupportedEncodingException e) {
Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$
// fallback to default
xmlClasspath = new String(bytes);
}
return decodeClasspath(xmlClasspath, unknownElements);
}
/**
* Reads and decode an XML classpath string. Returns a two-dimensional array, where the number of elements in the row is fixed to 2.
* The first element is an array of raw classpath entries and the second element is an array of referenced entries that may have been stored
* by the client earlier. See {@link IJavaProject#getReferencedClasspathEntries()} for more details.
*
*/
public IClasspathEntry[][] decodeClasspath(String xmlClasspath, Map unknownElements) throws IOException, ClasspathEntry.AssertionFailedException {
ArrayList paths = new ArrayList();
IClasspathEntry defaultOutput = null;
StringReader reader = new StringReader(xmlClasspath);
Element cpElement;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
} catch (SAXException e) {
throw new IOException(Messages.file_badFormat);
} catch (ParserConfigurationException e) {
throw new IOException(Messages.file_badFormat);
} finally {
reader.close();
}
if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) { //$NON-NLS-1$
throw new IOException(Messages.file_badFormat);
}
NodeList list = cpElement.getElementsByTagName(ClasspathEntry.TAG_CLASSPATHENTRY);
int length = list.getLength();
for (int i = 0; i < length; ++i) {
Node node = list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements);
if (entry != null){
if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) {
defaultOutput = entry; // separate output
} else {
paths.add(entry);
}
}
}
}
int pathSize = paths.size();
IClasspathEntry[][] entries = new IClasspathEntry[2][];
entries[0] = new IClasspathEntry[pathSize + (defaultOutput == null ? 0 : 1)];
paths.toArray(entries[0]);
if (defaultOutput != null) entries[0][pathSize] = defaultOutput; // ensure output is last item
paths.clear();
list = cpElement.getElementsByTagName(ClasspathEntry.TAG_REFERENCED_ENTRY);
length = list.getLength();
for (int i = 0; i < length; ++i) {
Node node = list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements);
if (entry != null){
paths.add(entry);
}
}
}
entries[1] = new IClasspathEntry[paths.size()];
paths.toArray(entries[1]);
return entries;
}
public IClasspathEntry decodeClasspathEntry(String encodedEntry) {
try {
if (encodedEntry == null) return null;
StringReader reader = new StringReader(encodedEntry);
Element node;
try {
DocumentBuilder parser =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
node = parser.parse(new InputSource(reader)).getDocumentElement();
} catch (SAXException e) {
return null;
} catch (ParserConfigurationException e) {
return null;
} finally {
reader.close();
}
if (!node.getNodeName().equalsIgnoreCase(ClasspathEntry.TAG_CLASSPATHENTRY)
|| node.getNodeType() != Node.ELEMENT_NODE) {
return null;
}
return ClasspathEntry.elementDecode(node, this, null/*not interested in unknown elements*/);
} catch (IOException e) {
// bad format
return null;
}
}
/**
* Returns a default class path.
* This is the root of the project
*/
protected IClasspathEntry[] defaultClasspath() {
return new IClasspathEntry[] {
JavaCore.newSourceEntry(this.project.getFullPath())};
}
public int hashCode() {
return this.project.hashCode();
}
private boolean hasUTF8BOM(byte[] bytes) {
if (bytes.length > IContentDescription.BOM_UTF_8.length) {
for (int i = 0, length = IContentDescription.BOM_UTF_8.length; i < length; i++) {
if (IContentDescription.BOM_UTF_8[i] != bytes[i])
return false;
}
return true;
}
return false;
}
/**
* Returns the package fragment roots identified by the given entry. In case it refers to
* a project, it will follow its classpath so as to find exported roots as well.
* Only works with resolved entry
*
* @param resolvedEntry
* IClasspathEntry
* @param accumulatedRoots
* ObjectVector
* @param rootIDs
* HashSet
* @param referringEntry
* the CP entry (project) referring to this entry, or null if initial project
* @param retrieveExportedRoots
* boolean
* @throws JavaModelException
*/
public void computePackageFragmentRoots(
IClasspathEntry resolvedEntry,
ObjectVector accumulatedRoots,
HashSet rootIDs,
IClasspathEntry referringEntry,
boolean retrieveExportedRoots,
Map rootToResolvedEntries) throws JavaModelException {
String rootID = ((ClasspathEntry)resolvedEntry).rootID();
if (rootIDs.contains(rootID)) return;
IPath projectPath = this.project.getFullPath();
IPath entryPath = resolvedEntry.getPath();
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IPackageFragmentRoot root = null;
switch (resolvedEntry.getEntryKind()) {
// source folder
case IClasspathEntry.CPE_SOURCE:
if (projectPath.isPrefixOf(entryPath)) {
Object target = getTarget(entryPath, true/*check existency*/);
if (target == null) return;
if (target instanceof IFolder || target instanceof IProject) {
root = getPackageFragmentRoot((IResource)target);
}
}
break;
// internal/external JAR or folder
case IClasspathEntry.CPE_LIBRARY:
if (referringEntry != null && !resolvedEntry.isExported())
return;
Object target = getTarget(entryPath, true/*check existency*/);
if (target == null)
return;
if (target instanceof IResource){
// // internal target
root = getPackageFragmentRoot((IResource) target, entryPath);
} else
if (target instanceof File) {
// external target
if (isFile(target)) {
root = new JarPackageFragmentRoot(entryPath, this);
} else if (((File)target).isDirectory()) {
// root = getPackageFragmentRoot((File)target, entryPath);
// root = new ExternalPackageFragmentRoot(entryPath, this);
throw new UnsupportedOperationException();
}
}
break;
// recurse into required project
case IClasspathEntry.CPE_PROJECT:
if (!retrieveExportedRoots) return;
if (referringEntry != null && !resolvedEntry.isExported()) return;
IResource member = workspaceRoot.findMember(entryPath);
if (member != null && member.getType() == IResource.PROJECT) {// double check if bound to project (23977)
IProject requiredProjectRsc = (IProject)member;
if (org.eclipse.jdt.internal.core.JavaProject.hasJavaNature(requiredProjectRsc)) { // special builder binary output
rootIDs.add(rootID);
org.eclipse.jdt.internal.core.JavaProject requiredProject = (org.eclipse.jdt.internal.core.JavaProject)JavaCore.create(requiredProjectRsc);
requiredProject.computePackageFragmentRoots(
requiredProject.getResolvedClasspath(),
accumulatedRoots,
rootIDs,
rootToResolvedEntries == null ? resolvedEntry
: ((ClasspathEntry)resolvedEntry)
.combineWith((ClasspathEntry)referringEntry),
// only combine if need to build the reverse map
retrieveExportedRoots,
rootToResolvedEntries);
}
break;
}
}
if (root != null) {
accumulatedRoots.add(root);
rootIDs.add(rootID);
if (rootToResolvedEntries != null) rootToResolvedEntries
.put(root, ((ClasspathEntry)resolvedEntry).combineWith((ClasspathEntry)referringEntry));
}
}
/**
* @see IJavaProject
*/
public IPackageFragmentRoot getPackageFragmentRoot(IResource resource) {
return getPackageFragmentRoot(resource, null/*no entry path*/);
}
private IPackageFragmentRoot getPackageFragmentRoot(IResource resource, IPath entryPath) {
switch (resource.getType()) {
case IResource.FILE:
return new JarPackageFragmentRoot(resource, this);
case IResource.FOLDER:
// if (ExternalFoldersManager.isInternalPathForExternalFolder(resource.getFullPath()))
// return new ExternalPackageFragmentRoot(resource, entryPath, this);
return new PackageFragmentRoot(resource, this);
case IResource.PROJECT:
return new PackageFragmentRoot(resource, this);
default:
return null;
}
}
/**
* Answers an ID which is used to distinguish project/entries during package
* fragment root computations
*
* @return String
*/
public String rootID() {
return "[PRJ]" + this.project.getFullPath(); //$NON-NLS-1$
}
@Override
public Object[] getNonJavaResources() throws JavaModelException {
return ((JavaProjectElementInfo) getElementInfo()).getNonJavaResources(this);
}
@Override
public String getOption(String optionName, boolean inheritJavaCoreOptions) {
return getJavaModelManager().getOption(optionName, inheritJavaCoreOptions, getEclipsePreferences());
}
public Map getOptions(boolean inheritJavaCoreOptions) {
// initialize to the defaults from JavaCore options pool
Map options = inheritJavaCoreOptions ? JavaCore.getOptions() : new Hashtable(5);
// Get project specific options
PerProjectInfo perProjectInfo = null;
Hashtable projectOptions = null;
JavaModelManager javaModelManager = getJavaModelManager();
HashSet optionNames = javaModelManager.optionNames;
try {
perProjectInfo = getPerProjectInfo();
projectOptions = perProjectInfo.options;
if (projectOptions == null) {
// get eclipse preferences
IEclipsePreferences projectPreferences= getEclipsePreferences();
if (projectPreferences == null) return options; // cannot do better (non-Java project)
// create project options
String[] propertyNames = projectPreferences.keys();
projectOptions = new Hashtable(propertyNames.length);
for (int i = 0; i < propertyNames.length; i++){
String propertyName = propertyNames[i];
String value = projectPreferences.get(propertyName, null);
if (value != null) {
value = value.trim();
// Keep the option value, even if it's deprecated
projectOptions.put(propertyName, value);
if (!optionNames.contains(propertyName)) {
// try to migrate deprecated options
String[] compatibleOptions = (String[]) javaModelManager.deprecatedOptions.get(propertyName);
if (compatibleOptions != null) {
for (int co=0, length=compatibleOptions.length; co < length; co++) {
String compatibleOption = compatibleOptions[co];
if (!projectOptions.containsKey(compatibleOption))
projectOptions.put(compatibleOption, value);
}
}
}
}
}
// cache project options
perProjectInfo.options = projectOptions;
}
} catch (JavaModelException jme) {
projectOptions = new Hashtable();
} catch (BackingStoreException e) {
projectOptions = new Hashtable();
}
// Inherit from JavaCore options if specified
if (inheritJavaCoreOptions) {
Iterator propertyNames = projectOptions.entrySet().iterator();
while (propertyNames.hasNext()) {
Map.Entry entry = (Map.Entry) propertyNames.next();
String propertyName = (String) entry.getKey();
String propertyValue = (String) entry.getValue();
if (propertyValue != null && javaModelManager.knowsOption(propertyName)){
options.put(propertyName, propertyValue.trim());
}
}
Util.fixTaskTags(options);
return options;
}
Util.fixTaskTags(projectOptions);
return projectOptions;
}
@Override
public IPath getOutputLocation() throws JavaModelException {
return defaultOutputLocation();
}
/**
* Returns a default output location.
* This is the project bin folder
*/
protected IPath defaultOutputLocation() {
return this.project.getFullPath().append("bin"); //$NON-NLS-1$
}
@Override
public IPackageFragmentRoot getPackageFragmentRoot(String externalLibraryPath) {
return new JarPackageFragmentRoot(new Path(externalLibraryPath), this);
}
@Override
public IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException {
Object[] children;
int length;
IPackageFragmentRoot[] roots;
System.arraycopy(
children = getChildren(),
0,
roots = new IPackageFragmentRoot[length = children.length],
0,
length);
return roots;
}
@Override
public IPackageFragmentRoot[] getPackageFragmentRoots(IClasspathEntry entry) {
throw new UnsupportedOperationException();
}
@Override
public IPackageFragment[] getPackageFragments() throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public IProject getProject() {
return project;
}
@Override
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource)
throws JavaModelException {
// cannot refresh cp markers on opening (emulate cp check on startup) since can create deadlocks (see bug 37274)
IClasspathEntry[] resolvedClasspath = getResolvedClasspath();
// compute the pkg fragment roots
info.setChildren(computePackageFragmentRoots(resolvedClasspath, true, null /*no reverse map*/));
// JavaModelManager.getIndexManager().indexAll(project);
return true;
}
/*
* Returns whether the given resource is accessible through the children or the non-Java resources of this project.
* Returns true if the resource is not in the project.
* Assumes that the resource is a folder or a file.
*/
public boolean contains(IResource resource) {
return true;
}
// @Override
// public IJavaElement getAncestor(int ancestorType) {
// return null;
// @Override
// public boolean exists() {
// return false;
@Override
public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaModelException {
return null;
}
@Override
public IResource getCorrespondingResource() throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public String getElementName() {
return project.getName();
}
/*
* no path canonicalization
*/
public IPackageFragmentRoot getPackageFragmentRoot0(IPath externalLibraryPath) {
// IFolder linkedFolder = JavaModelManager.getExternalManager().getFolder(externalLibraryPath);
// if (linkedFolder != null)
// return new ExternalPackageFragmentRoot(linkedFolder, externalLibraryPath, this);
return new JarPackageFragmentRoot(externalLibraryPath, this);
}
/**
* @param path IPath
* @return A handle to the package fragment root identified by the given path.
* This method is handle-only and the element may or may not exist. Returns
* <code>null</code> if unable to generate a handle from the path (for example,
* an absolute path that has less than 1 segment. The path may be relative or
* absolute.
*/
public IPackageFragmentRoot getPackageFragmentRoot(IPath path) {
if (!path.isAbsolute()) {
path = getPath().append(path);
}
int segmentCount = path.segmentCount();
if (segmentCount == 0) {
return null;
}
if (path.getDevice() != null || JavaModel.getExternalTarget(path, true/*check existence*/) != null) {
// external path
return getPackageFragmentRoot0(path);
}
IWorkspaceRoot workspaceRoot = this.project.getWorkspace().getRoot();
IResource resource = workspaceRoot.findMember(path);
if (resource == null) {
// resource doesn't exist in workspace
if (path.getFileExtension() != null) {
if (!workspaceRoot.getProject(path.segment(0)).exists()) {
// assume it is an external ZIP archive
return getPackageFragmentRoot0(path);
} else {
// assume it is an internal ZIP archive
resource = workspaceRoot.getFile(path);
}
} else if (segmentCount == 1) {
// assume it is a project
String projectName = path.segment(0);
if (getElementName().equals(projectName)) {
// default root
resource = this.project;
} else {
// lib being another project
resource = workspaceRoot.getProject(projectName);
}
} else {
// assume it is an internal folder
resource = workspaceRoot.getFolder(path);
}
}
return getPackageFragmentRoot(resource);
}
@Override
public IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) {
switch (token.charAt(0)) {
case JavaElement.JEM_PACKAGEFRAGMENTROOT:
String rootPath = IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH;
token = null;
while (memento.hasMoreTokens()) {
token = memento.nextToken();
if (token == MementoTokenizer.PACKAGEFRAGMENT || token == MementoTokenizer.COUNT) {
break;
}
rootPath += token;
}
JavaElement root = (JavaElement)getPackageFragmentRoot(new Path(rootPath));
if (token != null && token.charAt(0) == JavaElement.JEM_PACKAGEFRAGMENT) {
return root.getHandleFromMemento(token, memento, owner);
} else {
return root.getHandleFromMemento(memento, owner);
}
}
return null;
}
@Override
public int getElementType() {
return IJavaElement.JAVA_PROJECT;
}
@Override
protected char getHandleMementoDelimiter() {
return JavaElement.JEM_JAVAPROJECT;
}
public IPath getPath() {
return project.getFullPath();
}
@Override
public IJavaElement getPrimaryElement() {
throw new UnsupportedOperationException();
}
@Override
protected IResource resource(PackageFragmentRoot root) {
return project;
}
@Override
public ISchedulingRule getSchedulingRule() {
throw new UnsupportedOperationException();
}
@Override
public IResource getUnderlyingResource() throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public Object getAdapter(Class aClass) {
throw new UnsupportedOperationException();
}
@Override
public void close() throws JavaModelException {
super.close();
}
@Override
public String findRecommendedLineSeparator() throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public IBuffer getBuffer() throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public boolean hasUnsavedChanges() throws JavaModelException {
throw new UnsupportedOperationException();
}
// @Override
// public boolean isOpen() {
// throw new UnsupportedOperationException();
@Override
public void makeConsistent(IProgressMonitor progress) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public void open(IProgressMonitor progress) throws JavaModelException {
throw new UnsupportedOperationException();
}
@Override
public void save(IProgressMonitor progress, boolean force) throws JavaModelException {
throw new UnsupportedOperationException();
}
/**
* The path is known to match a source/library folder entry.
*
* @param path
* IPath
* @return IPackageFragmentRoot
*/
public IPackageFragmentRoot getFolderPackageFragmentRoot(IPath path) {
if (path.segmentCount() == 1) { // default project root
return getPackageFragmentRoot();
}
return getPackageFragmentRoot(this.project.getWorkspace().getRoot().getFolder(path));
}
public JavaProjectElementInfo.ProjectCache getProjectCache() throws JavaModelException {
return ((JavaProjectElementInfo)getElementInfo()).getProjectCache(this);
}
/**
* Returns a new element info for this element.
*/
protected Object createElementInfo() {
return new JavaProjectElementInfo();
}
@Override
protected IStatus validateExistence(IResource underlyingResource) {
if ((!((IProject)underlyingResource).getFolder(INNER_DIR).exists())) {
return newDoesNotExistStatus();
}
return JavaModelStatus.VERIFIED_OK;
}
protected JavaModelStatus newDoesNotExistStatus() {
return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this);
}
// /**
// * @see JavaElement#getHandleMemento(StringBuffer)
// */
// protected void getHandleMemento(StringBuffer buff) {
//// buff.append(getElementName());
/*
* Resets this project's caches
*/
public void resetCaches() {
JavaProjectElementInfo
info = (JavaProjectElementInfo) getJavaModelManager().peekAtInfo(this);
if (info != null){
info.resetCaches();
}
}
private void addToResult(IClasspathEntry rawEntry, IClasspathEntry resolvedEntry, ResolvedClasspath result,
LinkedHashSet resolvedEntries,
Map oldChainedEntriesMap, boolean addAsChainedEntry, Map knownDrives) {
IPath resolvedPath;
// If it's already been resolved, do not add to resolvedEntries
if (result.rawReverseMap.get(resolvedPath = resolvedEntry.getPath()) == null) {
result.rawReverseMap.put(resolvedPath, rawEntry);
result.rootPathToResolvedEntries.put(resolvedPath, resolvedEntry);
resolvedEntries.add(resolvedEntry);
if (addAsChainedEntry) {
IClasspathEntry chainedEntry = null;
chainedEntry = (ClasspathEntry) oldChainedEntriesMap.get(resolvedPath);
if (chainedEntry != null) {
// This is required to keep the attributes if any added by the user in
// the previous session such as source attachment path etc.
copyFromOldChainedEntry((ClasspathEntry) resolvedEntry, (ClasspathEntry) chainedEntry);
}
}
}
// if (resolvedEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY &&/* ExternalFoldersManager.isExternalFolderPath(resolvedPath)*/ false) {
// externalFoldersManager.addFolder(resolvedPath, true/*scheduleForCreation*/); // no-op if not an external folder or if already registered
// // The source attachment path could be external too and in which case, must be added.
// IPath sourcePath = resolvedEntry.getSourceAttachmentPath();
// if (sourcePath != null && driveExists(sourcePath, knownDrives) && ExternalFoldersManager.isExternalFolderPath(sourcePath)) {
// externalFoldersManager.addFolder(sourcePath, true);
}
private void copyFromOldChainedEntry(ClasspathEntry resolvedEntry, ClasspathEntry chainedEntry) {
IPath path = chainedEntry.getSourceAttachmentPath();
if ( path != null) {
resolvedEntry.sourceAttachmentPath = path;
}
path = chainedEntry.getSourceAttachmentRootPath();
if (path != null) {
resolvedEntry.sourceAttachmentRootPath = path;
}
IClasspathAttribute[] attributes = chainedEntry.getExtraAttributes();
if (attributes != null) {
resolvedEntry.extraAttributes = attributes;
}
}
/**
* Convenience method that returns the specific type of info for a Java project.
*/
protected JavaProjectElementInfo getJavaProjectElementInfo()
throws JavaModelException {
return (JavaProjectElementInfo)getElementInfo();
}
public NameLookup newNameLookup(ICompilationUnit[] workingCopies) throws JavaModelException {
return getJavaProjectElementInfo().newNameLookup(this, workingCopies);
}
public SearchableEnvironment newSearchableNameEnvironment(ICompilationUnit[] workingCopies) throws JavaModelException {
return new SearchableEnvironment(this, workingCopies);
}
/**
* Returns true if this handle represents the same Java project
* as the given handle. Two handles represent the same
* project if they are identical or if they represent a project with
* the same underlying resource and occurrence counts.
*
* @see JavaElement#equals(Object)
*/
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof org.eclipse.jdt.internal.core.JavaProject))
return false;
org.eclipse.jdt.internal.core.JavaProject other = (org.eclipse.jdt.internal.core.JavaProject) o;
return this.project.equals(other.getProject());
}
public PerProjectInfo getPerProjectInfo() throws JavaModelException {
return getJavaModelManager().getPerProjectInfoCheckExistence(this.project);
}
/*
* Returns a new search name environment for this project. This name environment first looks in the working copies
* of the given owner.
*/
public SearchableEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaModelException {
return new SearchableEnvironment(this, owner);
}
/**
* This is a helper method returning the expanded classpath for the project, as a list of classpath entries,
* where all classpath variable entries have been resolved and substituted with their final target entries.
* All project exports have been appended to project entries.
* @return IClasspathEntry[]
* @throws JavaModelException
*/
public IClasspathEntry[] getExpandedClasspath() throws JavaModelException {
// ObjectVector accumulatedEntries = new ObjectVector();
// computeExpandedClasspath(null, new HashSet(5), accumulatedEntries);
// IClasspathEntry[] expandedPath = new IClasspathEntry[accumulatedEntries.size()];
// accumulatedEntries.copyInto(expandedPath);
// return expandedPath;
return getResolvedClasspath();
}
/**
* Returns the project custom preference pool.
* Project preferences may include custom encoding.
* @return IEclipsePreferences or <code>null</code> if the project
* does not have a java nature.
*/
public IEclipsePreferences getEclipsePreferences() {
if (!org.eclipse.jdt.internal.core.JavaProject.hasJavaNature(this.project)) return null;
// Get cached preferences if exist
PerProjectInfo perProjectInfo = getJavaModelManager().getPerProjectInfo(this.project, true);
if (perProjectInfo.preferences != null) return perProjectInfo.preferences;
// Init project preferences
IScopeContext context = new ProjectScope(getProject());
final IEclipsePreferences eclipsePreferences = context.getNode(JavaCore.PLUGIN_ID);
// updatePreferences(eclipsePreferences);
perProjectInfo.preferences = eclipsePreferences;
// // Listen to new preferences node
// final IEclipsePreferences eclipseParentPreferences = (IEclipsePreferences) eclipsePreferences.parent();
// if (eclipseParentPreferences != null) {
// if (this.preferencesNodeListener != null) {
// eclipseParentPreferences.removeNodeChangeListener(this.preferencesNodeListener);
// this.preferencesNodeListener = new IEclipsePreferences.INodeChangeListener() {
// public void added(IEclipsePreferences.NodeChangeEvent event) {
// // do nothing
// public void removed(IEclipsePreferences.NodeChangeEvent event) {
// if (event.getChild() == eclipsePreferences) {
// JavaModelManager.getJavaModelManager().resetProjectPreferences(JavaProject.this);
// eclipseParentPreferences.addNodeChangeListener(this.preferencesNodeListener);
// // Listen to preferences changes
// if (this.preferencesChangeListener != null) {
// eclipsePreferences.removePreferenceChangeListener(this.preferencesChangeListener);
// this.preferencesChangeListener = new IEclipsePreferences.IPreferenceChangeListener() {
// public void preferenceChange(IEclipsePreferences.PreferenceChangeEvent event) {
// String propertyName = event.getKey();
// JavaModelManager manager = JavaModelManager.getJavaModelManager();
// if (propertyName.startsWith(JavaCore.PLUGIN_ID)) {
// if (propertyName.equals(JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER) ||
// propertyName.equals(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER) ||
// propertyName.equals(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE) ||
// propertyName.equals(JavaCore.CORE_JAVA_BUILD_RECREATE_MODIFIED_CLASS_FILES_IN_OUTPUT_FOLDER) ||
// propertyName.equals(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH) ||
// propertyName.equals(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS) ||
// propertyName.equals(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS) ||
// propertyName.equals(JavaCore.CORE_INCOMPLETE_CLASSPATH) ||
// propertyName.equals(JavaCore.CORE_CIRCULAR_CLASSPATH) ||
// propertyName.equals(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE) ||
// propertyName.equals(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL) ||
// propertyName.equals(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM))
// manager.deltaState.addClasspathValidation(JavaProject.this);
// manager.resetProjectOptions(JavaProject.this);
// eclipsePreferences.addPreferenceChangeListener(this.preferencesChangeListener);
return eclipsePreferences;
}
/**
* Returns a canonicalized path from the given external path.
* Note that the return path contains the same number of segments
* and it contains a device only if the given path contained one.
* @param externalPath IPath
* @see java.io.File for the definition of a canonicalized path
* @return IPath
*/
public static IPath canonicalizedPath(IPath externalPath) {
if (externalPath == null)
return null;
if (IS_CASE_SENSITIVE) {
return externalPath;
}
// if not external path, return original path
IWorkspace workspace = ResourcesPlugin.getWorkspace();
if (workspace == null) return externalPath; // protection during shutdown (30487)
if (workspace.getRoot().findMember(externalPath) != null) {
return externalPath;
}
IPath canonicalPath = null;
try {
canonicalPath =
new Path(new File(externalPath.toOSString()).getCanonicalPath());
} catch (IOException e) {
// default to original path
return externalPath;
}
IPath result;
int canonicalLength = canonicalPath.segmentCount();
if (canonicalLength == 0) {
// the java.io.File canonicalization failed
return externalPath;
} else if (externalPath.isAbsolute()) {
result = canonicalPath;
} else {
// if path is relative, remove the first segments that were added by the java.io.File canonicalization
// e.g. 'lib/classes.zip' was converted to 'd:/myfolder/lib/classes.zip'
int externalLength = externalPath.segmentCount();
if (canonicalLength >= externalLength) {
result = canonicalPath.removeFirstSegments(canonicalLength - externalLength);
} else {
return externalPath;
}
}
// keep device only if it was specified (this is because File.getCanonicalPath() converts '/lib/classes.zip' to 'd:/lib/classes/zip')
if (externalPath.getDevice() == null) {
result = result.setDevice(null);
}
// keep trailing separator only if it was specified (this is because File.getCanonicalPath() converts 'd:/lib/classes/' to 'd:/lib/classes')
if (externalPath.hasTrailingSeparator()) {
result = result.addTrailingSeparator();
}
return result;
}
/**
* Remove all markers denoting classpath problems
*/ //TODO (philippe) should improve to use a bitmask instead of booleans (CYCLE, FORMAT, VALID)
protected void flushClasspathProblemMarkers(boolean flushCycleMarkers, boolean flushClasspathFormatMarkers, boolean flushOverlappingOutputMarkers) {
// try {
// if (this.project.isAccessible()) {
// IMarker[] markers = this.project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
// for (int i = 0, length = markers.length; i < length; i++) {
// IMarker marker = markers[i];
// if (flushCycleMarkers && flushClasspathFormatMarkers && flushOverlappingOutputMarkers) {
// marker.delete();
// } else {
// String cycleAttr = (String)marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED);
// String classpathFileFormatAttr = (String)marker.getAttribute(IJavaModelMarker.CLASSPATH_FILE_FORMAT);
// String overlappingOutputAttr = (String) marker.getAttribute(IJavaModelMarker.OUTPUT_OVERLAPPING_SOURCE);
// if ((flushCycleMarkers == (cycleAttr != null && cycleAttr.equals("true"))) //$NON-NLS-1$
// && (flushOverlappingOutputMarkers == (overlappingOutputAttr != null && overlappingOutputAttr.equals("true"))) //$NON-NLS-1$
// && (flushClasspathFormatMarkers == (classpathFileFormatAttr != null && classpathFileFormatAttr.equals("true")))){ //$NON-NLS-1$
// marker.delete();
// } catch (CoreException e) {
// // could not flush markers: not much we can do
// if (JavaModelManager.VERBOSE) {
// e.printStackTrace();
}
/**
* Writes the classpath in a sharable format (VCM-wise) only when necessary, that is, if it is semantically different
* from the existing one in file. Will never write an identical one.
*
* @param newClasspath IClasspathEntry[]
* @param newOutputLocation IPath
* @return boolean Return whether the .classpath file was modified.
* @throws JavaModelException
*/
public boolean writeFileEntries(IClasspathEntry[] newClasspath, IClasspathEntry[] referencedEntries, IPath newOutputLocation)
throws JavaModelException {
if (!this.project.isAccessible()) return false;
Map unknownElements = new HashMap();
IClasspathEntry[][] fileEntries = readFileEntries(unknownElements);
if (fileEntries[0] != JavaProject.INVALID_CLASSPATH &&
areClasspathsEqual(newClasspath, newOutputLocation, fileEntries[0])
&& (referencedEntries == null || areClasspathsEqual(referencedEntries, fileEntries[1]))) {
// no need to save it, it is the same
return false;
}
// actual file saving
try {
setSharedProperty(JavaProject.CLASSPATH_FILENAME,
encodeClasspath(newClasspath, referencedEntries, newOutputLocation, true, unknownElements));
return true;
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
/**
* Record a shared persistent property onto a project.
* Note that it is orthogonal to IResource persistent properties, and client code has to decide
* which form of storage to use appropriately. Shared properties produce real resource files which
* can be shared through a VCM onto a server. Persistent properties are not shareable.
* <p>
* Shared properties end up in resource files, and thus cannot be modified during
* delta notifications (a CoreException would then be thrown).
*
* @param key String
* @param value String
* see JavaProject#getSharedProperty(String key)
* @throws CoreException
*/
public void setSharedProperty(String key, String value) throws CoreException {
IFile rscFile = this.project.getFile(key);
byte[] bytes = null;
try {
bytes = value.getBytes(org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8
} catch (UnsupportedEncodingException e) {
Util.log(e, "Could not write .classpath with UTF-8 encoding "); //$NON-NLS-1$
// fallback to default
bytes = value.getBytes();
}
InputStream inputStream = new ByteArrayInputStream(bytes);
// update the resource content
if (rscFile.exists()) {
// if (rscFile.isReadOnly()) {
// // provide opportunity to checkout read-only .classpath file (23984)
// ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{rscFile}, IWorkspace.VALIDATE_PROMPT);
rscFile.setContents(inputStream, IResource.FORCE, null);
} else {
rscFile.create(inputStream, IResource.FORCE, null);
}
}
private static boolean areClasspathsEqual(IClasspathEntry[] first, IClasspathEntry[] second) {
if (first != second) {
if (first == null) return false;
int length = first.length;
if (second == null || second.length != length)
return false;
for (int i = 0; i < length; i++) {
if (!first[i].equals(second[i]))
return false;
}
}
return true;
}
/**
* Compare current classpath with given one to see if any different.
* Note that the argument classpath contains its binary output.
* @param newClasspath IClasspathEntry[]
* @param newOutputLocation IPath
* @param otherClasspathWithOutput IClasspathEntry[]
* @return boolean
*/
private static boolean areClasspathsEqual(IClasspathEntry[] newClasspath, IPath newOutputLocation,
IClasspathEntry[] otherClasspathWithOutput) {
if (otherClasspathWithOutput == null || otherClasspathWithOutput.length == 0)
return false;
int length = otherClasspathWithOutput.length;
if (length != newClasspath.length + 1)
// output is amongst file entries (last one)
return false;
// compare classpath entries
for (int i = 0; i < length - 1; i++) {
if (!otherClasspathWithOutput[i].equals(newClasspath[i]))
return false;
}
// compare binary outputs
IClasspathEntry output = otherClasspathWithOutput[length - 1];
if (output.getContentKind() != ClasspathEntry.K_OUTPUT
|| !output.getPath().equals(newOutputLocation))
return false;
return true;
}
/**
* Returns the XML String encoding of the class path.
*/
protected String encodeClasspath(IClasspathEntry[] classpath, IClasspathEntry[] referencedEntries, IPath outputLocation, boolean indent,
Map unknownElements) throws JavaModelException {
try {
ByteArrayOutputStream s = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$
XMLWriter xmlWriter = new XMLWriter(writer, this, true/*print XML version*/);
xmlWriter.startTag(ClasspathEntry.TAG_CLASSPATH, indent);
for (int i = 0; i < classpath.length; ++i) {
((ClasspathEntry)classpath[i]).elementEncode(xmlWriter, this.project.getFullPath(), indent, true, unknownElements, false);
}
if (outputLocation != null) {
outputLocation = outputLocation.removeFirstSegments(1);
outputLocation = outputLocation.makeRelative();
HashMap parameters = new HashMap();
parameters.put(ClasspathEntry.TAG_KIND, ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT));
parameters.put(ClasspathEntry.TAG_PATH, String.valueOf(outputLocation));
xmlWriter.printTag(ClasspathEntry.TAG_CLASSPATHENTRY, parameters, indent, true, true);
}
if (referencedEntries != null) {
for (int i = 0; i < referencedEntries.length; ++i) {
((ClasspathEntry)referencedEntries[i])
.elementEncode(xmlWriter, this.project.getFullPath(), indent, true, unknownElements, true);
}
}
xmlWriter.endTag(ClasspathEntry.TAG_CLASSPATH, indent, true/*insert new line*/);
writer.flush();
writer.close();
return s.toString("UTF8");//$NON-NLS-1$
} catch (IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
}
public String encodeClasspathEntry(IClasspathEntry classpathEntry) {
try {
ByteArrayOutputStream s = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$
XMLWriter xmlWriter = new XMLWriter(writer, this, false/*don't print XML version*/);
((ClasspathEntry)classpathEntry)
.elementEncode(xmlWriter, this.project.getFullPath(), true/*indent*/, true/*insert new line*/, null/*not interested in unknown elements*/,
(classpathEntry.getReferencingEntry() != null));
writer.flush();
writer.close();
return s.toString("UTF8");//$NON-NLS-1$
} catch (IOException e) {
return null; // never happens since all is done in memory
}
}
/*
* Reads the classpath file entries of this project's .classpath file.
* This includes the output entry.
* As a side effect, unknown elements are stored in the given map (if not null)
*/
private IClasspathEntry[][] readFileEntries(Map unkwownElements) {
try {
return readFileEntriesWithException(unkwownElements);
} catch (CoreException e) {
Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$
return new IClasspathEntry[][] {JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES};
} catch (IOException e) {
Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$
return new IClasspathEntry[][] {JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES};
} catch (ClasspathEntry.AssertionFailedException e) {
Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$
return new IClasspathEntry[][] {JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES};
}
}
public static class ResolvedClasspath {
IClasspathEntry[] resolvedClasspath;
IJavaModelStatus unresolvedEntryStatus = JavaModelStatus.VERIFIED_OK;
HashMap<IPath, IClasspathEntry> rawReverseMap = new HashMap<>();
Map<IPath, IClasspathEntry> rootPathToResolvedEntries = new HashMap<>();
IClasspathEntry[] referencedEntries = null;
}
}
|
package edu.umich.med.michr.pdfhighlight;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.action.type.PDActionJavaScript;
public class PDFHighlighter {
private static String SOURCE_PDF_FILE="test.pdf";
private static String TARGET_PDF_FILE="test-highlighted.pdf";
private static String JS_FILE="find-words.js";
private static String SOURCE_PDF_FILE_PATH;
private static String TARGET_PDF_FILE_PATH;
private static String JS_FILE_PATH;
/**
* PDF file to be highlighted has to be in src/main/resources folder.
* To run in Gradle:
* "gradle -q" :(interactive, pdf input and output names are asked in GUI prompt)
* "gradle -PpdfFiles=test.pdf,test-highlighted.pdf": (non-interactive)
* Output files will be generated under build/recources/main folder under the java project root.
* To run in eclipse:
* In eclipse gradle plugin is needed. The classpath is the output bin folder so make sure the project is cleaned eclipse project browser is refreshed so that eclipse can find pdf and js files in the src/main/resources directory.
* When running in eclipse (right click on PDFHighlighter.java in project browser or in code window then pick "Run As"->"Java Application" then in console window you will be asked input and output pdf files for js(highlighter) injection.
* The output files will be under bin directory under project root.
*/
private static ClassLoader classLoader= PDFHighlighter.class.getClassLoader();
public static void main(String[] args) throws IOException, COSVisitorException, URISyntaxException {
collectFileNames(args);// default pdf file names and js file name is defined in build.gradle file as well as in static variables and should match for the app to run consistently in both eclipse, command line and gradle
PDDocument doc = PDDocument.load(SOURCE_PDF_FILE_PATH);
String jsCode= new String(Files.readAllBytes(Paths.get(JS_FILE_PATH)));
PDActionJavaScript javascript = new PDActionJavaScript(jsCode);
doc.getDocumentCatalog().setOpenAction(javascript);
doc.save(TARGET_PDF_FILE_PATH);
doc.close();
}
private static String getFilePath(String fileName){
return classLoader.getResource(fileName).getPath();
}
private static void getUserInputFromCommandLine(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter source pdf file name (default:"+SOURCE_PDF_FILE+"): ");
String source= sc.nextLine();
SOURCE_PDF_FILE=!source.equals("")?source:SOURCE_PDF_FILE;
System.out.println("Enter target pdf file name (default:"+TARGET_PDF_FILE+"): ");
String target= sc.nextLine();
TARGET_PDF_FILE=!target.equals("")?target:TARGET_PDF_FILE;
sc.close();
}
private static void collectFileNames(String[] args){
try{
getUserInputFromCommandLine();
}catch(Exception ex){
SOURCE_PDF_FILE=args[0];
TARGET_PDF_FILE=args[1];
}
SOURCE_PDF_FILE_PATH = getFilePath(SOURCE_PDF_FILE);
TARGET_PDF_FILE_PATH = SOURCE_PDF_FILE_PATH.substring(0,SOURCE_PDF_FILE_PATH.lastIndexOf(File.separator)+1)+TARGET_PDF_FILE;
JS_FILE_PATH = getFilePath(JS_FILE);
}
}
|
// -*- Mode: Java -*-
package gov.nist.basekb;
// Java:
import cc.mallet.classify.Classifier;
import cc.mallet.pipe.Pipe;
import cc.mallet.types.Instance;
import cc.mallet.types.Labeling;
import com.google.common.base.Joiner;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.docvalues.LongDocValues;
import org.apache.lucene.queries.function.valuesource.LongFieldSource;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueLong;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import java.io.*;
import java.util.*;
import static spark.Spark.*;
// Guava goodies
// Lucene:
// Spark
// Pebble
public class SearchServer {
@Option(name="-c", aliases={"--config"}, usage="FreebaseTools config file")
public String config_file_path = "/Users/soboroff/basekb/basekb-search/config.dat";
@Option(name="-p", aliases={"--port"}, usage="Port for service (default 8080)")
public int server_port = 8080;
@Option(name="-i", aliases={"--index"}, usage="Index location")
public String index_path = "/Users/soboroff/basekb/basekb-index";
@Option(name="-m", aliases={"--classifier"}, usage="MALLET classifier for entity types")
public String classifier_path = "/Users/soboroff/basekb/basekb-search/enttype.classifier";
@Option(name="-d", aliases={"--search-depth"}, usage="Depth for first-pass search results")
public int search_depth = 1000;
public static Map<String, String> docToMap(Document doc) {
Map<String, String> m = new LinkedHashMap<>();
for (IndexableField field: doc.getFields()) {
String key = field.name();
String val = field.stringValue();
if (m.containsKey(key)) {
val = m.get(key) + ", " + val;
}
m.put(key, val);
}
return m;
}
public static void printSubjectVerbose(Document subject, float score, String indent,
FreebaseSearcher tools, PrintWriter out) throws IOException {
// Pretty-print everything we know about `subject' to `out'.
// Annotate its `score' if it is non-negative.
if (score >= 0.0)
out.println(tools.getSubjectName(subject) + ": [score=" + score + "]");
else
out.println(tools.getSubjectName(subject) + ":");
for (IndexableField field : subject.getFields()) {
if (! tools.FIELD_NAME_SUBJECT.equals(field.name())) {
out.print(indent + field.name() + ": " + tools.fbi.normalizeNewlines(field.stringValue()));
if (field.stringValue().startsWith("f_m.")) {
int docid = tools.getSubjectDocID(field.stringValue());
if (docid > 0) {
Document new_subj = tools.getDocumentInMode(docid);
INNER: for (IndexableField new_field : new_subj.getFields()) {
if ((new_field.name().equals("rs_label") ||
new_field.name().equals("f_type.object.name")) &&
(new_field.stringValue().endsWith("@en"))) {
out.print(" (" + tools.fbi.normalizeNewlines(new_field.stringValue()) + ")");
break INNER;
}
}
}
}
out.println("");
}
}
}
public static String getFirstEnglishValue(Document doc, String key) {
for (String v: doc.getValues(key)) {
if (v.endsWith("@en")) {
return v;
}
}
return null;
}
public static void render_short(Document doc, float score, PrintWriter out) {
if (score > 0.0) {
out.println(doc.get("subject") + ": [" + score + "]");
} else {
out.println(doc.get("subject") + ":");
}
out.println(" " + getFirstEnglishValue(doc, "rs_label"));
out.println(" " + getFirstEnglishValue(doc, "f_common.topic.description"));
}
public static class Comparators {
public static final Comparator<HashMap<String, String>> SCORE =
(HashMap<String, String> d1, HashMap<String, String> d2) -> {
return Double.compare(Double.parseDouble(d2.getOrDefault("score", "0.0")),
Double.parseDouble(d1.getOrDefault("score", "0.0")));
};
public static final Comparator<HashMap<String, String>> PRBIN =
(HashMap<String, String> d1, HashMap<String, String> d2) -> {
int i1 = 0, i2 = 0;
String pr1 = d1.get("pr_bin");
if (pr1 != null)
i1 = Integer.parseInt(pr1);
String pr2 = d2.get("pr_bin");
if (pr2 != null)
i2 = Integer.parseInt(pr2);
return Integer.compare(i2, i1);
};
public static final Comparator<HashMap<String, String>> PR_BIN_SCORE =
(HashMap<String, String> d1, HashMap<String, String> d2) -> {
return PRBIN.thenComparing(SCORE).compare(d1, d2);
};
}
public SearchServer(String[] args) {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
}
catch (CmdLineException e) {
System.err.println("ERROR: " + e.getMessage());
System.err.println("Usage:");
parser.printUsage(System.err);
System.exit(1);
}
}
public Labeling classify(Document doc, Classifier classifier) {
Pipe p = classifier.getInstancePipe();
Joiner join = Joiner.on(" ");
String data = join.join(doc.getValues("r_type"));
String name = doc.get("rs_label");
Instance i = new Instance(data, null, name, null);
i = p.instanceFrom(i);
Labeling lab = classifier.classify(i).getLabeling();
return lab;
}
public static class SafeLongFieldSource extends LongFieldSource {
public SafeLongFieldSource(String field) {
super(field);
}
protected NumericDocValues getNumericDocValues(LeafReaderContext readerContext, String field) throws IOException {
NumericDocValues ndv = readerContext.reader().getNumericDocValues(field);
if (ndv == null) {
ndv = new NumericDocValues() {
@Override
public long get(int docid) { return 1; }
};
}
return ndv;
}
protected Bits getDocsWithField(LeafReaderContext readerContext, String field) throws IOException {
Bits bits = readerContext.reader().getDocsWithField(field);
if (bits == null) {
bits = new Bits.MatchNoBits(1);
}
return bits;
}
@Override
public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException {
final NumericDocValues arr = getNumericDocValues(readerContext, field);
final Bits valid = getDocsWithField(readerContext, field);
return new LongDocValues(this) {
@Override
public long longVal(int doc) {
return arr.get(doc);
}
@Override
public boolean exists(int doc) {
return arr.get(doc) != 0 || valid.get(doc);
}
@Override
public Object objectVal(int doc) {
return valid.get(doc) ? longToObject(arr.get(doc)) : null;
}
@Override
public String strVal(int doc) {
return valid.get(doc) ? longToString(arr.get(doc)) : null;
}
@Override
protected long externalToLong(String extVal) {
return SafeLongFieldSource.this.externalToLong(extVal);
}
@Override
public ValueFiller getValueFiller() {
return new ValueFiller() {
private final MutableValueLong mval = newMutableValueLong();
@Override
public MutableValue getValue() {
return mval;
}
@Override
public void fillValue(int doc) {
mval.value = arr.get(doc);
mval.exists = mval.value != 0 || valid.get(doc);
}
};
}
};
}
}
public static void main(String[] args) throws Exception {
// FreebaseTools main shell command dispatch.
SearchServer srv = new SearchServer(args);
FreebaseIndexer fbi = new FreebaseIndexer(srv.index_path);
fbi.INDEX_DIRECTORY_NAME = srv.index_path;
FreebaseSearcher tools = new FreebaseSearcher(fbi);
EntityRenderer abbrev = new EntityTypeRenderer(tools);
LongFormRenderer full = new LongFormRenderer();
Classifier tmpclass = null;
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(srv.classifier_path)));
tmpclass = (Classifier) ois.readObject();
final Classifier classifier = tmpclass;
ois.close();
Pipe pipe = classifier.getInstancePipe();
try {
if (fbi.SHOW_DEBUG) {
fbi.printLog("DBG: cmdline args:");
for (String arg : args)
fbi.printLog(" " + arg);
fbi.printlnLog();
fbi.printlnLog("DBG: configuration:");
}
staticFileLocation("/public");
port(srv.server_port);
PebbleEngine engine = new PebbleEngine.Builder().build();
PebbleTemplate main_template = engine.getTemplate("templates/main.peb");
get("/", (req, res) -> {
StringWriter buf = new StringWriter();
main_template.evaluate(buf);
return buf.toString();
});
PebbleTemplate disp_template = engine.getTemplate("templates/disp.peb");
get("/lookup/:subject", (req, res) -> {
tools.getIndexReader();
Map<String, Object> context = new HashMap<>();
int docid = tools.getSubjectDocID(req.params(":subject"));
if (docid < 0) {
halt(404, "Subject not found");
} else {
Document doc = tools.getDocumentInMode(docid);
StringWriter bufw = new StringWriter();
full.render(doc, bufw);
context.put("text", bufw.toString());
context.put("doc", docToMap(doc));
context.put("docid", docid);
context.put("subject", req.params(":subject"));
bufw.getBuffer().setLength(0);
disp_template.evaluate(bufw, context);
return bufw.toString();
}
return null;
});
PebbleTemplate serp_template = engine.getTemplate("templates/serp.peb");
Joiner joiner = Joiner.on(", ");
Ranker r = new MultiFieldRanker(tools.getIndexSearcher(), fbi.getIndexAnalyzer(), srv.search_depth);
get("/search", (req, res) -> {
res.header("Content-Encoding", "gzip");
StringWriter bufw = new StringWriter();
String qstring = req.queryParams("q");
TopDocs results = r.rank(qstring);
ScoreDoc[] hits = results.scoreDocs;
int numTotalHits = results.totalHits;
LinkedHashMap<String, ArrayList<HashMap<String, String>>> disp_docs = new LinkedHashMap<String, ArrayList<HashMap<String, String>>>();
String types[] = {"PER", "ORG", "GPE", "LOC", "FAC", "OTHER"};
for (String t : types) {
disp_docs.put(t, new ArrayList(hits.length));
}
Map<String, Object> context = new HashMap<>();
context.put("query", qstring);
context.put("totalHits", numTotalHits);
context.put("hits", hits);
context.put("docs", disp_docs);
for (int i = 0; i < hits.length; i++) {
bufw.getBuffer().setLength(0);
int docid = hits[i].doc;
float score = hits[i].score;
Document doc = tools.getDocumentInMode(docid);
Labeling labs = srv.classify(doc, classifier);
String type = labs.getBestLabel().toString();
ArrayList<HashMap<String, String>> this_dispdocs = disp_docs.get(type);
if (this_dispdocs == null) {
this_dispdocs = new ArrayList<HashMap<String, String>>(hits.length);
disp_docs.put(type, this_dispdocs);
}
abbrev.render(doc, bufw, score);
HashMap<String, String> dmap = new HashMap();
dmap.put("text", bufw.toString());
dmap.put("subject", doc.get("subject"));
dmap.put("types", joiner.join(doc.getValues("r_type")));
dmap.put("label", getFirstEnglishValue(doc, "rs_label"));
String pr = doc.get("pr_bin");
if (pr == null)
pr = "0";
dmap.put("pr_bin", pr);
dmap.put("score", Double.toString(hits[i].score));
this_dispdocs.add(dmap);
}
int first_nonzero_type_count = 0;
String first_nonzero_type = "";
for (Map.Entry<String, ArrayList<HashMap<String, String>>> disp_pair : disp_docs.entrySet()) {
String this_type = disp_pair.getKey();
ArrayList this_dispdocs = disp_pair.getValue();
Collections.sort(this_dispdocs, Comparators.SCORE);
if (first_nonzero_type_count == 0 && this_dispdocs.size() > 0) {
first_nonzero_type_count = this_dispdocs.size();
first_nonzero_type = this_type;
}
}
context.put("first_type", first_nonzero_type);
bufw.getBuffer().setLength(0);
serp_template.evaluate(bufw, context);
return bufw.toString();
});
}
catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(1);
}
}
}
|
package org.eclipse.che.plugin.maven.client.project;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.api.factory.shared.dto.Factory;
import org.eclipse.che.api.promises.client.Operation;
import org.eclipse.che.api.promises.client.OperationException;
import org.eclipse.che.api.promises.client.PromiseError;
import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto;
import org.eclipse.che.ide.api.factory.FactoryAcceptedEvent;
import org.eclipse.che.ide.api.factory.FactoryAcceptedHandler;
import org.eclipse.che.ide.api.notification.NotificationManager;
import org.eclipse.che.plugin.maven.client.service.MavenServerServiceClient;
import org.eclipse.che.plugin.maven.shared.MavenAttributes;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import static org.eclipse.che.ide.api.notification.StatusNotification.DisplayMode.EMERGE_MODE;
import static org.eclipse.che.ide.api.notification.StatusNotification.Status.FAIL;
/**
* Provide functionality for import/re-import maven model for given project
*
* @author Vitalii Parfonov
*/
@Singleton
public class MavenModelImporter implements FactoryAcceptedHandler {
private final NotificationManager notificationManager;
private final MavenServerServiceClient mavenClient;
@Inject
public MavenModelImporter(EventBus eventBus,
NotificationManager notificationManager,
MavenServerServiceClient mavenClient) {
this.notificationManager = notificationManager;
this.mavenClient = mavenClient;
eventBus.addHandler(FactoryAcceptedEvent.TYPE, this);
}
@Override
public void onFactoryAccepted(FactoryAcceptedEvent event) {
final Factory factory = event.getFactory();
final List<ProjectConfigDto> projects = factory.getWorkspace().getProjects();
final List<String> paths = new ArrayList<>();
for (ProjectConfigDto project : projects) {
if (MavenAttributes.MAVEN_ID.equals(project.getType())) {
paths.add(project.getPath());
}
}
if (!paths.isEmpty()) {
reimport(paths);
}
}
/**
*
* @param projectPaths
*/
public void reimport(List<String> projectPaths) {
mavenClient.reImportProjects(projectPaths).catchError(new Operation<PromiseError>() {
@Override
public void apply(PromiseError arg) throws OperationException {
notificationManager.notify("Problem with reimporting maven", arg.getMessage(), FAIL, EMERGE_MODE);
}
});
}
}
|
package uk.gov.ons.ctp.response.action.message;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeaderKey;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration (locations = { "/FeedbackServiceTest-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class FeedbackServiceTest {
public FeedbackService feedbackService = new FeedbackService();
@Before
public void setUp() throws Exception {
System.out.println("Test");
}
@After
public void tearDown() throws Exception {
}
@Autowired
MessageChannel feedbackXml;
@Autowired
QueueChannel testChannel;
@Autowired
@Qualifier("feedbackUnmarshaller")
Jaxb2Marshaller feedbackMarshaller;
@Test
public void testSendctiveMQMessage() {
try {
String testMessage = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<p:actionFeedback xmlns:p=\"http:
"<actionId>1</actionId>" +
"<situation>situation</situation>" +
"<isComplete>true</isComplete>" +
"<isFailed>true</isFailed>" +
"<notes>notes</notes>" +
"</p:actionFeedback>";
feedbackXml.send(MessageBuilder.withPayload(testMessage).build());
Message<?> outMessage = testChannel.receive(0);
assertNotNull("outMessage should not be null", outMessage);
boolean payLoadContainsAdaptor = outMessage.getPayload().toString().contains("uk.gov.ons.ctp.response.action.message.feedback.ActionFeedback");
assertTrue("Payload does not contain reference to ActionFeedback adaptor", payLoadContainsAdaptor);
assertThat(outMessage, hasHeaderKey("timestamp"));
assertThat(outMessage, hasHeaderKey("id"));
outMessage = testChannel.receive(0);
assertNull("Only one message expected from feedbackTransformed", outMessage);
String contextPath = feedbackMarshaller.getContextPath();
String jaxbContext = feedbackMarshaller.getJaxbContext().toString();
System.out.println("Marshaller context path: " + contextPath);
System.out.println("Marshaller jaxbContext: " + jaxbContext);
}
catch (Exception ex) {
fail("testSendctiveMQMessage has failed " + ex.getMessage());
}
}
}
|
package com.oracle.truffle.llvm.parser.bc.impl.nodes;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.llvm.nodes.base.LLVMExpressionNode;
import com.oracle.truffle.llvm.nodes.impl.base.LLVMAddressNode;
import com.oracle.truffle.llvm.nodes.impl.base.LLVMContext;
import com.oracle.truffle.llvm.nodes.impl.base.LLVMFunctionNode;
import com.oracle.truffle.llvm.nodes.impl.base.LLVMStructWriteNode;
import com.oracle.truffle.llvm.nodes.impl.base.floating.LLVM80BitFloatNode;
import com.oracle.truffle.llvm.nodes.impl.base.floating.LLVMDoubleNode;
import com.oracle.truffle.llvm.nodes.impl.base.floating.LLVMFloatNode;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI16Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI1Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI32Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI64Node;
import com.oracle.truffle.llvm.nodes.impl.base.integers.LLVMI8Node;
import com.oracle.truffle.llvm.nodes.impl.literals.LLVMFunctionLiteralNodeGen;
import com.oracle.truffle.llvm.nodes.impl.literals.LLVMSimpleLiteralNode;
import com.oracle.truffle.llvm.nodes.impl.memory.LLVMAddressZeroNode;
import com.oracle.truffle.llvm.nodes.impl.memory.LLVMAllocInstruction;
import com.oracle.truffle.llvm.nodes.impl.memory.LLVMAllocInstructionFactory;
import com.oracle.truffle.llvm.nodes.impl.memory.LLVMStoreNodeFactory;
import com.oracle.truffle.llvm.nodes.impl.vars.StructLiteralNode;
import com.oracle.truffle.llvm.parser.LLVMBaseType;
import com.oracle.truffle.llvm.parser.bc.impl.LLVMLabelList;
import com.oracle.truffle.llvm.parser.bc.impl.util.LLVMBitcodeTypeHelper;
import com.oracle.truffle.llvm.parser.factories.LLVMCastsFactory;
import com.oracle.truffle.llvm.parser.factories.LLVMGetElementPtrFactory;
import com.oracle.truffle.llvm.parser.factories.LLVMLiteralFactory;
import com.oracle.truffle.llvm.parser.instructions.LLVMConversionType;
import com.oracle.truffle.llvm.types.LLVMAddress;
import com.oracle.truffle.llvm.types.LLVMFunctionDescriptor;
import com.oracle.truffle.llvm.types.LLVMIVarBit;
import uk.ac.man.cs.llvm.ir.model.FunctionDeclaration;
import uk.ac.man.cs.llvm.ir.model.FunctionDefinition;
import uk.ac.man.cs.llvm.ir.model.GlobalValueSymbol;
import uk.ac.man.cs.llvm.ir.model.Symbol;
import uk.ac.man.cs.llvm.ir.model.ValueSymbol;
import uk.ac.man.cs.llvm.ir.model.constants.ArrayConstant;
import uk.ac.man.cs.llvm.ir.model.constants.BinaryOperationConstant;
import uk.ac.man.cs.llvm.ir.model.constants.BlockAddressConstant;
import uk.ac.man.cs.llvm.ir.model.constants.CastConstant;
import uk.ac.man.cs.llvm.ir.model.constants.CompareConstant;
import uk.ac.man.cs.llvm.ir.model.constants.FloatingPointConstant;
import uk.ac.man.cs.llvm.ir.model.constants.GetElementPointerConstant;
import uk.ac.man.cs.llvm.ir.model.constants.IntegerConstant;
import uk.ac.man.cs.llvm.ir.model.constants.NullConstant;
import uk.ac.man.cs.llvm.ir.model.constants.StringConstant;
import uk.ac.man.cs.llvm.ir.model.constants.StructureConstant;
import uk.ac.man.cs.llvm.ir.model.constants.UndefinedConstant;
import uk.ac.man.cs.llvm.ir.types.ArrayType;
import uk.ac.man.cs.llvm.ir.types.FloatingPointType;
import uk.ac.man.cs.llvm.ir.types.FunctionType;
import uk.ac.man.cs.llvm.ir.types.IntegerType;
import uk.ac.man.cs.llvm.ir.types.PointerType;
import uk.ac.man.cs.llvm.ir.types.StructureType;
import uk.ac.man.cs.llvm.ir.types.Type;
import uk.ac.man.cs.llvm.ir.types.VectorType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public final class LLVMConstantGenerator {
private LLVMConstantGenerator() {
}
public static LLVMExpressionNode toConstantNode(Symbol value, int align, Function<GlobalValueSymbol, LLVMExpressionNode> variables, LLVMContext context, FrameSlot stackSlot, LLVMLabelList labels,
LLVMBitcodeTypeHelper typeHelper) {
if (value instanceof GlobalValueSymbol) {
return variables.apply((GlobalValueSymbol) value);
} else if (value instanceof FunctionDefinition || value instanceof FunctionDeclaration) {
final FunctionType type = (FunctionType) value;
final LLVMFunctionDescriptor.LLVMRuntimeType returnType = LLVMBitcodeTypeHelper.toRuntimeType(type.getReturnType());
final LLVMFunctionDescriptor.LLVMRuntimeType[] argTypes = LLVMBitcodeTypeHelper.toRuntimeTypes(type.getArgumentTypes());
final String name = ((ValueSymbol) value).getName();
return LLVMFunctionLiteralNodeGen.create(context.getFunctionRegistry().createFunctionDescriptor(name, returnType, argTypes, type.isVarArg()));
} else if (value instanceof StringConstant) {
final StringConstant constant = (StringConstant) value;
final String chars = constant.getString();
final List<LLVMI8Node> values = new ArrayList<>(chars.length());
for (int i = 0; i < chars.length(); i++) {
values.add(new LLVMSimpleLiteralNode.LLVMI8LiteralNode((byte) chars.charAt(i)));
}
if (constant.isCString()) {
values.add(new LLVMSimpleLiteralNode.LLVMI8LiteralNode((byte) 0));
}
final int size = typeHelper.getByteSize(new IntegerType(Byte.SIZE)) * values.size();
final LLVMAllocInstruction.LLVMAllocaInstruction target = LLVMAllocInstructionFactory.LLVMAllocaInstructionNodeGen.create(size, 1, context, stackSlot);
return LLVMStoreNodeFactory.LLVMI8ArrayLiteralNodeGen.create(values.toArray(new LLVMI8Node[values.size()]), typeHelper.getByteSize(new IntegerType(Byte.SIZE)), target);
} else if (value instanceof ArrayConstant) {
return toArrayConstant((ArrayConstant) value, align, variables, context, stackSlot, labels, typeHelper);
} else if (value instanceof StructureConstant) {
return toStructureConstant((StructureConstant) value, align, variables, context, stackSlot, labels, typeHelper);
} else if (value instanceof NullConstant) {
return LLVMConstantGenerator.toConstantZeroNode(value.getType(), context, stackSlot, typeHelper);
} else if (value instanceof UndefinedConstant) {
return LLVMConstantGenerator.toConstantZeroNode(value.getType(), context, stackSlot, typeHelper);
} else if (value instanceof BinaryOperationConstant) {
final BinaryOperationConstant operation = (BinaryOperationConstant) value;
final LLVMExpressionNode lhs = toConstantNode(operation.getLHS(), align, variables, context, stackSlot, labels, typeHelper);
final LLVMExpressionNode rhs = toConstantNode(operation.getRHS(), align, variables, context, stackSlot, labels, typeHelper);
final LLVMBaseType type = LLVMBitcodeTypeHelper.getLLVMBaseType(operation.getType());
return LLVMNodeGenerator.generateBinaryOperatorNode(operation.getOperator(), type, lhs, rhs);
} else if (value instanceof CastConstant) {
final CastConstant cast = (CastConstant) value;
final LLVMConversionType type = LLVMBitcodeTypeHelper.toConversionType(cast.getOperator());
final LLVMExpressionNode fromNode = toConstantNode(cast.getValue(), align, variables, context, stackSlot, labels, typeHelper);
final LLVMBaseType from = LLVMBitcodeTypeHelper.getLLVMBaseType(cast.getValue().getType());
final LLVMBaseType to = LLVMBitcodeTypeHelper.getLLVMBaseType(cast.getType());
return LLVMCastsFactory.cast(fromNode, to, from, type);
} else if (value instanceof CompareConstant) {
final CompareConstant compare = (CompareConstant) value;
final LLVMExpressionNode lhs = toConstantNode(compare.getLHS(), align, variables, context, stackSlot, labels, typeHelper);
final LLVMExpressionNode rhs = toConstantNode(compare.getRHS(), align, variables, context, stackSlot, labels, typeHelper);
return LLVMNodeGenerator.toCompareNode(compare.getOperator(), compare.getLHS().getType(), lhs, rhs);
} else if (value instanceof GetElementPointerConstant) {
return toGetElementPointerConstant((GetElementPointerConstant) value, align, variables, context, stackSlot, labels, typeHelper);
} else if (value instanceof IntegerConstant) {
final IntegerConstant constant = (IntegerConstant) value;
final int bits = ((IntegerType) (constant).getType()).getBitCount();
switch (bits) {
case 1:
return new LLVMSimpleLiteralNode.LLVMI1LiteralNode(constant.getValue() != 0);
case Byte.SIZE:
return new LLVMSimpleLiteralNode.LLVMI8LiteralNode((byte) constant.getValue());
case Short.SIZE:
return new LLVMSimpleLiteralNode.LLVMI16LiteralNode((short) constant.getValue());
case Integer.SIZE:
return new LLVMSimpleLiteralNode.LLVMI32LiteralNode((int) constant.getValue());
case Long.SIZE:
return new LLVMSimpleLiteralNode.LLVMI64LiteralNode(constant.getValue());
default:
return new LLVMSimpleLiteralNode.LLVMIVarBitLiteralNode(LLVMIVarBit.fromLong(bits, constant.getValue()));
}
} else if (value instanceof FloatingPointConstant) {
final FloatingPointConstant constant = (FloatingPointConstant) value;
switch (((FloatingPointType) constant.getType())) {
case FLOAT:
return new LLVMSimpleLiteralNode.LLVMFloatLiteralNode(constant.toFloat());
case DOUBLE:
return new LLVMSimpleLiteralNode.LLVMDoubleLiteralNode(constant.toDouble());
default:
throw new UnsupportedOperationException("Unsupported Floating Point Type: " + constant.getType());
}
} else if (value instanceof BlockAddressConstant) {
return toBlockAddressConstant((BlockAddressConstant) value, labels);
} else {
throw new UnsupportedOperationException("Unsupported Constant: " + value);
}
}
private static LLVMExpressionNode toArrayConstant(ArrayConstant array, int align, Function<GlobalValueSymbol, LLVMExpressionNode> variables, LLVMContext context, FrameSlot stackSlot,
LLVMLabelList labels, LLVMBitcodeTypeHelper typeHelper) {
final Type elementType = array.getType().getElementType();
final LLVMBaseType llvmElementType = LLVMBitcodeTypeHelper.getLLVMBaseType(elementType);
final int stride = typeHelper.getByteSize(elementType);
final LLVMAllocInstruction.LLVMAllocaInstruction allocation = LLVMAllocInstructionFactory.LLVMAllocaInstructionNodeGen.create(typeHelper.getByteSize(array.getType()),
typeHelper.getAlignment(array.getType()), context, stackSlot);
switch (llvmElementType) {
case I8: {
final LLVMI8Node[] elements = new LLVMI8Node[array.getElementCount()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (LLVMI8Node) toConstantNode(array.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
}
return LLVMStoreNodeFactory.LLVMI8ArrayLiteralNodeGen.create(elements, stride, allocation);
}
case I16: {
final LLVMI16Node[] elements = new LLVMI16Node[array.getElementCount()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (LLVMI16Node) toConstantNode(array.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
}
return LLVMStoreNodeFactory.LLVMI16ArrayLiteralNodeGen.create(elements, stride, allocation);
}
case I32: {
final LLVMI32Node[] elements = new LLVMI32Node[array.getElementCount()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (LLVMI32Node) toConstantNode(array.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
}
return LLVMStoreNodeFactory.LLVMI32ArrayLiteralNodeGen.create(elements, stride, allocation);
}
case I64: {
final LLVMI64Node[] elements = new LLVMI64Node[array.getElementCount()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (LLVMI64Node) toConstantNode(array.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
}
return LLVMStoreNodeFactory.LLVMI64ArrayLiteralNodeGen.create(elements, stride, allocation);
}
case FLOAT: {
final LLVMFloatNode[] elements = new LLVMFloatNode[array.getElementCount()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (LLVMFloatNode) toConstantNode(array.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
}
return LLVMStoreNodeFactory.LLVMFloatArrayLiteralNodeGen.create(elements, stride, allocation);
}
case DOUBLE: {
final LLVMDoubleNode[] elements = new LLVMDoubleNode[array.getElementCount()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (LLVMDoubleNode) toConstantNode(array.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
}
return LLVMStoreNodeFactory.LLVMDoubleArrayLiteralNodeGen.create(elements, stride, allocation);
}
case ARRAY:
case STRUCT: {
final LLVMAddressNode[] elements = new LLVMAddressNode[array.getElementCount()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (LLVMAddressNode) toConstantNode(array.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
}
return LLVMStoreNodeFactory.LLVMAddressArrayCopyNodeGen.create(elements, stride, allocation);
}
case ADDRESS: {
final LLVMAddressNode[] elements = new LLVMAddressNode[array.getElementCount()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (LLVMAddressNode) toConstantNode(array.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
}
return LLVMStoreNodeFactory.LLVMAddressArrayLiteralNodeGen.create(elements, stride, allocation);
}
case FUNCTION_ADDRESS: {
final LLVMFunctionNode[] elements = new LLVMFunctionNode[array.getElementCount()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (LLVMFunctionNode) toConstantNode(array.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
}
return LLVMStoreNodeFactory.LLVMFunctionArrayLiteralNodeGen.create(elements, stride, allocation);
}
default:
throw new AssertionError(llvmElementType);
}
}
private static LLVMExpressionNode toBlockAddressConstant(BlockAddressConstant blockAddressConstant, LLVMLabelList labels) {
final FunctionDefinition function = blockAddressConstant.getFunction();
final Map<String, Integer> innerLabels = labels.labels(function.getName());
for (Map.Entry<String, Integer> labelEntry : innerLabels.entrySet()) {
if (labelEntry.getValue().equals(blockAddressConstant.getBlock())) {
String blockName = labelEntry.getKey();
for (int i = 0; i < function.getBlockCount(); i++) {
if (function.getBlock(i).getName().equals(blockName)) {
return new LLVMSimpleLiteralNode.LLVMAddressLiteralNode(LLVMAddress.fromLong(i));
}
}
}
}
throw new AssertionError("Could not find Block: " + blockAddressConstant.getBlock());
}
private static LLVMExpressionNode toGetElementPointerConstant(GetElementPointerConstant constant, int align, Function<GlobalValueSymbol, LLVMExpressionNode> variables, LLVMContext context,
FrameSlot stackSlot, LLVMLabelList labels, LLVMBitcodeTypeHelper typeHelper) {
LLVMAddressNode currentAddress = (LLVMAddressNode) toConstantNode(constant.getBasePointer(), align, variables, context, stackSlot, labels, typeHelper);
Type currentType = constant.getBasePointer().getType();
Type parentType = null;
int currentOffset = 0;
for (final Symbol index : constant.getIndices()) {
final Integer indexVal = LLVMNodeGenerator.evaluateIntegerConstant(index);
if (indexVal == null) {
throw new IllegalStateException("Invalid index: " + index);
}
currentOffset += typeHelper.goIntoTypeGetLength(currentType, indexVal);
parentType = currentType;
currentType = LLVMBitcodeTypeHelper.goIntoType(currentType, indexVal);
}
if (currentType != null && !((parentType instanceof StructureType) && (((StructureType) parentType).isPacked()))) {
currentOffset += typeHelper.getPadding(currentOffset, currentType);
}
if (currentOffset != 0) {
currentAddress = LLVMGetElementPtrFactory.create(LLVMBaseType.I32, currentAddress, new LLVMSimpleLiteralNode.LLVMI32LiteralNode(1), currentOffset);
}
return currentAddress;
}
private static LLVMStructWriteNode createStructWriteNode(LLVMExpressionNode parsedConstant, LLVMBaseType baseType, int byteSize) {
switch (baseType) {
case I1:
return new StructLiteralNode.LLVMI1StructWriteNode((LLVMI1Node) parsedConstant);
case I8:
return new StructLiteralNode.LLVMI8StructWriteNode((LLVMI8Node) parsedConstant);
case I16:
return new StructLiteralNode.LLVMI16StructWriteNode((LLVMI16Node) parsedConstant);
case I32:
return new StructLiteralNode.LLVMI32StructWriteNode((LLVMI32Node) parsedConstant);
case I64:
return new StructLiteralNode.LLVMI64StructWriteNode((LLVMI64Node) parsedConstant);
case FLOAT:
return new StructLiteralNode.LLVMFloatStructWriteNode((LLVMFloatNode) parsedConstant);
case DOUBLE:
return new StructLiteralNode.LLVMDoubleStructWriteNode((LLVMDoubleNode) parsedConstant);
case X86_FP80:
return new StructLiteralNode.LLVM80BitFloatStructWriteNode((LLVM80BitFloatNode) parsedConstant);
case ARRAY:
case STRUCT:
if (byteSize == 0) {
return new StructLiteralNode.LLVMEmptyStructWriteNode();
} else {
return new StructLiteralNode.LLVMCompoundStructWriteNode((LLVMAddressNode) parsedConstant, byteSize);
}
case ADDRESS:
return new StructLiteralNode.LLVMAddressStructWriteNode((LLVMAddressNode) parsedConstant);
case FUNCTION_ADDRESS:
return new StructLiteralNode.LLVMFunctionStructWriteNode((LLVMFunctionNode) parsedConstant);
default:
throw new AssertionError("Invalid BaseType for StructWriteNode: " + baseType);
}
}
private static LLVMExpressionNode toStructureConstant(StructureConstant constant, int align, Function<GlobalValueSymbol, LLVMExpressionNode> variables, LLVMContext context, FrameSlot stackSlot,
LLVMLabelList labels, LLVMBitcodeTypeHelper typeHelper) {
final int elementCount = constant.getElementCount();
final boolean packed = constant.isPacked();
final int[] offsets = new int[elementCount];
final LLVMStructWriteNode[] nodes = new LLVMStructWriteNode[elementCount];
final StructureType structureType = (StructureType) constant.getType();
final int structSize = typeHelper.getByteSize(structureType);
final int structAlignment = typeHelper.getAlignment(structureType);
final LLVMAddressNode allocation = LLVMAllocInstructionFactory.LLVMAllocaInstructionNodeGen.create(structSize, structAlignment, context, stackSlot);
int currentOffset = 0;
for (int i = 0; i < elementCount; i++) {
final Type elementType = constant.getElementType(i);
if (!packed) {
currentOffset += typeHelper.getPadding(currentOffset, elementType);
}
offsets[i] = currentOffset;
final int byteSize = typeHelper.getByteSize(elementType);
final LLVMExpressionNode resolvedConstant = toConstantNode(constant.getElement(i), align, variables, context, stackSlot, labels, typeHelper);
nodes[i] = createStructWriteNode(resolvedConstant, LLVMBitcodeTypeHelper.getLLVMBaseType(elementType), byteSize);
currentOffset += byteSize;
}
return new StructLiteralNode(offsets, nodes, allocation);
}
private static LLVMExpressionNode toStructZeroNode(StructureType structureType, LLVMContext context, FrameSlot stackSlot, LLVMBitcodeTypeHelper typeHelper) {
final int size = typeHelper.getByteSize(structureType);
if (size == 0) {
final LLVMAddress minusOneNode = LLVMAddress.fromLong(-1);
return new LLVMSimpleLiteralNode.LLVMAddressLiteralNode(minusOneNode);
} else {
final int alignment = typeHelper.getAlignment(structureType);
final LLVMAddressNode addressNode = LLVMAllocInstructionFactory.LLVMAllocaInstructionNodeGen.create(size, alignment, context, stackSlot);
return new LLVMAddressZeroNode(addressNode, size);
}
}
private static LLVMExpressionNode toArrayZeroNode(ArrayType type, LLVMContext context, FrameSlot stack, LLVMBitcodeTypeHelper typeHelper) {
final int size = typeHelper.getByteSize(type);
if (size == 0) {
return null;
} else {
final int alignment = typeHelper.getAlignment(type);
final LLVMAddressNode allocation = LLVMAllocInstructionFactory.LLVMAllocaInstructionNodeGen.create(size, alignment, context, stack);
return new LLVMAddressZeroNode(allocation, size);
}
}
public static LLVMExpressionNode toConstantZeroNode(Type type, LLVMContext context, FrameSlot stack, LLVMBitcodeTypeHelper typeHelper) {
if (type instanceof IntegerType) {
final int vbr = ((IntegerType) type).getBitCount();
switch (vbr) {
case 1:
return new LLVMSimpleLiteralNode.LLVMI1LiteralNode(false);
case Byte.SIZE:
return new LLVMSimpleLiteralNode.LLVMI8LiteralNode((byte) 0);
case Short.SIZE:
return new LLVMSimpleLiteralNode.LLVMI16LiteralNode((short) 0);
case Integer.SIZE:
return new LLVMSimpleLiteralNode.LLVMI32LiteralNode(0);
case Long.SIZE:
return new LLVMSimpleLiteralNode.LLVMI64LiteralNode(0L);
default:
return new LLVMSimpleLiteralNode.LLVMIVarBitLiteralNode(LLVMIVarBit.fromLong(vbr, 0L));
}
} else if (type instanceof FloatingPointType) {
FloatingPointType floatingPointType = (FloatingPointType) type;
switch (floatingPointType) {
case FLOAT:
return new LLVMSimpleLiteralNode.LLVMFloatLiteralNode(0.0f);
case DOUBLE:
return new LLVMSimpleLiteralNode.LLVMDoubleLiteralNode(0.0);
default:
throw new UnsupportedOperationException("Unsupported Floating Point Type: " + floatingPointType);
}
} else if (type instanceof PointerType) {
if (((PointerType) type).getPointeeType() instanceof FunctionType) {
final LLVMFunctionDescriptor functionDescriptor = context.getFunctionRegistry().createZeroFunctionDescriptor();
return LLVMFunctionLiteralNodeGen.create(functionDescriptor);
} else {
return new LLVMSimpleLiteralNode.LLVMAddressLiteralNode(LLVMAddress.fromLong(0));
}
} else if (type instanceof ArrayType) {
return toArrayZeroNode((ArrayType) type, context, stack, typeHelper);
} else if (type instanceof VectorType) {
final VectorType vectorType = (VectorType) type.getType();
final LLVMAddressNode target = LLVMAllocInstructionFactory.LLVMAllocaInstructionNodeGen.create(typeHelper.getByteSize(type.getType()), typeHelper.getAlignment(type.getType()), context,
stack);
final LLVMExpressionNode[] zeroes = new LLVMExpressionNode[vectorType.getElementCount()];
Arrays.fill(zeroes, toConstantZeroNode(vectorType.getElementType(), context, stack, typeHelper));
return LLVMLiteralFactory.createVectorLiteralNode(Arrays.asList(zeroes), target, LLVMBitcodeTypeHelper.getLLVMBaseType(vectorType));
} else if (type instanceof FunctionType) {
final LLVMFunctionDescriptor functionDescriptor = context.getFunctionRegistry().createFunctionDescriptor("<zero function>", LLVMFunctionDescriptor.LLVMRuntimeType.ILLEGAL,
new LLVMFunctionDescriptor.LLVMRuntimeType[0], false);
return LLVMFunctionLiteralNodeGen.create(functionDescriptor);
} else if (type instanceof StructureType) {
final StructureType structureType = (StructureType) type;
return toStructZeroNode(structureType, context, stack, typeHelper);
} else {
throw new AssertionError("Unsupported Type for Zero Constant: " + type);
}
}
}
|
package hotchemi.com.github;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
/*
* A memory cache implementation which uses a LRU policy.
* <p>
* This implementation is thread safe.
*
* @author Shintaro Katafuchi
*/
public class LruCache<K, V> implements Cache<K, V> {
/**
* The flag represents remove all entries in the cache.
*/
private static final int REMOVE_ALL = -1;
private static final int DEFAULT_CAPACITY = 10;
private final Map<K, V> map;
private final int maxMemorySize;
private int memorySize;
public LruCache() {
this.map = new LruHashMap<>(DEFAULT_CAPACITY);
maxMemorySize = DEFAULT_CAPACITY * 1024 * 1024;
}
public LruCache(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("capacity <= 0");
}
this.map = new LruHashMap<>(capacity);
maxMemorySize = capacity * 1024 * 1024;
}
@Override
public V get(K key) {
Objects.requireNonNull(key, "key == null");
synchronized (this) {
V value = map.get(key);
if (value != null) {
return value;
}
}
return null;
}
@Override
public V put(K key, V value) {
Objects.requireNonNull(key, "key == null");
Objects.requireNonNull(value, "value == null");
V previous;
synchronized (this) {
previous = map.put(key, value);
memorySize += getValueSize(value);
if (previous != null) {
memorySize -= getValueSize(previous);
}
trimToSize(maxMemorySize);
}
return previous;
}
@Override
public V remove(K key) {
Objects.requireNonNull(key, "key == null");
V previous;
synchronized (this) {
previous = map.remove(key);
if (previous != null) {
memorySize -= getValueSize(previous);
}
}
return previous;
}
@Override
public synchronized void clear() {
trimToSize(REMOVE_ALL);
}
@Override
public synchronized int getMaxMemorySize() {
return maxMemorySize;
}
@Override
public synchronized int getMemorySize() {
return memorySize;
}
/**
* Returns a copy of the current contents of the cache.
*/
public synchronized Map<K, V> snapshot() {
return new LinkedHashMap<>(map);
}
/**
* Returns the class name.
* <p>
* This method should be overridden to debug exactly.
*
* @return class name.
*/
protected String getClassName() {
return LruCache.class.getName();
}
/**
* Returns the size of the entry.
* <p>
* The default implementation returns 1 so that max size is the maximum number of entries.
* <p>
* <em>Note:</em> This method should be overridden if you control memory size correctly.
*
* @param value value
* @return the size of the entry.
*/
protected int getValueSize(V value) {
return 1;
}
/**
* Remove the eldest entries.
* <p>
* <em>Note:</em> This method has to be called in synchronized block.
*
* @param maxSize max size
*/
private void trimToSize(int maxSize) {
while (true) {
if (memorySize <= maxSize || map.isEmpty()) {
break;
}
if (memorySize < 0 || (map.isEmpty() && memorySize != 0)) {
throw new IllegalStateException(getClassName() + " is reporting inconsistent results");
}
Map.Entry<K, V> toRemove = map.entrySet().iterator().next();
map.remove(toRemove.getKey());
memorySize -= getValueSize(toRemove.getValue());
}
}
@Override
public synchronized final String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<K, V> entry : map.entrySet()) {
sb.append(entry.getKey())
.append('=')
.append(entry.getValue())
.append(",");
}
sb.append("maxMemory=")
.append(maxMemorySize)
.append(",")
.append("memorySize=")
.append(memorySize);
return sb.toString();
}
}
|
package de.eternity.support.lua.functions;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.ThreeArgFunction;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
import de.eternity.GameData;
import de.eternity.gfx.Text;
public class NewTextArea extends ThreeArgFunction{
private GameData gameData;
public NewTextArea(GameData gameData) {
this.gameData = gameData;
}
@Override
public LuaValue call(LuaValue width, LuaValue height, LuaValue color) {
return CoerceJavaToLua.coerce(new Text(width.checkint(), height.checkint(), color.checkint(), gameData));
}
}
|
package com.thebluealliance.androidclient.listitems;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.thebluealliance.androidclient.Constants;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.listeners.TeamAtEventClickListener;
import com.thebluealliance.androidclient.listeners.TeamClickListener;
public class MatchListElement extends ListElement {
private String videoKey;
String matchTitle, redTeams[], blueTeams[], matchKey, redScore, blueScore;
private String selectedTeamNumber;
public MatchListElement(String youTubeVideoKey, String matchTitle, String[] redTeams, String[] blueTeams, String redScore, String blueScore, String matchKey) {
super(matchKey);
this.videoKey = youTubeVideoKey;
this.matchTitle = matchTitle;
this.redTeams = redTeams;
this.blueTeams = blueTeams;
this.redScore = redScore;
this.blueScore = blueScore;
this.matchKey = matchKey;
this.selectedTeamNumber = "";
}
public MatchListElement(String youTubeVideoKey, String matchTitle, String[] redTeams, String[] blueTeams, String redScore, String blueScore, String matchKey, String selectedTeamKey) {
super(matchKey);
this.videoKey = youTubeVideoKey;
this.matchTitle = matchTitle;
this.redTeams = redTeams;
this.blueTeams = blueTeams;
this.redScore = redScore;
this.blueScore = blueScore;
this.matchKey = matchKey;
this.selectedTeamNumber = selectedTeamKey.replace("frc", "");
}
@Override
public View getView(final Context context, LayoutInflater inflater, View convertView) {
ViewHolder holder;
if (convertView == null || !(convertView.getTag() instanceof ViewHolder)) {
convertView = inflater.inflate(R.layout.list_item_match, null);
holder = new ViewHolder();
holder.matchTitle = (TextView) convertView.findViewById(R.id.match_title);
holder.red1 = (TextView) convertView.findViewById(R.id.red1);
holder.red2 = (TextView) convertView.findViewById(R.id.red2);
holder.red3 = (TextView) convertView.findViewById(R.id.red3);
holder.blue1 = (TextView) convertView.findViewById(R.id.blue1);
holder.blue2 = (TextView) convertView.findViewById(R.id.blue2);
holder.blue3 = (TextView) convertView.findViewById(R.id.blue3);
holder.redScore = (TextView) convertView.findViewById(R.id.red_score);
holder.blueScore = (TextView) convertView.findViewById(R.id.blue_score);
holder.redAlliance = convertView.findViewById(R.id.red_alliance);
holder.blueAlliance = convertView.findViewById(R.id.blue_alliance);
holder.videoIcon = (ImageView) convertView.findViewById(R.id.match_video);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.matchTitle.setTag(matchKey);
if (!redScore.contains("?") && !blueScore.contains("?")) {
try {
int bScore = Integer.parseInt(blueScore),
rScore = Integer.parseInt(redScore);
if (bScore > rScore) {
//blue wins
holder.blueAlliance.setBackgroundResource(R.drawable.blue_border);
holder.redAlliance.setBackgroundColor(context.getResources().getColor(R.color.lighter_red));
} else if (bScore < rScore) {
//red wins
holder.redAlliance.setBackgroundResource(R.drawable.red_border);
holder.blueAlliance.setBackgroundColor(context.getResources().getColor(R.color.lighter_blue));
}
} catch (NumberFormatException e) {
Log.w(Constants.LOG_TAG, "Attempted to parse an invalid match score.");
}
}
//if we have video for this match, show an icon
if (videoKey != null) {
holder.videoIcon.setVisibility(View.VISIBLE);
} else {
holder.videoIcon.setVisibility(View.INVISIBLE);
}
holder.matchTitle.setText(matchTitle);
TeamAtEventClickListener listener = new TeamAtEventClickListener(context);
String eventKey = matchKey.split("_")[0];
// Set team text depending on alliance size.
if (redTeams.length == 0) {
holder.red1.setText("");
holder.red2.setText("");
holder.red3.setText("");
} else {
holder.red1.setText(redTeams[0]);
holder.red1.setTag("frc" + redTeams[0]+"@"+eventKey);
holder.red1.setOnClickListener(listener);
if (selectedTeamNumber.equals(redTeams[0])) {
holder.red1.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
holder.red1.setTypeface(Typeface.DEFAULT);
}
holder.red2.setText(redTeams[1]);
holder.red2.setTag("frc" + redTeams[1]+"@"+eventKey);
holder.red2.setOnClickListener(listener);
if (selectedTeamNumber.equals(redTeams[1])) {
holder.red2.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
holder.red2.setTypeface(Typeface.DEFAULT);
}
if (redTeams.length == 2) {
holder.red3.setVisibility(View.GONE);
} else {
holder.red3.setVisibility(View.VISIBLE);
holder.red3.setText(redTeams[2]);
holder.red3.setTag("frc" + redTeams[2]+"@"+eventKey);
holder.red3.setOnClickListener(listener);
if (selectedTeamNumber.equals(redTeams[2])) {
holder.red3.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
holder.red3.setTypeface(Typeface.DEFAULT);
}
}
}
if (blueTeams.length == 0) {
holder.blue1.setText("");
holder.blue2.setText("");
holder.blue3.setText("");
} else {
holder.blue1.setText(blueTeams[0]);
holder.blue1.setTag("frc" + blueTeams[0]+"@"+eventKey);
holder.blue1.setOnClickListener(listener);
if (selectedTeamNumber.equals(blueTeams[0])) {
holder.blue1.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
holder.blue1.setTypeface(Typeface.DEFAULT);
}
holder.blue2.setText(blueTeams[1]);
holder.blue2.setTag("frc" + blueTeams[1]+"@"+eventKey);
holder.blue2.setOnClickListener(listener);
if (selectedTeamNumber.equals(blueTeams[1])) {
holder.blue2.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
holder.blue2.setTypeface(Typeface.DEFAULT);
}
if (blueTeams.length == 2) {
holder.blue3.setVisibility(View.GONE);
} else {
holder.blue3.setVisibility(View.VISIBLE);
holder.blue3.setText(blueTeams[2]);
holder.blue3.setTag("frc" + blueTeams[2]+"@"+eventKey);
holder.blue3.setOnClickListener(listener);
if (selectedTeamNumber.equals(blueTeams[2])) {
holder.blue3.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
holder.blue3.setTypeface(Typeface.DEFAULT);
}
}
}
holder.redScore.setText(redScore);
holder.blueScore.setText(blueScore);
return convertView;
}
private static class ViewHolder {
TextView matchTitle;
TextView red1;
TextView red2;
TextView red3;
TextView blue1;
TextView blue2;
TextView blue3;
TextView redScore;
TextView blueScore;
View redAlliance;
View blueAlliance;
ImageView videoIcon;
}
}
|
package imagej.ops.map;
/**
* Marker interface to mark {@link InplaceMapper}s
*
* @author Christian Dietz
*/
public interface InplaceMapper<A> extends Mapper<A, A> {
// NB: Marker interface
}
|
package org.opensingular.server.commons.spring.security.config.cas.util;
import org.apache.wicket.mock.MockApplication;
import org.apache.wicket.protocol.http.mock.MockHttpServletRequest;
import org.apache.wicket.protocol.http.mock.MockHttpServletResponse;
import org.apache.wicket.protocol.http.mock.MockHttpSession;
import org.apache.wicket.protocol.http.mock.MockServletContext;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.verification.Times;
import org.opensingular.server.commons.config.ServerContext;
import org.springframework.mock.web.MockFilterConfig;
import javax.servlet.FilterChain;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
public class SSOFilterTest {
public MockFilterConfig filterConfig;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Before
public void configureFilterConfig() {
MockApplication application = new MockApplication();
MockServletContext context = new MockServletContext(application, "");
context.setAttribute("nada", ServerContext.WORKLIST);
filterConfig = new MockFilterConfig(context);
filterConfig.addInitParameter(SSOFilter.URL_EXCLUDE_PATTERN_PARAM, "/rest");
filterConfig.addInitParameter(SSOFilter.CLIENT_LOGOUT_URL, "/logout");
filterConfig.addInitParameter(SSOConfigurableFilter.SINGULAR_CONTEXT_ATTRIBUTE, "nada");
request = new MockHttpServletRequest(application, new MockHttpSession(context), context){
@Override
public String getContextPath() {
return ServerContext.WORKLIST.getUrlPath();
}
};
response = new MockHttpServletResponse(request);
}
@Test
public void testLogout() throws Exception {
SSOFilter filter = spy(SSOFilter.class);
FilterChain filterChain = mock(FilterChain.class);
filter.init(filterConfig);
request.setURL("/worklist/logout");
filter.doFilter(request, response, filterChain);
verify(filterChain, new Times(0)).doFilter(request, response);
}
}
|
package de.gurkenlabs.litiengine.graphics;
import java.io.File;
import de.gurkenlabs.litiengine.resources.DataFormat;
public enum ImageFormat {
UNDEFINED, PNG, GIF, BMP, JPG;
public static ImageFormat get(String imageFormat) {
return DataFormat.get(imageFormat, values(), UNDEFINED);
}
public static boolean isSupported(File file) {
return isSupported(file.toString());
}
public static boolean isSupported(String fileName) {
return DataFormat.isSupported(fileName, values(), UNDEFINED);
}
public static String[] getAllExtensions() {
return DataFormat.getAllExtensions(values(), UNDEFINED);
}
public String toExtension() {
return "." + this.name().toLowerCase();
}
@Override
public String toString() {
return this.name().toLowerCase();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.