answer stringlengths 17 10.2M |
|---|
package de.retest.recheck.util;
import java.util.Locale;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.similarity.FuzzyScore;
public class StringSimilarity {
private StringSimilarity() {}
private static final FuzzyScore fuzzyScore = new FuzzyScore( Locale.GERMAN );
public static double textSimilarity( final String text0, final String text1 ) {
if ( text0 == null || text1 == null ) {
return simpleSimilarity( text0, text1 );
}
if ( text0.equals( text1 ) ) {
return 1.0;
}
final double fuzzyDistance = fuzzyScore.fuzzyScore( text0, text1 );
if ( fuzzyDistance == 0.0 ) {
return 0.0;
}
final double maxLength = Math.max( text0.length(), text1.length() );
final double similarity = fuzzyDistance / (maxLength * 4.0);
assert similarity >= 0.0 && similarity <= 1.0 : "text0 is: '" + text0 + "' - text1 is: '" + text1
+ "', result is:" + similarity;
return similarity;
}
public static double pathSimilarity( final String path0, final String path1 ) {
if ( path0 == null || path1 == null ) {
return simpleSimilarity( path0, path1 );
}
if ( path0.equals( path1 ) ) {
return 1.0;
}
final String cleanPath0 = removeBrackets( path0 );
final String cleanPath1 = removeBrackets( path1 );
if ( cleanPath0.isEmpty() || cleanPath1.isEmpty() ) {
return 0.0;
}
final int commonPrefixLength = StringUtils.getCommonPrefix( cleanPath0, cleanPath1 ).length();
final int commonSuffixLength = getCommonSuffixStartingAt( cleanPath0, cleanPath1, commonPrefixLength );
final int minLength = Math.min( cleanPath0.length(), cleanPath1.length() );
final int maxLength = Math.max( cleanPath0.length(), cleanPath1.length() );
final int difference =
Math.abs( minLength - (commonPrefixLength + commonSuffixLength) ) + maxLength - minLength;
double similarity = (maxLength - difference) / (double) maxLength;
similarity = similarity * similarity;
assert similarity >= 0.0 && similarity <= 1.0 : "path0 is: '" + path0 + "' - path1 is: '" + path1
+ "', result is:" + similarity;
return similarity;
}
private static int getCommonSuffixStartingAt( final String path0, final String path1, final int start ) {
int commonSuffixLength = 0;
for ( int idxP0 = path0.length() - 1, idxP1 = path1.length() - 1; idxP0 >= start
&& idxP1 >= start; idxP0--, idxP1-- ) {
final char c0 = path0.charAt( idxP0 );
final char c1 = path1.charAt( idxP1 );
if ( c0 == c1 ) {
commonSuffixLength++;
} else {
return commonSuffixLength;
}
}
return commonSuffixLength;
}
public static double simpleSimilarity( final String s0, final String s1 ) {
return Objects.equals( s0, s1 ) ? 1.0 : 0.0;
}
private static String removeBrackets( final String path ) {
return path.replaceAll( "[\\[\\]]", "" );
}
} |
package dinglydell.techresearch.gui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import dinglydell.techresearch.PlayerTechDataExtendedProps;
import dinglydell.techresearch.TechResearch;
import dinglydell.techresearch.event.TechKeyBindings;
import dinglydell.techresearch.network.PacketBuyTech;
import dinglydell.techresearch.researchtype.ResearchType;
import dinglydell.techresearch.techtree.NodeProgress;
import dinglydell.techresearch.techtree.TechNode;
public class GuiResearch extends GuiScreen {
private static final ResourceLocation TEXTURE = new ResourceLocation(
TechResearch.MODID + ":textures/gui/research.png");
private static final int GUI_WIDTH = 256;
private static final int GUI_HEIGHT = 164;
private static final int POINTS_WIDTH = 80;
private PlayerTechDataExtendedProps ptdep;
private Collection<TechNode> options;
private List<CostComponent> components = new ArrayList<CostComponent>();
public GuiResearch() {
ptdep = PlayerTechDataExtendedProps
.get(Minecraft.getMinecraft().thePlayer);
options = ptdep.getAvailableNodes();
}
@Override
public void initGui() {
super.initGui();
int i = 0;
buttonList.clear();
int offsetLeft = (width - GUI_WIDTH) / 2;
int offsetTop = (height - GUI_HEIGHT) / 2;
for (TechNode node : ptdep.getAvailableNodes()) {
buttonList.add(new OptionButton(i++,
offsetLeft + POINTS_WIDTH + 10, offsetTop + 8 + (i - 1)
* 39, 160, 30, node, ptdep.getProgress(node)));
}
int textX = 8;
int textY = 8;
// i = 0;
components.clear();
ResearchType rt = ResearchType.getTopType();
addComponents(rt, offsetLeft + textX, offsetTop + textY);
}
private int addComponents(ResearchType rt, int offsetLeft, int offsetTop) {
if (ptdep.hasDiscovered(rt)) {
addComponent(rt, offsetLeft, offsetTop);
int offsetChange = 16;
offsetTop += offsetChange;
offsetLeft += 4;
}
for (ResearchType child : rt.getChildren()) {
offsetTop = addComponents(child, offsetLeft, offsetTop);
}
return offsetTop;
// for (ResearchType rt : ResearchType.getTypes().values()) {
// if (rt.isBaseDiscoveredType(ptdep)
// && !(rt.isOtherType(ptdep) && ptdep
// .getDisplayResearchPoints(rt.name) == 0)) {
// components.add(new CostComponent(mc, offsetLeft + textX,
// offsetTop + textY + (i++ * 16), rt, ptdep
// .getDisplayResearchPoints(rt.name)));
}
private void addComponent(ResearchType rt, int offsetLeft, int offsetTop) {
components.add(new CostComponent(mc, offsetLeft, offsetTop, rt, Math
.round(rt.getValue(ptdep) * 100) / 100.0));
}
@Override
public void updateScreen() {
super.updateScreen();
}
@Override
protected void actionPerformed(GuiButton parButton) {
if (parButton instanceof OptionButton) {
OptionButton button = (OptionButton) parButton;
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
TechResearch.snw.sendToServer(new PacketBuyTech(button.tech));
}
}
@Override
public void drawScreen(int x, int y, float p_73863_3_) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.getTextureManager().bindTexture(TEXTURE);
int offsetLeft = (width - GUI_WIDTH) / 2;
int offsetTop = (height - GUI_HEIGHT) / 2;
drawTexturedModalRect(offsetLeft,
offsetTop,
0,
0,
GUI_WIDTH,
GUI_HEIGHT);
List<String> tooltip = new ArrayList<String>();
for (CostComponent cost : components) {
cost.drawCost();
boolean isHovering = cost.isHovering(x, y);
if (isHovering) {
cost.addTooltip(tooltip, true);
}
}
// int textX = 8;
// int textY = 8;
// float scale = 0.8f;
// GL11.glScalef(scale, scale, scale);
// draw stuff
// for (ResearchType rt : ResearchType.getTypes().values()) {
// if (rt.isBaseDiscoveredType(ptdep)) {
// String displayName = rt.getDisplayName();
// if (rt.isOtherType(ptdep)) {
// if (ptdep.getDisplayResearchPoints(rt.name) == 0) {
// continue;
// displayName = StatCollector
// .translateToLocal("gui.techresearch.other")
// + displayName;
// String drawStr = displayName + ": "
// + ptdep.getDisplayResearchPoints(rt.name);
// if (fontRendererObj.getStringWidth(drawStr) > POINTS_WIDTH) {
// drawStr = (rt.isOtherType(ptdep) ? "O. " : "")
// + rt.getDisplayName().substring(0, 3) + ": "
// + ptdep.getDisplayResearchPoints(rt.name);
// // fontRendererObj.drawString(drawStr,
// // (int) ((offsetLeft + textX) / scale),
// // (int) ((offsetTop + textY) / scale),
// // 16777215,
// // false);
// int trueX = (int) ((offsetLeft + textX) / scale);
// int trueY = (int) ((offsetTop + textY) / scale);
// mc.getTextureManager().bindTexture(rt.icon);
// float texScale = 1 / 24f;
// scaleIcon();
// drawTexturedModalRect((int) (trueX / texScale),
// (int) (trueY / texScale),
// 256,
// 256);
// unscaleIcon();
// fontRendererObj.drawString(""
// + ptdep.getDisplayResearchPoints(rt.name),
// trueX + 12,
// trueY,
// 0xFFFFFF,
// false);
// textY += 20;
// GL11.glScalef(1 / scale, 1 / scale, 1 / scale);
super.drawScreen(x, y, p_73863_3_);
for (Object b : buttonList) {
OptionButton ob = ((OptionButton) b);
if (ob.hovering) {
ob.addTooltip(tooltip);
}
}
this.drawHoveringText(tooltip, x, y, fontRendererObj);
}
static void scaleIcon() {
float texScale = 1 / 24f;
GL11.glScalef(texScale, texScale, texScale);
}
static void unscaleIcon() {
float texScale = 1 / 24f;
GL11.glScalef(1 / texScale, 1 / texScale, 1 / texScale);
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
@Override
protected void keyTyped(char key, int keyCode) {
super.keyTyped(key, keyCode);
if (TechKeyBindings.openTable.getKeyCode() == keyCode) {
mc.thePlayer.closeScreen();
}
}
public static void openGui() {
Minecraft.getMinecraft().displayGuiScreen(new GuiResearch());
}
@SideOnly(Side.CLIENT)
static class CostComponent extends Gui {
private static final float SCALE = 1 / 20f;
// private PlayerTechDataExtendedProps ptdep;
private ResearchType type;
private double cost;
private int posX;
private int posY;
private Minecraft mc;
public CostComponent(Minecraft mc, int x, int y, ResearchType type,
double cost) {
this.mc = mc;
this.type = type;
this.cost = cost;
posX = x;
posY = y;
}
public boolean isHovering(int x, int y) {
return (x >= this.posX && y >= this.posY
&& x < this.posX + this.getWidth() && y < this.posY + 16);
}
public int getWidth() {
FontRenderer fontrenderer = mc.fontRenderer;
return (int) (256 * SCALE)
+ fontrenderer.getStringWidth("" + getCostString());
}
public void drawCost() {
FontRenderer fontrenderer = mc.fontRenderer;
int height = 16;
mc.getTextureManager().bindTexture(type.icon);
float scale = SCALE;
GL11.glScalef(scale, scale, scale);
drawTexturedModalRect((int) (posX / scale),
(int) (posY / scale),
0,
0,
256,
256);
GL11.glScalef(1 / scale, 1 / scale, 1 / scale);
fontrenderer.drawString(getCostString(),
posX + 16,
posY + (int) (256 * scale / 2) - fontrenderer.FONT_HEIGHT
/ 2,
0xFFFFFF,
false);
}
private String getCostString() {
return ((int) this.cost == this.cost ? ("" + (int) this.cost)
: ("" + this.cost));
}
public void addTooltip(List<String> tooltip) {
addTooltip(tooltip, false);
}
public void addTooltip(List<String> tooltip, boolean verbose) {
tooltip.add(type.getDisplayName() + ": " + getCostString());
if (verbose) {
ResearchType parent = type.getParentType();
List<ResearchType> parents = new ArrayList<ResearchType>();
while (parent != null) {
parents.add(parent);
parent = parent.getParentType();
}
for (int i = 1; i <= parents.size(); i++) {
parent = parents.get(parents.size() - i);
char[] indent = new char[i];
Arrays.fill(indent, ' ');
String indentString = new String(indent);
tooltip.add(indentString + "-" + parent.getDisplayName());
}
}
}
}
@SideOnly(Side.CLIENT)
static class OptionButton extends GuiButton {
public boolean hovering;
TechNode tech;
private NodeProgress progress;
private List<CostComponent> components = new ArrayList<CostComponent>();
public OptionButton(int id, int x, int y, int width, int height,
TechNode tech, NodeProgress progress) {
super(id, x, y, width, height, tech.getDisplayName());
this.tech = tech;
this.progress = progress;
this.visible = true;
Minecraft mc = Minecraft.getMinecraft();
FontRenderer fontrenderer = mc.fontRenderer;
int costX = 2 * (x + 1);
for (Entry<ResearchType, Double> cost : tech.costs.entrySet()) {
CostComponent cc = new CostComponent(mc, costX,
2 * (y + height - 8), cost.getKey(), cost.getValue());
components.add(cc);
costX += cc.getWidth() + 2;
}
}
public void addTooltip(List<String> tooltip) {
tooltip.add(tech.type.getChatColour() + tech.getDisplayName());
for (CostComponent cost : components) {
cost.addTooltip(tooltip);
}
List<Item> unlocked = tech.getItemsUnlocked();
if (unlocked.size() > 0) {
tooltip.add(StatCollector
.translateToLocal("gui.techresearch.tooltip.unlocks"));
for (Item it : unlocked) {
tooltip.add(" "
+ StatCollector.translateToLocal(it
.getUnlocalizedName() + ".name"));
}
}
String typeDesc = tech.type.getDescription();
if (typeDesc != null) {
tooltip.add(tech.type.getChatColour() + ""
+ EnumChatFormatting.ITALIC + typeDesc);
}
String desc = tech.getDescription();
if (!desc.contains(".desc")) {
tooltip.add("");
int n = 40;
// int repeat = (int) Math.ceil(desc.length() / (double) n);
int end = n;
for (int i = 0; i < desc.length(); i = end, end += n) {
while (end < desc.length()
&& end > i
&& !(desc.charAt(end) == ' ' || desc
.charAt(end - 1) == ' ')) {
end
}
if (end == i) {
end += n;
}
tooltip.add(desc.substring(i, Math.min(desc.length(), end)));
}
}
}
@Override
public void drawButton(Minecraft mc, int parX, int parY) {
if (visible) {
FontRenderer fontrenderer = mc.fontRenderer;
hovering = (parX >= xPosition && parY >= yPosition
&& parX < xPosition + width && parY < yPosition
+ height);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
mc.getTextureManager().bindTexture(TEXTURE);
int textureX = 0;
int textureY = GUI_HEIGHT + 1;
if (hovering) {
textureY += height + 1;
}
drawTexturedModalRect(xPosition,
yPosition,
textureX,
textureY,
width,
height);
fontrenderer.drawString(tech.getDisplayName(),
xPosition + 2,
yPosition + height / 3,
0xFFFFFF,
false);
float scale = 0.5f;
GL11.glScalef(scale, scale, scale);
for (CostComponent cost : components) {
cost.drawCost();
}
int newX = (int) (xPosition / scale);
int newY = (int) (yPosition / scale);
fontrenderer.drawString(tech.type.getDisplayName(),
newX + 2,
(int) (yPosition / scale + 2),
tech.type.getColour(),
false);
// String str;
// if (progress == null) {
// str = tech.costsAsString();
// } else {
// str = tech.costsAsString(progress);
// fontrenderer.drawString(tech.costsAsString(),
// newX + 2,
// newY + (int) (height / scale)
// - fontrenderer.FONT_HEIGHT,
// 0xFFFFFF);
GL11.glScalef(1 / scale, 1 / scale, 1 / scale);
}
}
}
} |
package foodtruck.socialmedia;
import java.net.URI;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.sun.jersey.api.client.WebResource;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import foodtruck.dao.TruckDAO;
import foodtruck.model.StaticConfig;
import foodtruck.model.Story;
import foodtruck.model.StoryType;
import foodtruck.model.Truck;
import foodtruck.util.Clock;
import foodtruck.util.FacebookTimeFormat;
import foodtruck.util.Secondary;
/**
* @author aviolette
* @since 8/26/15
*/
public class FacebookConnector implements SocialMediaConnector {
private static final Logger log = Logger.getLogger(FacebookConnector.class.getName());
private final WebResource facebook;
private final StaticConfig config;
private final Clock clock;
private final DateTimeFormatter formatter;
private final TruckDAO truckDAO;
@Inject
public FacebookConnector(@FacebookEndpoint WebResource facebookEndpoint, StaticConfig config,
Clock clock, @FacebookTimeFormat DateTimeFormatter formatter,
@Secondary TruckDAO truckDAO) {
this.facebook = facebookEndpoint;
this.config = config;
this.clock = clock;
this.formatter = formatter;
this.truckDAO = truckDAO;
}
@Override
public List<Story> recentStories() {
ImmutableList.Builder<Story> stories = ImmutableList.builder();
for (Truck truck : truckDAO.findFacebookTrucks()) {
try {
stories.addAll(retrieveStoriesForTruck(truck));
} catch (Exception e) {
log.log(Level.WARNING, e.getMessage(), e);
}
}
return stories.build();
}
private ImmutableList<Story> retrieveStoriesForTruck(Truck truck) throws JSONException {
JSONObject json = facebook.uri(URI.create("/v2.4" + truck.getFacebook() + "/posts"))
.queryParam("access_token", config.getFacebookAccessToken())
.header("Accept", "application/json")
.get(JSONObject.class);
JSONArray data = json.getJSONArray("data");
DateTime start = clock.currentDay().toDateTimeAtStartOfDay();
ImmutableList.Builder<Story> stories = ImmutableList.builder();
boolean first = true;
for (int i=0; i < data.length(); i++) {
JSONObject storyObj = data.getJSONObject(i);
if (!storyObj.has("message")) {
continue;
}
String id = storyObj.getString("id");
if (id.equals(truck.getLastScanned())) {
break;
}
if (first) {
truck = Truck.builder(truck).lastScanned(id).build();
truckDAO.save(truck);
first = false;
}
DateTime createTime = formatter.parseDateTime(storyObj.getString("created_time"));
if (createTime.isBefore(start)) {
break;
}
createTime = clock.now();
String message = storyObj.getString("message");
stories.add(Story.builder()
.text(message)
// This is a bad assumption to make, but the easiest way to get it to work across the board
.userId(truck.getTwitterHandle())
.time(createTime)
.type(StoryType.FACEBOOK)
.build());
}
return stories.build();
}
} |
package ge.edu.freeuni.sdp.arkanoid.model;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Point;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Rectangle;
public abstract class Brick extends Gobj<Rectangle> {
private final BrickColor _color;
private final Capsule _capsule;
private final int _score;
private boolean _isAlive;
Brick(Point position, BrickColor color, Capsule capsule) {
super(position);
_color = color;
_capsule = capsule;
_score = 50;
_isAlive = true;
}
@Override
public GobjKind getKind() {
return GobjKind.Brick;
}
public void interact(Gobj other) {
if (other instanceof Ball) {
_capsule.release(getPosition());
_isAlive = false;
} else if (other instanceof MovementKillerBrick){
_isAlive = false;
}
}
public int getScore() {
return this._score;
}
@Override
public boolean isAlive() {
return _isAlive;
}
public BrickColor getColor() {
return _color;
}
} |
package hudson.plugins.jira;
import hudson.Util;
import hudson.model.AbstractProject;
import hudson.model.Job;
import hudson.model.JobProperty;
import hudson.model.JobPropertyDescriptor;
import hudson.util.CopyOnWriteList;
import hudson.util.FormFieldValidator;
import org.apache.axis.AxisFault;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import javax.xml.rpc.ServiceException;
import java.io.IOException;
import java.net.URL;
/**
* Associates {@link AbstractProject} with {@link JiraSite}.
*
* @author Kohsuke Kawaguchi
*/
public class JiraProjectProperty extends JobProperty<AbstractProject<?,?>> {
/**
* Used to find {@link JiraSite}. Matches {@link JiraSite#getName()}.
* Always non-null (but beware that this value might become stale
* if the system config is changed.)
*/
public final String siteName;
/**
* @stapler-constructor
*/
public JiraProjectProperty(String siteName) {
if(siteName==null) {
// defaults to the first one
JiraSite[] sites = DESCRIPTOR.getSites();
if(sites.length>0)
siteName = sites[0].getName();
}
this.siteName = siteName;
}
/**
* Gets the {@link JiraSite} that this project belongs to.
*
* @return
* null if the configuration becomes out of sync.
*/
public JiraSite getSite() {
JiraSite[] sites = DESCRIPTOR.getSites();
if(siteName==null && sites.length>0)
// default
return sites[0];
for( JiraSite site : sites ) {
if(site.getName().equals(siteName))
return site;
}
return null;
}
public DescriptorImpl getDescriptor() {
return DESCRIPTOR;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends JobPropertyDescriptor {
private final CopyOnWriteList<JiraSite> sites = new CopyOnWriteList<JiraSite>();
public DescriptorImpl() {
super(JiraProjectProperty.class);
load();
}
public boolean isApplicable(Class<? extends Job> jobType) {
return AbstractProject.class.isAssignableFrom(jobType);
}
public String getDisplayName() {
return "Associated JIRA";
}
public JiraSite[] getSites() {
return sites.toArray(new JiraSite[0]);
}
public JobProperty<?> newInstance(StaplerRequest req) throws FormException {
JiraProjectProperty jpp = req.bindParameters(JiraProjectProperty.class, "jira.");
if(jpp.siteName==null)
jpp = null; // not configured
return jpp;
}
public boolean configure(StaplerRequest req) {
sites.replaceBy(req.bindParametersToList(JiraSite.class,"jira."));
save();
return true;
}
/**
* Checks if the JIRA URL is accessible and exists.
*/
public void doUrlCheck(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this can be used to check existence of any file in any URL, so admin only
new FormFieldValidator.URLCheck(req,rsp) {
protected void check() throws IOException, ServletException {
String url = Util.fixEmpty(request.getParameter("value"));
if(url==null) {
error("JIRA URL is a mandatory field");
return;
}
try {
if(findText(open(new URL(url)),"Atlassian JIRA"))
ok();
else
error("This is a valid URL but it doesn't look like JIRA");
} catch (IOException e) {
handleIOException(url,e);
}
}
}.process();
}
/**
* Checks if the user name and password are valid.
*/
public void doLoginCheck(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(req,rsp,false) {
protected void check() throws IOException, ServletException {
String url = Util.fixEmpty(request.getParameter("url"));
if(url==null) {// URL not entered yet
ok();
return;
}
JiraSite site = new JiraSite(new URL(url),
request.getParameter("user"),
request.getParameter("pass"));
try {
site.createSession();
ok();
} catch (AxisFault e) {
error(e.getFaultString());
} catch (ServiceException e) {
error(e.getMessage());
}
}
}.process();
}
}
} |
package hudson.plugins.templateproject;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.console.HyperlinkNote;
import hudson.Util;
import hudson.model.BuildListener;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.Node;
import hudson.model.Run;
import hudson.scm.ChangeLogParser;
import hudson.scm.NullSCM;
import hudson.scm.PollingResult;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.scm.SCM;
import hudson.security.AccessControlled;
import hudson.tasks.Messages;
import hudson.util.FormValidation;
import java.io.File;
import java.io.IOException;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import java.util.List;
import org.jenkinsci.plugins.multiplescms.MultiSCM;
import org.jenkinsci.plugins.multiplescms.MultiSCMRevisionState;
public class ProxySCM extends SCM {
private final String projectName;
@DataBoundConstructor
public ProxySCM(String projectName) {
this.projectName = projectName;
}
public String getProjectName() {
return projectName;
}
public String getExpandedProjectName(AbstractBuild<?, ?> build) {
return TemplateUtils.getExpandedProjectName(projectName, build);
}
// Primarily used for polling, not building.
public AbstractProject<?, ?> getProject() {
return TemplateUtils.getProject(projectName, null);
}
public SCM getProjectScm(AbstractBuild<?, ?> build) {
try {
return TemplateUtils.getProject(projectName, build).getScm();
} catch (Exception e) {
return new NullSCM();
}
}
public SCM getProjectScm() {
return getProjectScm(null);
}
public void checkout(@Nonnull Run<?,?> build, @Nonnull Launcher launcher, @Nonnull FilePath workspace,
@Nonnull TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState baseline)
throws IOException, InterruptedException {
// Unique situation where MultiSCM has $None for SCMRevisionState
// Potentially due to SCM polling and references lost, or fixed with:
// Since MultiSCM is optional, might not be installed, hacky check string name.
if (getProjectScm((AbstractBuild) build).toString().contains("multiplescms")) {
if ((baseline == SCMRevisionState.NONE) || (baseline == null)) {
baseline = new MultiSCMRevisionState();
}
}
AbstractProject p = TemplateUtils.getProject(getProjectName(), (AbstractBuild) build);
listener.getLogger().println("[TemplateProject] Using SCM from: " + HyperlinkNote.encodeTo('/'+ p.getUrl(), p.getFullDisplayName()));
getProjectScm((AbstractBuild) build).checkout(build, launcher, workspace, listener, changelogFile, baseline);
}
@Override
public ChangeLogParser createChangeLogParser() {
return getProjectScm().createChangeLogParser();
}
@Override
@Deprecated
public boolean pollChanges(AbstractProject project, Launcher launcher,
FilePath workspace, TaskListener listener) throws IOException,
InterruptedException {
return getProjectScm().pollChanges(project, launcher, workspace, listener);
}
@Extension
public static class DescriptorImpl extends SCMDescriptor {
public DescriptorImpl() {
super(null);
}
@Override
public String getDisplayName() {
return "Use SCM from another project";
}
/**
* Form validation method.
*/
public FormValidation doCheckProjectName(@AncestorInPath AccessControlled anc, @QueryParameter String value) {
if (!anc.hasPermission(Item.CONFIGURE)) return FormValidation.ok();
//this check is important because otherwise plugin will check for similar project which impacts performance
//the check will be performed even if this plugin is not used as SCM for the current project
if(StringUtils.isEmpty(value)) {
return FormValidation.error("Project cannot be empty");
}
Item item = Hudson.getInstance().getItemByFullName(value, Item.class);
if (item == null) {
return FormValidation.error(Messages.BuildTrigger_NoSuchProject(value,
AbstractProject.findNearest(value).getName()));
}
if (!(item instanceof AbstractProject)) {
return FormValidation.error(Messages.BuildTrigger_NotBuildable(value));
}
return FormValidation.ok();
}
}
// If a Parameter is used for projectName, some of these won't return anythign useful.
// Because of it's nature `expand()`-ing the parameter is only useful at run time.
@Override
public RepositoryBrowser getBrowser() {
return getProjectScm().getBrowser();
}
@Override
public FilePath getModuleRoot(FilePath workspace) {
return getProjectScm().getModuleRoot(workspace);
}
@Override
public FilePath[] getModuleRoots(FilePath workspace) {
return getProjectScm().getModuleRoots(workspace);
}
@Override
public boolean processWorkspaceBeforeDeletion(
AbstractProject<?, ?> project, FilePath workspace, Node node)
throws IOException, InterruptedException {
return getProjectScm().processWorkspaceBeforeDeletion(project, workspace, node);
}
@Override
public boolean requiresWorkspaceForPolling() {
return getProjectScm().requiresWorkspaceForPolling();
}
@Override
public boolean supportsPolling() {
// @TODO: worth adding check if expandedProjectName even exists?
// If still $PROJECT, won't expand so nothing to poll.
return getProjectScm().supportsPolling();
}
@Override
public void buildEnvVars(AbstractBuild<?, ?> build, java.util.Map<String, String> env) {
getProjectScm(build).buildEnvVars(build, env);
}
@Override
public SCMRevisionState calcRevisionsFromBuild(AbstractBuild<?, ?> paramAbstractBuild, Launcher paramLauncher,
TaskListener paramTaskListener) throws IOException, InterruptedException {
return getProjectScm(paramAbstractBuild).calcRevisionsFromBuild(paramAbstractBuild, paramLauncher, paramTaskListener);
}
@Override
protected PollingResult compareRemoteRevisionWith(AbstractProject<?, ?> project, Launcher launcher,
FilePath workspace, TaskListener listener, SCMRevisionState baseline)
throws IOException, InterruptedException {
return getProjectScm().poll(project, launcher, workspace, listener, baseline);
}
} |
package info.gameboxx.gameboxx.util;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.Collection;
/**
* A {@link Sound} with a volume and pitch.
* Has a bunch of methods to play the sounds.
*/
public class SoundEffect {
private Sound sound;
private String customSound;
private float volume = 1;
private float pitch = 1;
/**
* Creates a new SoundEffect instance with the specified volume and pitch.
* @param sound The {@link Sound} effect.
* @param volume The volume (This should be a float between 0,2)
* @param pitch The pitch (This should be a float between 0,2)
*/
public SoundEffect(Sound sound, float volume, float pitch) {
this.sound = sound;
this.volume = volume;
this.pitch = pitch;
}
/**
* Creates a new SoundEffect instance with default volume and pitch.
* @param sound The {@link Sound} effect.
*/
public SoundEffect(Sound sound) {
this.sound = sound;
}
/**
* Creates a new SoundEffect instance with the specified volume and pitch.
* @param customSound The name of the custom sound effect.
* This name must be the name of a sound defined in a server resource pack.
* If no sound is found with this name and you play the sound nothing will happen.
* @param volume The volume (This should be a float between 0,2)
* @param pitch The pitch (This should be a float between 0,2)
*/
public SoundEffect(String customSound, float volume, float pitch) {
this.customSound = customSound;
this.volume = volume;
this.pitch = pitch;
}
/**
* Creates a new SoundEffect instance with default volume and pitch.
* @param customSound The name of the custom sound effect.
* This name must be the name of a sound defined in a server resource pack.
* If no sound is found with this name and you play the sound nothing will happen.
*/
public SoundEffect(String customSound) {
this.customSound = customSound;
}
/**
* Get the {@link Sound} effect.
* @return The {@link Sound} effect. (May be {@code null} when constructed with a custom sound!)
*/
public Sound getSound() {
return sound;
}
/**
* Get the name of the custom sound effect.
* @return The name of the custom sound effect. (May be {@code null} when constructed with a regular sound!)
*/
public String getCustomSound() {
return customSound;
}
/**
* Set the {@link Sound} effect.
* @param sound The {@link Sound} effect.
*/
public void setSound(Sound sound) {
this.sound = sound;
}
/**
* Set the custom sound effect.
* This name must be the name of a sound defined in a server resource pack.
* If no sound is found with this name and you play the sound nothing will happen.
* @param customSound Name of the custom sound effect.
*/
public void setCustomSound(String customSound) {
this.customSound = customSound;
}
/**
* Get the volume for the sound.
* @return The volume.
*/
public float getVolume() {
return volume;
}
/**
* Set the volume for the sound.
* @param volume The volume. (This should be a float between 0,2)
*/
public void setVolume(float volume) {
this.volume = volume;
}
/**
* Get the pitch for the sound.
* @return The pitch.
*/
public float getPitch() {
return pitch;
}
/**
* SEt the pitch for the sound.
* @param pitch The pitch. (This should be a float between 0,2)
*/
public void setPitch(float pitch) {
this.pitch = pitch;
}
/**
* Play the sound for the player only at the player location.
* @see Player#playSound(Location, Sound, float, float)
*/
public void play(Player player) {
play(player, player.getLocation());
}
/**
* Play the sound for the player only at the specified location.
* @see Player#playSound(Location, Sound, float, float)
*/
public void play(Player player, Location location) {
if (customSound != null) {
player.playSound(location, customSound, volume, pitch);
} else {
player.playSound(location, sound, volume, pitch);
}
}
/**
* Play the sound for the player only at the player location with a certain offset.
* @see Player#playSound(Location, Sound, float, float)
*/
public void play(Player player, double offsetX, double offsetY, double offsetZ) {
play(player, player.getLocation().add(offsetX, offsetY, offsetZ));
}
/**
* Play the sound for all players in the specified world.
* @see Player#playSound(Location, Sound, float, float)
*/
public void play(World world) {
play(Bukkit.getServer().getOnlinePlayers());
}
/**
* Play the sound for all players in the specified world.
* The sound will be played at each players location with the specified offset.
* @see Player#playSound(Location, Sound, float, float)
*/
public void play(World world, double offsetX, double offsetY, double offsetZ) {
play(Bukkit.getServer().getOnlinePlayers(), offsetX, offsetY, offsetZ);
}
/**
* Play the sound for all the listed players specified.
* The sound will be played at each players location.
* @see Player#playSound(Location, Sound, float, float)
*/
public void play(Collection<? extends Player> players) {
for (Player player : Bukkit.getOnlinePlayers()) {
play(player);
}
}
/**
* Play the sound for all the listed players specified.
* The sound will be played at each players location with the specified offset.
* @see Player#playSound(Location, Sound, float, float)
*/
public void play(Collection<? extends Player> players, double offsetX, double offsetY, double offsetZ) {
for (Player player : Bukkit.getOnlinePlayers()) {
play(player, offsetX, offsetY, offsetZ);
}
}
/**
* Play the sound for all players nearby the specified location.
* <b>This does not support custom sounds!</b>
* @see World#playSound(Location, Sound, float, float)
*/
public void play(World world, Location location) {
if (sound != null) {
world.playSound(location, sound, volume, pitch);
}
}
} |
/**
* Part of Employ
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DashboardFrame extends CommonFrame implements ActionListener {
JButton buttonAddData = new JButton("Add");
JButton buttonDeleteData = new JButton("Delete");
JTextField textNumber = new JTextField(10);
JTextField textOutput = new JTextField(10);
// define dashboard for special frame
public DashboardFrame() {
super("Dashboard");
buttonAddData.setActionCommand("addData");
buttonDeleteData.setActionCommand("deleteData");
buttonAddData.addActionListener(this);
buttonDeleteData.addActionListener(this);
textNumber.addActionListener(this);
add(buttonAddData);
add(buttonDeleteData);
add(textNumber);
add(textOutput);
}
// define listener action when button "Add" is clicked
public void actionPerformed(ActionEvent event) {
String inputNumber = textNumber.getText();
textOutput.setText(inputNumber);
if (event.getActionCommand().equals("addData"))
getContentPane().setBackground(Color.white);
else if (event.getActionCommand().equals("deleteData"))
getContentPane().setBackground(Color.darkGray);
else
getContentPane().setBackground(Color.black);
repaint();
}
} |
package innovimax.mixthem.interfaces;
import java.io.IOException;
public interface IInputChar {
/**
* Returns true if there is more characters.
* @return Returns true if there is more characters
* @throws IOException - If an I/O error occurs
*/
public boolean hasCharacter() throws IOException;
/**
* Reads a single character
* @return The character read as an int, or -1 if there is no more characters.
* @throws IOException - If an I/O error occurs
*/
public int nextCharacter() throws IOException;
/**
* Reads characters into a portion of an array.
* @param buffer Destination buffer
* @param len - Maximum number of characters to read
* @return The number of characters read, or -1 if there is no more characters
* @throws IOException - If an I/O error occurs
*/
public int nextCharacters(char[] buffer, int len) throws IOException;
/**
* Closes this input and releases any system resources associated with it.
* @throws IOException - If an I/O error occurs
*/
public void close() throws IOException;
} |
/**
* Part of Employ
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DashboardFrame extends CommonFrame implements ActionListener {
JButton buttonAddData = new JButton("Add");
JButton buttonDeleteData = new JButton("Delete");
JTextField textInputNumber = new JTextField(10);
JTextField textOutputNumber = new JTextField(10);
// define dashboard for special frame
public DashboardFrame() {
super("Dashboard");
buttonAddData.setActionCommand("addData");
buttonDeleteData.setActionCommand("deleteData");
buttonAddData.addActionListener(this);
buttonDeleteData.addActionListener(this);
textInputNumber.addActionListener(this);
textOutputNumber.setEditable(false);
add(buttonAddData);
add(buttonDeleteData);
add(textInputNumber);
add(textOutputNumber);
}
// get input number in text input
void getTextInput() {
String inputNumber = textInputNumber.getText();
textOutputNumber.setText(inputNumber);
}
// clear input number in text input
void clearInputNumber() {
textOutputNumber.setText("");
}
// define listener action when button is clicked
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("addData"))
getTextInput();
else if (event.getActionCommand().equals("deleteData"))
clearInputNumber();
else
getContentPane().setBackground(Color.white);
repaint();
}
} |
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// File created: 2012-02-22 20:40:39
package fi.tkk.ics.hadoop.bam;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import net.sf.samtools.SAMFileReader;
/** An {@link org.apache.hadoop.mapreduce.InputFormat} for SAM and BAM files.
* Values are the individual records; see {@link BAMRecordReader} for the
* meaning of the key.
*
* <p>By default, files are recognized as SAM or BAM based on their file
* extensions: see {@link #TRUST_EXTS_PROPERTY}. If that fails, or this
* behaviour is disabled, the first byte of each file is read to determine the
* file type.</p>
*/
public class AnySAMInputFormat
extends FileInputFormat<LongWritable,SAMRecordWritable>
{
/** A Boolean property: are file extensions trusted? The default is
* <code>true</code>.
*
* @see SAMFormat#inferFromFilePath
*/
public static final String TRUST_EXTS_PROPERTY =
"hadoopbam.anysam.trust-exts";
private final BAMInputFormat bamIF = new BAMInputFormat();
private final SAMInputFormat samIF = new SAMInputFormat();
private final Map<Path,SAMFormat> formatMap;
private final boolean givenMap;
private Configuration conf;
private boolean trustExts;
public AnySAMInputFormat() {
this.formatMap = new HashMap<Path,SAMFormat>();
this.givenMap = false;
this.conf = null;
}
/** Creates a new input format, reading {@link #TRUST_EXTS_PROPERTY} from
* the given <code>Configuration</code>.
*/
public AnySAMInputFormat(Configuration conf) {
this.formatMap = new HashMap<Path,SAMFormat>();
this.conf = conf;
this.trustExts = conf.getBoolean(TRUST_EXTS_PROPERTY, true);
this.givenMap = false;
}
/** Creates a new input format, trusting the given <code>Map</code> to
* define the file-to-format associations. Neither file paths nor their
* contents are looked at, only the <code>Map</code> is used.
*
* <p>The <code>Map</code> is not copied, so it should not be modified while
* this input format is in use!</p>
* */
public AnySAMInputFormat(Map<Path,SAMFormat> formatMap) {
this.formatMap = formatMap;
this.givenMap = true;
// Arbitrary values.
this.conf = null;
this.trustExts = false;
}
public SAMFormat getFormat(final Path path) {
SAMFormat fmt = formatMap.get(path);
if (fmt != null || formatMap.containsKey(path))
return fmt;
if (givenMap)
throw new IllegalArgumentException(
"SAM format for '"+path+"' not in given map");
if (this.conf == null)
throw new IllegalStateException("Don't have a Configuration yet");
if (trustExts) {
final SAMFormat f = SAMFormat.inferFromFilePath(path);
if (f != null) {
formatMap.put(path, f);
return f;
}
}
try {
fmt = SAMFormat.inferFromData(path.getFileSystem(conf).open(path));
} catch (IOException e) {}
formatMap.put(path, fmt);
return fmt;
}
@Override public RecordReader<LongWritable,SAMRecordWritable>
createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws InterruptedException, IOException
{
final Path path;
if (split instanceof FileSplit)
path = ((FileSplit)split).getPath();
else if (split instanceof FileVirtualSplit)
path = ((FileVirtualSplit)split).getPath();
else
throw new IllegalArgumentException(
"split '"+split+"' has unknown type: cannot extract path");
if (this.conf == null)
this.conf = ctx.getConfiguration();
final SAMFormat fmt = getFormat(path);
if (fmt == null)
throw new IllegalArgumentException(
"unknown SAM format, cannot create RecordReader: "+path);
switch (fmt) {
case SAM: return samIF.createRecordReader(split, ctx);
case BAM: return bamIF.createRecordReader(split, ctx);
default: assert false; return null;
}
}
/** Defers to {@link BAMInputFormat} or {@link SAMInputFormat} as
* appropriate for the given path.
*/
@Override public boolean isSplitable(JobContext job, Path path) {
if (this.conf == null)
this.conf = job.getConfiguration();
final SAMFormat fmt = getFormat(path);
if (fmt == null)
return super.isSplitable(job, path);
switch (fmt) {
case SAM: return samIF.isSplitable(job, path);
case BAM: return bamIF.isSplitable(job, path);
default: assert false; return false;
}
}
/** Defers to {@link BAMInputFormat} as appropriate for each individual
* path. SAM paths do not require special handling, so their splits are left
* unchanged.
*/
@Override public List<InputSplit> getSplits(JobContext job)
throws IOException
{
if (this.conf == null)
this.conf = job.getConfiguration();
final List<InputSplit> origSplits = super.getSplits(job);
// We have to partition the splits by input format and hand them over to
// the *InputFormats for any further handling.
// At least for now, BAMInputFormat is the only one that needs to mess
// with them any further, so we can just extract the BAM ones and leave
// the rest as they are.
final List<InputSplit>
bamOrigSplits = new ArrayList<InputSplit>(origSplits.size()),
newSplits = new ArrayList<InputSplit>(origSplits.size());
for (final InputSplit iSplit : origSplits) {
final FileSplit split = (FileSplit)iSplit;
if (SAMFormat.BAM.equals(getFormat(split.getPath())))
bamOrigSplits.add(split);
else
newSplits.add(split);
}
newSplits.addAll(bamIF.getSplits(bamOrigSplits, job.getConfiguration()));
return newSplits;
}
} |
package foam.nanos.auth;
import foam.core.ContextAwareSupport;
import foam.core.X;
import foam.dao.ArraySink;
import foam.dao.DAO;
import foam.dao.Sink;
import foam.mlang.MLang;
import foam.nanos.logger.Logger;
import foam.nanos.NanoService;
import foam.nanos.session.Session;
import foam.util.Email;
import foam.util.Password;
import foam.util.SafetyUtil;
import javax.security.auth.AuthPermission;
import java.security.Permission;
import java.util.Calendar;
import java.util.List;
import static foam.mlang.MLang.AND;
import static foam.mlang.MLang.EQ;
public class UserAndGroupAuthService
extends ContextAwareSupport
implements AuthService, NanoService
{
protected DAO userDAO_;
protected DAO groupDAO_;
protected DAO sessionDAO_;
public final static String CHECK_USER_PERMISSION = "service.auth.checkUser";
public UserAndGroupAuthService(X x) {
setX(x);
}
@Override
public void start() {
userDAO_ = (DAO) getX().get("localUserDAO");
groupDAO_ = (DAO) getX().get("localGroupDAO");
sessionDAO_ = (DAO) getX().get("sessionDAO");
}
public User getCurrentUser(X x) throws AuthenticationException {
// fetch context and check if not null or user id is 0
Session session = x.get(Session.class);
if ( session == null || session.getUserId() == 0 ) {
throw new AuthenticationException("Not logged in");
}
// get user from session id
User user = (User) userDAO_.find(session.getUserId());
if ( user == null ) {
throw new AuthenticationException("User not found: " + session.getUserId());
}
// check if user enabled
if ( ! user.getEnabled() ) {
throw new AuthenticationException("User disabled");
}
// check if user login enabled
if ( ! user.getLoginEnabled() ) {
throw new AuthenticationException("Login disabled");
}
// check if user group enabled
Group group = (Group) groupDAO_.find(user.getGroup());
if ( group != null && ! group.getEnabled() ) {
throw new AuthenticationException("User group disabled");
}
// check for two-factor authentication
if ( user.getTwoFactorEnabled() && ! session.getContext().getBoolean("twoFactorSuccess") ) {
throw new AuthenticationException("User requires two-factor authentication");
}
return user;
}
/**
* A challenge is generated from the userID provided
* This is saved in a LinkedHashMap with ttl of 5
*/
public String generateChallenge(long userId) throws AuthenticationException {
throw new UnsupportedOperationException("Unsupported operation: generateChallenge");
}
/**
* Checks the LinkedHashMap to see if the the challenge supplied is correct
* and the ttl is still valid
*
* How often should we purge this map for challenges that have expired?
*/
public User challengedLogin(X x, long userId, String challenge) throws AuthenticationException {
throw new UnsupportedOperationException("Unsupported operation: challengedLogin");
}
/**
Logs user and sets user group into the current sessions context.
*/
private User userAndGroupContext(X x, User user, String password) throws AuthenticationException {
if ( user == null ) {
throw new AuthenticationException("User not found");
}
// check if user enabled
if ( ! user.getEnabled() ) {
throw new AuthenticationException("User disabled");
}
// check if user login enabled
if ( ! user.getLoginEnabled() ) {
throw new AuthenticationException("Login disabled");
}
// check if user group enabled
Group group = (Group) groupDAO_.find(user.getGroup());
if ( group != null && ! group.getEnabled() ) {
throw new AuthenticationException("User group disabled");
}
if ( ! Password.verify(password, user.getPassword()) ) {
throw new AuthenticationException("Invalid Password");
}
// Freeze user
user = (User) user.fclone();
user.freeze();
Session session = x.get(Session.class);
session.setUserId(user.getId());
session.setContext(session.getContext().put("user", user));
sessionDAO_.put(session);
return user;
}
/**
* Login a user by the id provided, validate the password
* and return the user in the context.
*/
public User login(X x, long userId, String password) throws AuthenticationException {
if ( userId < 1 || SafetyUtil.isEmpty(password) ) {
throw new AuthenticationException("Invalid Parameters");
}
return userAndGroupContext(x, (User) userDAO_.find(userId), password);
}
public User loginByEmail(X x, String email, String password) throws AuthenticationException {
User user = (User) userDAO_.find(
AND(
EQ(User.EMAIL, email.toLowerCase()),
EQ(User.LOGIN_ENABLED, true)
)
);
if ( user == null ) {
throw new AuthenticationException("User not found");
}
return userAndGroupContext(x, user, password);
}
public boolean checkUserPermission(foam.core.X x, User user, Permission permission) {
if ( ! check(x, CHECK_USER_PERMISSION) ) {
throw new AuthorizationException();
}
if ( user == null || permission == null ) {
return false;
}
try {
String groupId = (String) user.getGroup();
while ( ! SafetyUtil.isEmpty(groupId) ) {
Group group = (Group) groupDAO_.find(groupId);
// if group is null break
if ( group == null ) {
break;
}
if ( group.implies(permission) ) {
return true;
}
// check parent group
groupId = group.getParent();
}
} catch (Throwable t) {
}
return false;
}
public boolean checkPermission(foam.core.X x, Permission permission) {
if ( x == null || permission == null ) {
return false;
}
Session session = x.get(Session.class);
if ( session == null || session.getUserId() == 0 ) {
return false;
}
// NOTE: It's important that we use the User from the context here instead
// of looking it up in a DAO because if the user is actually an entity that
// an agent is acting as, then the user we get from the DAO won't have the
// correct group, which is the group set on the junction between the agent
// and the entity.
User user = (User) x.get("user");
// check if user exists and is enabled
if ( user == null || ! user.getEnabled() ) {
return false;
}
try {
String groupId = (String) user.getGroup();
while ( ! SafetyUtil.isEmpty(groupId) ) {
Group group = (Group) groupDAO_.find(groupId);
// if group is null break
if ( group == null ) {
break;
}
// check if group is enabled
if ( ! group.getEnabled() ) {
return false;
}
if ( group.implies(permission) ) {
return true;
}
// check parent group
groupId = group.getParent();
}
} catch (IllegalArgumentException e) {
Logger logger = (Logger) x.get("logger");
logger.error("check", permission, e);
} catch (Throwable t) {
}
return false;
}
public boolean check(foam.core.X x, String permission) {
return checkPermission(x, new AuthPermission(permission));
}
public boolean validatePassword( String newPassword) {
return Password.isValid(newPassword);
}
public boolean checkUser(foam.core.X x, User user, String permission) {
return checkUserPermission(x, user, new AuthPermission(permission));
}
/**
* Given a context with a user, validate the password to be updated
* and return a context with the updated user information
*/
public User updatePassword(foam.core.X x, String oldPassword, String newPassword) throws AuthenticationException {
if ( x == null || SafetyUtil.isEmpty(oldPassword) || SafetyUtil.isEmpty(newPassword) ) {
throw new RuntimeException("Password fields cannot be blank");
}
Session session = x.get(Session.class);
if ( session == null || session.getUserId() == 0 ) {
throw new AuthenticationException("User not found");
}
User user = (User) userDAO_.find(session.getUserId());
if ( user == null ) {
throw new AuthenticationException("User not found");
}
// check if user enabled
if ( ! user.getEnabled() ) {
throw new AuthenticationException("User disabled");
}
// check if user login enabled
if ( ! user.getLoginEnabled() ) {
throw new AuthenticationException("Login disabled");
}
// check if user group enabled
Group group = (Group) groupDAO_.find(user.getGroup());
if ( group != null && ! group.getEnabled() ) {
throw new AuthenticationException("User group disabled");
}
if ( ! validatePassword(newPassword) ) {
throw new AuthenticationException(Password.PASSWORD_ERROR_MESSAGE);
}
// old password does not match
if ( ! Password.verify(oldPassword, user.getPassword()) ) {
throw new RuntimeException("Old password is incorrect");
}
// new password is the same
if ( Password.verify(newPassword, user.getPassword()) ) {
throw new RuntimeException("New password must be different");
}
// store new password in DAO and put in context
user = (User) user.fclone();
user.setPasswordLastModified(Calendar.getInstance().getTime());
user.setPreviousPassword(user.getPassword());
user.setPassword(Password.hash(newPassword));
// TODO: modify line to allow actual setting of password expiry in cases where users are required to periodically update their passwords
user.setPasswordExpiry(null);
user = (User) userDAO_.put(user);
session.setContext(session.getContext().put("user", user));
return user;
}
/**
* Used to validate properties of a user. This will be called on registration of users
* Will mainly be used as a veto method.
* Users should have id, email, first name, last name, password for registration
*/
public void validateUser(X x, User user) throws AuthenticationException {
if ( user == null ) {
throw new AuthenticationException("Invalid User");
}
if ( SafetyUtil.isEmpty(user.getEmail()) ) {
throw new AuthenticationException("Email is required for creating a user");
}
if ( ! Email.isValid(user.getEmail()) ) {
throw new AuthenticationException("Email format is invalid");
}
if ( SafetyUtil.isEmpty(user.getFirstName()) ) {
throw new AuthenticationException("First Name is required for creating a user");
}
if ( SafetyUtil.isEmpty(user.getLastName()) ) {
throw new AuthenticationException("Last Name is required for creating a user");
}
if ( SafetyUtil.isEmpty(user.getPassword()) ) {
throw new AuthenticationException("Password is required for creating a user");
}
if ( ! Password.isValid(user.getPassword()) ) {
throw new AuthenticationException("Password needs to minimum 8 characters, contain at least one uppercase, one lowercase and a number");
}
}
/**
* Just return a null user for now. Not sure how to handle the cleanup
* of the current context
*/
public void logout(X x) {
Session session = x.get(Session.class);
if ( session != null && session.getUserId() != 0 ) {
sessionDAO_.remove(session);
}
}
} |
package jp.toastkid.slideshow.control;
import com.jfoenix.controls.JFXButton;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.util.Duration;
/**
* Stop watch powered by JavaFX.
*
* <pre>
* final Stopwatch stopwatch = new Stopwatch();
* stopwatch.setTextFill(Color.NAVY);
* stopwatch.setStyle("-fx-font-size: 2em;");
* final Button reset = new JFXButton("Reset");
* reset.setOnAction(eve -> {stopwatch.reset();});
* new HBox().getChildren().addAll(stopwatch, reset);
* </pre>
*
* @author Toast kid
*
*/
public class Stopwatch extends JFXButton {
/** timeline. */
private Timeline timeline;
/** String property. */
private final StringProperty timeSeconds = new SimpleStringProperty();
/** contanis duration. */
private Duration time = Duration.ZERO;
/** this timer is active. */
private boolean active;
/**
* initialize this component.
*/
public Stopwatch() {
this.textProperty().bind(timeSeconds);
this.setOnAction(eve -> {start();});
reset();
}
/**
* start count up.
*/
public void start() {
if (active) {
timeline.stop();
active = false;
timeSeconds.set(makeText(time));
return;
}
active = true;
if (timeline == null) {
timeline = new Timeline(
new KeyFrame(Duration.millis(100),
e2 -> {
if (!active) {
return;
}
final Duration duration = ((KeyFrame) e2.getSource()).getTime();
time = time.add(duration);
timeSeconds.set(makeText(time));
}
)
);
}
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
/**
* duration to text.
* @param duration
* @return
*/
private String makeText(final Duration duration) {
return String.format("%02d:%02d",
(long) (duration.toMinutes() % 60.0),
(long) (duration.toSeconds() % 60.0)
)
+ (active ? "|>" : "");
}
/**
* reset timer.
*/
public void reset() {
time = Duration.ZERO;
timeSeconds.set(makeText(time));
}
/**
* get is active.
* @return active(boolean)
*/
public boolean isActive() {
return active;
}
} |
package net.explorviz.server.main;
import java.util.ArrayList;
import java.util.Arrays;
public class Configuration {
public static String selectedLanguage = "english";
public static ArrayList<String> languages = new ArrayList<String>(Arrays.<String>asList("english", "german"));
public static boolean secondLandscape = false;
public static long tutorialStart = System.currentTimeMillis();
public static long secondLandscapeTime = System.currentTimeMillis();
public static boolean experiment = false;
public static boolean skipQuestion = false;
public static boolean rsfExportEnabled = false;
public static int outputIntervalSeconds = 10;
public static final ArrayList<String> DATABASE_NAMES = new ArrayList<String>();
public static final int TIMESHIFT_INTERVAL_IN_MINUTES = 10;
public static final int HISTORY_INTERVAL_IN_MINUTES = 24 * 60; // one day
public static final String MODEL_EXTENSION = ".expl";
public static final boolean DUMMYMODE = false;
} |
package net.imagej.ops;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import net.imagej.ops.OpCandidate.StatusCode;
import org.scijava.Context;
import org.scijava.InstantiableException;
import org.scijava.command.CommandInfo;
import org.scijava.command.CommandService;
import org.scijava.convert.ConvertService;
import org.scijava.log.LogService;
import org.scijava.module.Module;
import org.scijava.module.ModuleInfo;
import org.scijava.module.ModuleItem;
import org.scijava.module.ModuleService;
import org.scijava.plugin.AbstractSingletonService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.service.Service;
/**
* Default service for finding {@link Op}s which match a request.
*
* @author Curtis Rueden
*/
@Plugin(type = Service.class)
public class DefaultOpMatchingService extends
AbstractSingletonService<Optimizer> implements OpMatchingService
{
@Parameter
private Context context;
@Parameter
private ModuleService moduleService;
@Parameter
private CommandService commandService;
@Parameter
private ConvertService convertService;
@Parameter
private LogService log;
// -- OpMatchingService methods --
@Override
public List<CommandInfo> getOps() {
return commandService.getCommandsOfType(Op.class);
}
@Override
public <OP extends Op> Module findModule(final OpRef<OP> ref) {
// find candidates with matching name & type
final List<OpCandidate<OP>> candidates = findCandidates(ref);
if (candidates.isEmpty()) {
throw new IllegalArgumentException("No candidate '" + ref.getLabel() +
"' ops");
}
// narrow down candidates to the exact matches
final List<Module> matches = findMatches(candidates);
if (matches.size() == 1) {
// a single match: return it
if (log.isDebug()) {
log.debug("Selected '" + ref.getLabel() + "' op: " +
matches.get(0).getDelegateObject().getClass().getName());
}
return optimize(matches.get(0));
}
final String analysis = OpUtils.matchInfo(candidates, matches);
throw new IllegalArgumentException(analysis);
}
@Override
public <OP extends Op> List<OpCandidate<OP>> findCandidates(
final OpRef<OP> ref)
{
final ArrayList<OpCandidate<OP>> candidates =
new ArrayList<OpCandidate<OP>>();
for (final CommandInfo info : getOps()) {
if (isCandidate(info, ref)) {
candidates.add(new OpCandidate<OP>(ref, info));
}
}
return candidates;
}
@Override
public <OP extends Op> List<Module> findMatches(
final List<OpCandidate<OP>> candidates)
{
final ArrayList<Module> matches = new ArrayList<Module>();
double priority = Double.NaN;
for (final OpCandidate<?> candidate : candidates) {
final ModuleInfo info = candidate.getInfo();
final double p = info.getPriority();
if (p != priority && !matches.isEmpty()) {
// NB: Lower priority was reached; stop looking for any more matches.
break;
}
priority = p;
final Module module = match(candidate);
if (module != null) matches.add(module);
}
return matches;
}
@Override
public <OP extends Op> Module match(final OpCandidate<OP> candidate) {
if (!valid(candidate)) return null;
final Object[] args = paddedArgs(candidate);
return args == null ? null : match(candidate, args);
}
@Override
public <OP extends Op> boolean typesMatch(final OpCandidate<OP> candidate) {
if (!valid(candidate)) return false;
final Object[] args = paddedArgs(candidate);
return args == null ? false : typesMatch(candidate, args);
}
@Override
public Module assignInputs(final Module module, final Object... args) {
int i = 0;
for (final ModuleItem<?> item : module.getInfo().inputs()) {
assign(module, args[i++], item);
}
return module;
}
@Override
public Module optimize(final Module module) {
final ArrayList<Module> optimal = new ArrayList<Module>();
final ArrayList<Optimizer> optimizers = new ArrayList<Optimizer>();
double priority = Double.NaN;
for (final Optimizer optimizer : getInstances()) {
final double p = optimizer.getPriority();
if (p != priority && !optimal.isEmpty()) {
// NB: Lower priority was reached; stop looking for any more matches.
break;
}
priority = p;
final Module m = optimizer.optimize(module);
if (m != null) {
optimal.add(m);
optimizers.add(optimizer);
}
}
if (optimal.size() == 1) return optimal.get(0);
if (optimal.isEmpty()) return module;
// multiple matches
final double p = optimal.get(0).getInfo().getPriority();
final StringBuilder sb = new StringBuilder();
final String label = module.getDelegateObject().getClass().getName();
sb.append("Multiple '" + label + "' optimizations of priority " + p + ":\n");
for (int i = 0; i < optimizers.size(); i++) {
sb.append("\t" + optimizers.get(i).getClass().getName() + " produced:");
sb.append("\t\t" + OpUtils.opString(optimal.get(i).getInfo()) + "\n");
}
log.warn(sb.toString());
return module;
}
// -- PTService methods --
@Override
public Class<Optimizer> getPluginType() {
return Optimizer.class;
}
// -- Helper methods --
/** Helper method of {@link #findCandidates}. */
private <OP extends Op> boolean isCandidate(final CommandInfo info,
final OpRef<OP> ref)
{
if (!nameMatches(info, ref.getName())) return false;
// the name matches; now check the class
final Class<?> opClass;
try {
opClass = info.loadClass();
}
catch (final InstantiableException exc) {
log.error("Invalid op: " + info.getClassName());
return false;
}
return ref.getType() == null || ref.getType().isAssignableFrom(opClass);
}
/** Verifies that the given candidate's module is valid. */
private <OP extends Op> boolean valid(final OpCandidate<OP> candidate) {
if (candidate.getInfo().isValid()) return true;
candidate.setStatus(StatusCode.INVALID_MODULE);
return false;
}
/** Checks the number of args, padding optional args with null as needed. */
private <OP extends Op> Object[] paddedArgs(final OpCandidate<OP> candidate) {
int inputCount = 0, requiredCount = 0;
for (final ModuleItem<?> item : candidate.getInfo().inputs()) {
inputCount++;
if (item.isRequired()) requiredCount++;
}
final Object[] args = candidate.getRef().getArgs();
if (args.length == inputCount) {
// correct number of arguments
return args;
}
if (args.length > inputCount) {
// too many arguments
candidate.setStatus(StatusCode.TOO_MANY_ARGS,
args.length + " > " + inputCount);
return null;
}
if (args.length < requiredCount) {
// too few arguments
candidate.setStatus(StatusCode.TOO_FEW_ARGS,
args.length + " < " + requiredCount);
return null;
}
// pad optional parameters with null (from right to left)
final int argsToPad = inputCount - args.length;
final int optionalCount = inputCount - requiredCount;
final int optionalsToFill = optionalCount - argsToPad;
final Object[] paddedArgs = new Object[inputCount];
int argIndex = 0, paddedIndex = 0, optionalIndex = 0;
for (final ModuleItem<?> item : candidate.getInfo().inputs()) {
if (!item.isRequired() && optionalIndex++ >= optionalsToFill) {
// skip this optional parameter (pad with null)
paddedIndex++;
continue;
}
paddedArgs[paddedIndex++] = args[argIndex++];
}
return paddedArgs;
}
/** Helper method of {@link #match(OpCandidate)}. */
private <OP extends Op> Module match(final OpCandidate<OP> candidate,
final Object[] args)
{
// check that each parameter is compatible with its argument
if (!typesMatch(candidate, args)) return null;
// create module and assign the inputs
final Module module = createModule(candidate.getInfo(), args);
candidate.setModule(module);
// make sure the op itself is happy with these arguments
final Object op = module.getDelegateObject();
if (op instanceof Contingent) {
final Contingent c = (Contingent) op;
if (!c.conforms()) {
candidate.setStatus(StatusCode.DOES_NOT_CONFORM);
return null;
}
}
// found a match!
return module;
}
/**
* Checks that each parameter is type-compatible with its corresponding
* argument.
*/
private <OP extends Op> boolean typesMatch(final OpCandidate<OP> candidate,
final Object[] args)
{
int i = 0;
for (final ModuleItem<?> item : candidate.getInfo().inputs()) {
final Object arg = args[i++];
if (!canAssign(candidate, arg, item)) return false;
}
return true;
}
/** Helper method of {@link #isCandidate}. */
private boolean nameMatches(final ModuleInfo info, final String name) {
if (name == null || name.equals(info.getName())) return true;
// check for an alias
final String alias = info.get("alias");
if (name.equals(alias)) return true;
// check for a list of aliases
final String aliases = info.get("aliases");
if (aliases != null) {
for (final String a : aliases.split(",")) {
if (name.equals(a.trim())) return true;
}
}
return false;
}
/** Helper method of {@link #match(OpCandidate, Object[])}. */
private Module createModule(final ModuleInfo info, final Object... args) {
final Module module = moduleService.createModule(info);
context.inject(module.getDelegateObject());
return assignInputs(module, args);
}
/** Helper method of {@link #match(OpCandidate, Object[])}. */
private boolean canAssign(final OpCandidate<?> candidate, final Object arg,
final ModuleItem<?> item)
{
if (arg == null) {
if (item.isRequired()) {
candidate.setStatus(StatusCode.REQUIRED_ARG_IS_NULL, null, item);
return false;
}
return true;
}
final Type type = item.getGenericType();
if (!canConvert(arg, type)) {
candidate.setStatus(StatusCode.CANNOT_CONVERT,
arg.getClass().getName() + " => " + type, item);
return false;
}
return true;
}
/** Helper method of {@link #canAssign}. */
private boolean canConvert(final Object arg, final Type type) {
if (isMatchingClass(arg, type)) {
// NB: Class argument for matching, to help differentiate op signatures.
return true;
}
return convertService.supports(arg, type);
}
/** Helper method of {@link #assignInputs}. */
private void assign(final Module module, final Object arg,
final ModuleItem<?> item)
{
if (arg != null) {
final Type type = item.getGenericType();
final Object value = convert(arg, type);
module.setInput(item.getName(), value);
}
module.setResolved(item.getName(), true);
}
/** Helper method of {@link #assign}. */
private Object convert(final Object arg, final Type type) {
if (isMatchingClass(arg, type)) {
// NB: Class argument for matching; fill with null.
return null;
}
return convertService.convert(arg, type);
}
/** Determines whether the argument is a matching class instance. */
private boolean isMatchingClass(final Object arg, final Type type) {
return arg instanceof Class &&
convertService.supports((Class<?>) arg, type);
}
} |
package nl.topicus.mssql2monetdb;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import nl.topicus.mssql2monetdb.util.EmailUtil;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CopyToolConfig
{
private static final Logger LOG = LoggerFactory.getLogger(CopyToolConfig.class);
public static final int DEFAULT_BATCH_SIZE = 10000;
public static final String DEFAULT_SOURCE_ID = "_default";
private Properties databaseProperties;
private int batchSize = DEFAULT_BATCH_SIZE;
private String jobId;
private boolean schedulerEnabled;
private int schedulerInterval;
private boolean triggerEnabled;
private String triggerSource;
private String triggerTable;
private String triggerColumn;
private String triggerDirectory;
private File configFile;
private String tempDirectory;
private boolean noSwitch;
private boolean switchOnly;
private Map<String, SourceDatabase> sourceDatabases = new HashMap<>();
private Map<String, CopyTable> tablesToCopy = new HashMap<>();
public static boolean getBooleanProperty (Properties props, String key)
{
String value = props.getProperty(key);
if (StringUtils.isEmpty(value))
return false;
value = value.toLowerCase();
return (value.startsWith("y") || value.equals("true"));
}
public static String sha1Checksum (File file) throws NoSuchAlgorithmException, IOException
{
MessageDigest md = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream(file);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
fis.close();
byte[] mdbytes = md.digest();
//convert the byte to hex format
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
public CopyToolConfig(String args[]) throws ConfigException, ConfigurationException
{
LOG.info("Started logging of the MSSQL2MonetDB copy tool");
final Options options = new Options();
OptionBuilder.hasArg(true);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("Specify the configuration properties file");
OptionBuilder.withLongOpt("config");
options.addOption(OptionBuilder.create("c"));
OptionBuilder.hasArg(false);
OptionBuilder.hasOptionalArgs(0);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("Specify if views will be switched or not");
OptionBuilder.withLongOpt("no-switch");
options.addOption(OptionBuilder.create("ns"));
OptionBuilder.hasArg(false);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("Specify if views will be switched or not");
OptionBuilder.withLongOpt("switch-only");
options.addOption(OptionBuilder.create("so"));
//user
OptionBuilder.hasArg(true);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("MonetDB username");
OptionBuilder.withLongOpt("monetdb-user");
options.addOption(OptionBuilder.create());
//password
OptionBuilder.hasArg(true);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("MonetDB password");
OptionBuilder.withLongOpt("monetdb-password");
options.addOption(OptionBuilder.create());
//hostname
OptionBuilder.hasArg(true);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("MonetDB server");
OptionBuilder.withLongOpt("monetdb-server");
options.addOption(OptionBuilder.create());
//port
OptionBuilder.hasArg(true);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("MonetDB port");
OptionBuilder.withLongOpt("monetdb-port");
options.addOption(OptionBuilder.create());
//database
OptionBuilder.hasArg(true);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("MonetDB database");
OptionBuilder.withLongOpt("monetdb-db");
options.addOption(OptionBuilder.create());
//schema
OptionBuilder.hasArg(true);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("MonetDB schema");
OptionBuilder.withLongOpt("monetdb-schema");
options.addOption(OptionBuilder.create());
//table
OptionBuilder.hasArg(true);
OptionBuilder.isRequired(false);
OptionBuilder.withDescription("Table in MonetDB that should be switched");
OptionBuilder.withLongOpt("monetdb-table");
options.addOption(OptionBuilder.create());
CommandLineParser parser = new BasicParser();
final CommandLine cmd;
try
{
cmd = parser.parse(options, args);
}
catch (ParseException e)
{
LOG.error("ERROR: " + e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("mssql2monetdb", options);
throw new ConfigException(e.getMessage());
}
if (cmd == null)
{
LOG.error("CommandLine parser is null");
return;
}
this.noSwitch = cmd.hasOption("no-switch");
LOG.info("No-Switch-flag set to: " + noSwitch);
this.switchOnly = cmd.hasOption("switch-only");
LOG.info("Switch-Only-flag set to: " + switchOnly);
//manually switch just a single monetdb-table and explicitly require the user to specify only wanting to switch a view to another backing table
List<String> requiredOptionsForSchemaSwitchOnly = Arrays.asList("monetdb-table", "monetdb-schema", "monetdb-db", "monetdb-user", "monetdb-password", "monetdb-server", "switch-only");
boolean allRequiredOptionsPresent = requiredOptionsForSchemaSwitchOnly
.stream()
.allMatch(o -> cmd.hasOption(o)
&& (!options.getOption(o).hasArg()
|| (cmd.getOptionValue(o) != null && !cmd.getOptionValue(o).isEmpty())));
if (allRequiredOptionsPresent)
{
CopyTable ct = new CopyTable();
String table = cmd.getOptionValue("monetdb-table");
ct.setFromName(table);
ct.setToName(table);
ct.setCreate(false);
ct.setDrop(true);
ct.setSchema(cmd.getOptionValue("monetdb-schema"));
ct.setCopyViaTempTable(false);
ct.setUseFastViewSwitching(true);
MonetDBTable monetDBTable = new MonetDBTable(ct);
monetDBTable.setName(ct.getToName());
ct.getMonetDBTables().add(monetDBTable);
this.tablesToCopy.put(table, ct);
Properties monetDBProperties = new Properties();
monetDBProperties.put(CONFIG_KEYS.MONETDB_DATABASE.toString(), cmd.getOptionValue("monetdb-db"));
monetDBProperties.put(CONFIG_KEYS.MONETDB_USER.toString(), cmd.getOptionValue("monetdb-user"));
monetDBProperties.put(CONFIG_KEYS.MONETDB_PASSWORD.toString(), cmd.getOptionValue("monetdb-password"));
monetDBProperties.put(CONFIG_KEYS.MONETDB_SERVER.toString(), cmd.getOptionValue("monetdb-server") + (cmd.hasOption("monetdb-port") ? (":" + cmd.getOptionValue("monetdb-port")) : ""));
this.databaseProperties = monetDBProperties;
}
else if (cmd.hasOption("config"))
{
configFile = new File(cmd.getOptionValue("config"));
LOG.info("Using config file: " + configFile.getAbsolutePath());
// Load configuration using Commons Configuration lib (allows including other config files)
Configuration config = new PropertiesConfiguration(configFile);
// replace environment variable references in config and transform into a simple Properties object
Properties props = loadEnvironmentVariables(config);
this.databaseProperties = getAndValidateDatabaseProperties(props);
this.sourceDatabases = findSourceDatabases(props);
this.tablesToCopy = findTablesToCopy(props);
findSchedulerProperties(props);
findTriggerProperties(props);
this.tempDirectory = findTempDirectory(props);
// verify scheduling source
//checkSchedulingSource();
}
else
{
throw new IllegalArgumentException("Either a config file or a set of MonetDB parameters should be specified.");
}
}
private Properties loadEnvironmentVariables (Configuration config)
{
Iterator iter = config.getKeys();
Properties newProps = new Properties();
while(iter.hasNext())
{
String key = iter.next().toString();
String value = config.getString(key.toString());
// an environment variable value?
if (value.toLowerCase().startsWith("env:"))
{
value = this.getEnvironmentValue(value, key.toString());
}
else
{
// check if value contains references to environment variables
int pos = -1;
while((pos = value.indexOf("{env:", pos+1)) > -1)
{
int end = value.indexOf("}", pos);
if (end > -1)
{
String refPart = value.substring(pos+1, end);
String replaceValue = this.getEnvironmentValue(refPart, null);
value = value.replace("{" + refPart + "}", replaceValue);
pos = 0;
}
}
}
newProps.setProperty(key, value);
}
return newProps;
}
private String getEnvironmentValue(String refParts, String key)
{
String[] split = refParts.split(":");
// retrieve name of environment variable and (optional) default value
String envVar = split[1];
String defaultValue = (split.length >= 3) ? split[2] : "";
// get value of environment variable
String envValue = System.getenv(envVar);
if (StringUtils.isEmpty(envValue))
{
if (!StringUtils.isEmpty(key))
{
if (StringUtils.isEmpty(defaultValue))
{
LOG.warn("Configuration property '" + key.toString() + "' set to empty. "
+ "Environment variable '" + envVar + "' is empty or not set!");
}
else
{
LOG.info("Configuration property '" + key.toString() + "' set to default value '" + defaultValue + "'."
+ "Environment variable '" + envVar + "' is empty or not set.");
}
}
envValue = defaultValue;
}
return envValue;
}
private Properties getAndValidateDatabaseProperties(Properties config) throws ConfigException
{
boolean isMissing = false;
ArrayList<String> missingKeys = new ArrayList<String>();
for (CONFIG_KEYS key : CONFIG_KEYS.values())
{
String value = config.getProperty(key.toString());
if (key.isRequired() && StringUtils.isEmpty(value))
{
isMissing = true;
LOG.error("Missing config property: " + key);
missingKeys.add(key.toString());
}
}
if (isMissing)
{
LOG.error("Missing essential config properties");
EmailUtil.sendMail("The following configs are missing: " + missingKeys.toString(), "Missing essential config properties in monetdb", config);
throw new ConfigException("Missing essential config properties");
}
jobId = config.getProperty(CONFIG_KEYS.JOB_ID.toString());
// check if batch size has been specified
String batchSizeStr = config.getProperty(CONFIG_KEYS.BATCH_SIZE.toString());
if (StringUtils.isEmpty(batchSizeStr) == false)
{
try
{
this.batchSize = Integer.parseInt(batchSizeStr);
}
catch (NumberFormatException e)
{
// don't care, just ignore
}
}
return config;
}
private String findTempDirectory (Properties config)
{
String defaultTempDir = System.getProperty("java.io.tmpdir");
String tempDir = config.getProperty(CONFIG_KEYS.TEMP_DIR.toString());
// no custom temp directory specified?
// then use standard temp directory
if (StringUtils.isEmpty(tempDir))
return defaultTempDir;
// make sure directory does not end with slash
while(tempDir.endsWith("/"))
{
tempDir = tempDir.substring(0, tempDir.length()-1);
}
File dir = new File(tempDir);
if (dir.exists() && dir.isFile())
{
LOG.error("Unable to use '" + tempDir + "' as temporary directory. Already exists as file. Using standard temp directory.");
return defaultTempDir;
}
if (!dir.exists())
{
if (!dir.mkdir())
{
LOG.error("Unable to create temp directory '" + tempDir + "'. Using standard temp directory.");
return defaultTempDir;
}
}
// check if we can write to temp directory
File sample = new File(tempDir, "test.txt");
try {
if (!sample.createNewFile())
{
LOG.error("Unable to write to temp directory '" + tempDir + "'. Using standard temp directory.");
return defaultTempDir;
}
sample.delete();
} catch (IOException e) {
LOG.error("Unable to write to temp directory '" + tempDir + "'. Using standard temp directory.");
return defaultTempDir;
}
// all checks ok, so use custom temp directory
return tempDir;
}
private void findTriggerProperties (Properties config)
{
triggerEnabled = getBooleanProperty(config, CONFIG_KEYS.TRIGGER_ENABLED.toString());
if (!triggerEnabled)
return;
String source = config.getProperty(CONFIG_KEYS.TRIGGER_SOURCE.toString());
String table = config.getProperty(CONFIG_KEYS.TRIGGER_TABLE.toString());
String column = config.getProperty(CONFIG_KEYS.TRIGGER_COLUMN.toString());
String triggerDir = config.getProperty(CONFIG_KEYS.TRIGGER_DIR.toString());
if (StringUtils.isEmpty(source))
{
if (!this.sourceDatabases.containsKey(DEFAULT_SOURCE_ID))
{
LOG.error("No trigger source defined and default source database does not exist. Trigger disabled!");
triggerEnabled = false;
return;
}
else
{
source = DEFAULT_SOURCE_ID;
}
}
else
{
if (!this.sourceDatabases.containsKey(source))
{
LOG.error("Defined trigger source '" + source + "' does not exist. Trigger disabled!");
triggerEnabled = false;
return;
}
}
if (StringUtils.isEmpty(table))
{
LOG.error("Trigger table has not been set or is empty in configuration. Trigger disabled!");
triggerEnabled = false;
return;
}
if (StringUtils.isEmpty(column))
{
LOG.error("Trigger column has not been set or is empty in configuration. Trigger disabled!");
triggerEnabled = false;
return;
}
// no custom directory specified?
// then use home directory
if (StringUtils.isEmpty(triggerDir))
triggerDir = System.getProperty("user.dir");
// make sure directory does not end with slash
while(triggerDir.endsWith("/"))
{
triggerDir = triggerDir.substring(0, triggerDir.length()-1);
}
File dir = new File(triggerDir);
if (dir.exists() && dir.isFile())
{
LOG.error("Unable to use '" + triggerDir + "' as directory for trigger. Already exists as file. Trigger disabled!");
triggerEnabled = false;
return;
}
if (!dir.exists())
{
if (!dir.mkdir())
{
LOG.error("Unable to create directory '" + triggerDir + "'. Trigger disabled!.");
triggerEnabled = false;
return;
}
}
// check if we can write to trigger directory
File sample = new File(triggerDir, "test.txt");
try {
if (!sample.createNewFile())
{
LOG.error("Unable to write to trigger directory '" + triggerDir + "'.Trigger disabled!");
triggerEnabled = false;
return;
}
sample.delete();
} catch (IOException e) {
LOG.error("Unable to write to trigger directory '" + triggerDir + "'. Trigger disabled!");
triggerEnabled = false;
return;
}
triggerSource = source;
triggerTable = table;
triggerColumn = column;
triggerDirectory = triggerDir;
LOG.info("Trigger enabled, monitoring " + source +"." + table + "." + column + " for indication of new data");
}
private void findSchedulerProperties (Properties config)
{
schedulerEnabled = getBooleanProperty(config, CONFIG_KEYS.SCHEDULER_ENABLED.toString());
if (!schedulerEnabled)
return;
String intervalStr = config.getProperty(CONFIG_KEYS.SCHEDULER_INTERVAL.toString());
if (StringUtils.isEmpty(intervalStr))
{
schedulerEnabled = false;
LOG.warn("Scheduler has been enabled in configuration but no interval has been specified. Disabled scheduler!");
return;
}
intervalStr = intervalStr.toLowerCase().trim();
// try to convert interval into seconds
int interval = 0;
try {
interval = Integer.parseInt(intervalStr);
} catch (NumberFormatException e) {
// okay, so not a number
}
// not a valid interval yet? try other options
if (interval == 0)
{
if (intervalStr.startsWith("every "))
intervalStr = intervalStr.substring(6);
// example: 5 minutes => [0]: 5, [1]: minutes
String[] split = intervalStr.split(" ");
if (split.length >= 2)
{
String unit = split[1].toLowerCase();
try {
interval = Integer.parseInt(split[0]);
if (unit.startsWith("minute"))
interval = interval * 60;
else if (unit.startsWith("hour"))
interval = interval * 60 * 60;
else if (unit.startsWith("day"))
interval = interval * 60 * 60 * 24;
else
{
LOG.warn("Unknown scheduler interval unit '" + unit + "'");
interval = 0;
}
} catch (NumberFormatException e) {
LOG.warn("Unable to parse scheduler interval '" + split[0] + "'");
}
}
}
// check if a valid interval has been found
if (interval == 0)
{
schedulerEnabled = false;
LOG.warn("Unknown scheduler interval '" + intervalStr + "' specified. Disabled scheduler!");
}
LOG.info("Scheduler enabled, interval: " + interval + " seconds");
schedulerInterval = interval;
}
private HashMap<String, SourceDatabase> findSourceDatabases (Properties config)
{
HashMap<String, SourceDatabase> sourceDatabases = new HashMap<String, SourceDatabase>();
for (Entry<Object, Object> entry : config.entrySet())
{
String propName = entry.getKey().toString().toLowerCase();
String propValue = entry.getValue().toString().trim();
String[] split = propName.split("\\.");
if (split[0].equals("mssql") == false)
continue;
String id;
String key;
if (split.length == 3)
{
id = split[1];
key = split[2];
}
else if (split.length == 2)
{
id = DEFAULT_SOURCE_ID;
key = split[1];
}
else
{
continue;
}
key = key.toLowerCase().trim();
SourceDatabase db = sourceDatabases.get(id);
if (db == null)
{
db = new SourceDatabase();
db.setId(id);
}
if (key.equals("user"))
{
db.setUser(propValue);
}
else if (key.equals("password"))
{
db.setPassword(propValue);
}
else if (key.equals("server"))
{
db.setServer(propValue);
}
else if (key.equals("database"))
{
db.setDatabase(propValue);
}
else if (key.equals("instance"))
{
db.setInstance(propValue);
}
else if (key.equals("port"))
{
try
{
int portInt = Integer.parseInt(propValue);
db.setPort(portInt);
}
catch (NumberFormatException e)
{
LOG.warn("Invalid port specified for MSSQL '" + id + "', must be a valid integer!");
}
}
sourceDatabases.put(id, db);
}
// verify each source database has a database and server specified
Iterator<Entry<String, SourceDatabase>> iter = sourceDatabases.entrySet().iterator();
while(iter.hasNext())
{
Entry<String, SourceDatabase> entry = iter.next();
String id = entry.getKey();
SourceDatabase db = entry.getValue();
if (StringUtils.isEmpty(db.getDatabase()))
{
LOG.error("MSSQL database with id '" + id + "' is missing the database name in the config!");
iter.remove();
}
if (StringUtils.isEmpty(db.getServer()))
{
LOG.error("MSSQL database with id '" + id + "' is missing the server in the config!");
iter.remove();
}
}
if (sourceDatabases.size() == 0)
{
LOG.error("Configuration has specified NO source databases!");
EmailUtil.sendMail("Configuration has specified NO source databases!", "Configuration has specified NO source databases", config);
}
else
{
LOG.info("The following databases will be used as sources: ");
for (SourceDatabase db : sourceDatabases.values())
{
LOG.info("* " + db.getId() + ": " + db.getDatabase() + " (" + db.getServer() + ")");
}
}
return sourceDatabases;
}
/**
* Method to read a query file from disk into a String. Returns null and logs an error when
* an IOException (e.g. file not found) occurs when trying to read the file.
*
* @param filePath
* @return contents of query file
*/
private String readQueryFile(String filePath)
{
File queryFile = new File(filePath);
if (!queryFile.exists())
{
LOG.error("Unable to read query file '{}': file does not exist", filePath);
return null;
}
if (queryFile.isDirectory())
{
LOG.error("Unable to read query file '{}': is a directory", filePath);
return null;
}
try {
return new String(Files.readAllBytes(Paths.get(filePath)));
} catch (IOException e) {
LOG.error("Unable to read query file {} due to: {}", filePath, e.getMessage());
}
return null;
}
private HashMap<String, CopyTable> findTablesToCopy(Properties config)
{
HashMap<String, CopyTable> tablesToCopy = new HashMap<String, CopyTable>();
for (Entry<Object, Object> entry : config.entrySet())
{
String propName = entry.getKey().toString().toLowerCase();
String propValue = entry.getValue().toString();
boolean boolValue =
(propValue.equalsIgnoreCase("true") || propValue.equalsIgnoreCase("yes"));
String[] split = propName.split("\\.");
if (split.length < 3)
continue;
if (split[0].equals("table") == false)
continue;
String id = split[1];
String key = split[2].toLowerCase();
String subKey = null;
if (split.length > 3)
{
subKey = split[3].toLowerCase();
}
CopyTable table = tablesToCopy.get(id);
// if table does not exist than add new CopyTable with a MonetDBTable
if (table == null)
{
table = new CopyTable();
table.getMonetDBTables().add(new MonetDBTable(table));
}
switch(key)
{
case "source":
table.setSource(propValue);
break;
case "from":
if (StringUtils.isEmpty(subKey))
{
table.setFromName(propValue);
}
else
{
switch(subKey)
{
case "table":
table.setFromName(propValue);
break;
case "columns":
table.setFromColumns(propValue);
break;
case "query":
table.setFromQuery(propValue);
break;
case "queryfile":
table.setFromQuery(readQueryFile(propValue));
break;
case "countquery":
table.setFromCountQuery(propValue);
break;
case "countqueryfile":
table.setFromCountQuery(readQueryFile(propValue));
break;
default:
LOG.warn("Unknown 'from' option '{}'", subKey);
break;
}
}
break;
case "to":
table.setToName(propValue.toLowerCase());
table.getCurrentTable().setName(propValue.toLowerCase());
break;
case "schema":
table.setSchema(propValue);
break;
case "create":
table.setCreate(boolValue);
break;
case "truncate":
table.setTruncate(boolValue);
break;
case "drop":
table.setDrop(boolValue);
break;
case "copyviatemptable":
table.setCopyViaTempTable(boolValue);
break;
case "temptableprefix":
table.setTempTablePrefix(propValue);
break;
case "usefastviewswitching":
table.setUseFastViewSwitching(boolValue);
break;
case "uselockedmode":
table.setUseLockedMode(boolValue);
break;
case "allowempty":
table.setAllowEmpty(boolValue);
break;
case "copymethod":
propValue = propValue.toLowerCase();
if (propValue.equals("copyinto"))
{
table.setCopyMethod(CopyTable.COPY_METHOD_COPYINTO);
}
else if (propValue.startsWith("insert"))
{
table.setCopyMethod(CopyTable.COPY_METHOD_INSERT);
}
default:
LOG.warn("Unknown option: '{}'", key);
break;
}
tablesToCopy.put(id, table);
}
// verify each specified has a from and to name and add temp tables
// and add temptable configuration if copyViaTempTable
Iterator<Entry<String, CopyTable>> iter = tablesToCopy.entrySet().iterator();
ArrayList<String> missingResultTables = new ArrayList<String>();
ArrayList<String> missingNames = new ArrayList<String>();
while (iter.hasNext())
{
Entry<String, CopyTable> entry = iter.next();
String id = entry.getKey();
CopyTable table = entry.getValue();
if (table.getCurrentTable() == null)
{
LOG.error("Configuration for '" + id + "' is missing a result table");
missingResultTables.add(id);
iter.remove();
continue;
}
// check if table has a from table name or a custom from query
if (StringUtils.isEmpty(table.getFromName()) && StringUtils.isEmpty(table.getFromQuery()))
{
LOG.error("Configuration for '" + id + "' has no 'from table' and no custom 'from query'");
missingNames.add(id);
iter.remove();
continue;
}
// check if table has a custom from query but not a related a count query
if (StringUtils.isNotEmpty(table.getFromQuery()) && StringUtils.isEmpty(table.getFromCountQuery()))
{
LOG.error("Configuration for '{}' has a custom from query but is missing the related countquery config property", id);
iter.remove();
continue;
}
if (StringUtils.isEmpty(table.getCurrentTable().getName()))
{
if (StringUtils.isEmpty(table.getFromName()))
{
LOG.error("Configuration for '{}' is missing name of to table and name of source table not available", id);
iter.remove();
continue;
}
LOG.warn("Configuration for '" + id
+ "' is missing name of to table. Using name of from table ("
+ table.getFromName() + ")");
table.getCurrentTable().setName(table.getFromName());
table.setToName(table.getFromName());
}
// if no source database has been specified then the default source
// is used
if (StringUtils.isEmpty(table.getSource()))
{
// check if default source exists
if (sourceDatabases.containsKey(DEFAULT_SOURCE_ID))
{
table.setSource(DEFAULT_SOURCE_ID);
LOG.info("Using default source database for table with id '" + id + "'");
}
else
{
LOG.error("Table with id '" + id + "' has not specified a source database and no default source exists in configuration");
iter.remove();
continue;
}
}
else
{
// check if source exists
if (!sourceDatabases.containsKey(table.getSource()))
{
LOG.error("Table with id '" + id + "' has specified a source database (" + table.getSource() + ") "
+ "which does not exist in configuration");
iter.remove();
continue;
}
}
if (table.isCopyViaTempTable() && table.getTempTable() == null)
{
MonetDBTable tempTable = new MonetDBTable(table);
tempTable.setTempTable(true);
tempTable.setName(table.getToName());
table.getMonetDBTables().add(tempTable);
}
}
if(!missingResultTables.isEmpty())
{
EmailUtil.sendMail("Configuration is missing a result table: " + missingResultTables.toString(), "Configuration is missing a result table in monetdb", config);
}
if(!missingNames.isEmpty())
{
EmailUtil.sendMail("Configuration is missing name of from table : " + missingNames.toString(), "Configuration is missing name of from table in monetdb", config);
}
if (tablesToCopy.size() == 0)
{
LOG.error("Configuration has specified NO tables to copy!");
EmailUtil.sendMail("Configuration has specified NO tables to copy!", "Configuration has specified NO tables to copy in monetdb", config);
}
else
{
LOG.info("The following tables will be copied: ");
for (CopyTable table : tablesToCopy.values())
{
LOG.info(
"* {} -> {}.{}",
table.getDescription(),
table.getCurrentTable().getCopyTable().getSchema(),
table.getCurrentTable().getName()
);
}
}
return tablesToCopy;
}
public Properties getDatabaseProperties()
{
return databaseProperties;
}
public void setDatabaseProperties(Properties databaseProperties)
{
this.databaseProperties = databaseProperties;
}
public int getSchedulerInterval ()
{
return this.schedulerInterval;
}
public boolean isSchedulerEnabled ()
{
return this.schedulerEnabled;
}
public File getConfigFile ()
{
return this.configFile;
}
public int getBatchSize()
{
return batchSize;
}
public void setBatchSize(int batchSize)
{
this.batchSize = batchSize;
}
public Map<String, CopyTable> getTablesToCopy()
{
return tablesToCopy;
}
public String getJobId ()
{
if (StringUtils.isEmpty(jobId))
{
jobId = getConfigChecksum();
}
return "job-" + jobId;
}
public String getConfigChecksum ()
{
String checksum = null;
try {
checksum = sha1Checksum(this.configFile);
} catch (NoSuchAlgorithmException | IOException e) {
LOG.warn("Unable to calculate SHA-1 checksum of config file");
// default to using file size
checksum = String.valueOf(this.configFile.length());
}
return checksum;
}
public Map<String, SourceDatabase> getSourceDatabases ()
{
return this.sourceDatabases;
}
public boolean isTriggerEnabled ()
{
return triggerEnabled;
}
public String getTriggerSource()
{
return triggerSource;
}
public String getTriggerTable()
{
return triggerTable;
}
public String getTriggerColumn()
{
return triggerColumn;
}
public String getTriggerDirectory()
{
return triggerDirectory;
}
public String getTempDirectory ()
{
return tempDirectory;
}
public boolean hasNoSwitch() {
return noSwitch;
}
public void setNoSwitch(boolean noSwitch) {
this.noSwitch = noSwitch;
}
public boolean isSwitchOnly() {
return switchOnly;
}
public void setSwitchOnly(boolean switchOnly) {
this.switchOnly = switchOnly;
}
} |
package org.apache.couchdb.lucene;
import static java.lang.Math.min;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.FieldSelector;
import org.apache.lucene.document.MapFieldSelector;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FieldDoc;
import org.apache.lucene.search.IndexSearcher;
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.TopDocs;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.search.BooleanClause.Occur;
public final class SearchRequest {
private static final FieldSelector FS = new MapFieldSelector(new String[] { Config.ID });
private static final Database DB = new Database(Config.DB_URL);
private final String dbname;
private final Query q;
private final int skip;
private final int limit;
private final Sort sort;
private final boolean debug;
private final boolean include_docs;
private final boolean rewrite_query;
private final String ifNoneMatch;
public SearchRequest(final JSONObject obj) throws ParseException {
final JSONObject headers = obj.getJSONObject("headers");
final JSONObject info = obj.getJSONObject("info");
final JSONObject query = obj.getJSONObject("query");
this.ifNoneMatch = headers.optString("If-None-Match");
this.dbname = info.getString("db_name");
this.skip = query.optInt("skip", 0);
this.limit = query.optInt("limit", 25);
this.debug = query.optBoolean("debug", false);
this.include_docs = query.optBoolean("include_docs", false);
this.rewrite_query = query.optBoolean("rewrite", false);
// Parse query.
final BooleanQuery q = new BooleanQuery();
q.add(new TermQuery(new Term(Config.DB, this.dbname)), Occur.MUST);
q.add(Config.QP.parse(query.getString("q")), Occur.MUST);
this.q = q;
// Parse sort order.
final String sort = query.optString("sort", null);
if (sort == null) {
this.sort = null;
} else {
final String[] split = sort.split(",");
final SortField[] sort_fields = new SortField[split.length];
for (int i = 0; i < split.length; i++) {
switch (split[i].charAt(0)) {
case '/':
sort_fields[i] = new SortField(split[i].substring(1));
break;
case '\\':
sort_fields[i] = new SortField(split[i].substring(1), true);
break;
default:
sort_fields[i] = new SortField(split[i]);
break;
}
}
if (sort_fields.length == 1) {
// Let Lucene add doc as secondary sort order.
this.sort = new Sort(sort_fields[0].getField(), sort_fields[0].getReverse());
} else {
this.sort = new Sort(sort_fields);
}
}
}
public String execute(final IndexSearcher searcher) throws IOException {
// Decline requests over MAX_LIMIT.
if (limit > Config.MAX_LIMIT) {
return "{\"code\":400,\"body\":\"max limit was exceeded.\"}";
}
// Return "304 - Not Modified" if etag matches.
final String etag = getETag(searcher);
if (etag.equals(this.ifNoneMatch)) {
return "{\"code\":304}";
}
final JSONObject json = new JSONObject();
json.put("q", q.toString(Config.DEFAULT_FIELD));
json.put("etag", etag);
if (rewrite_query) {
final Query rewritten_q = q.rewrite(searcher.getIndexReader());
json.put("rewritten_q", rewritten_q.toString(Config.DEFAULT_FIELD));
final JSONObject freqs = new JSONObject();
final Set terms = new HashSet();
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 search.
final TopDocs td;
final StopWatch stopWatch = new StopWatch();
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 = 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, FS);
final JSONObject obj = new JSONObject();
// Include basic details.
obj.put("_id", doc.get(Config.ID));
obj.put("score", td.scoreDocs[i].score);
// Include sort order (if any).
if (td instanceof TopFieldDocs) {
final FieldDoc fd = (FieldDoc) ((TopFieldDocs) td).scoreDocs[i];
obj.put("sort_order", fd.fields);
}
// Fetch document (if requested).
if (include_docs) {
fetch_ids[i - skip] = doc.get(Config.ID);
}
rows.add(obj);
}
// Fetch documents (if requested).
if (include_docs) {
final JSONArray fetched_docs = DB.getDocs(dbname, fetch_ids).getJSONArray("rows");
for (int i = 0; i < max; i++) {
rows.getJSONObject(i).put("doc", fetched_docs.get(i));
}
}
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", toString(((TopFieldDocs) td).fields));
}
json.put("rows", rows);
}
final JSONObject result = new JSONObject();
result.put("code", 200);
final JSONObject headers = new JSONObject();
// Cache for 5 minutes.
headers.put("Cache-Control", "max-age=300");
// Results can't change unless the IndexReader does.
headers.put("ETag", etag);
result.put("headers", headers);
if (debug) {
result.put("body", String.format("<pre>%s</pre>", StringEscapeUtils.escapeHtml(json.toString(2))));
} else {
result.put("json", json);
}
return result.toString();
}
private String getETag(final IndexSearcher searcher) {
return Long.toHexString(searcher.getIndexReader().getVersion());
}
private 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();
}
} |
package org.jenkinsci.backend.ircbot;
import com.atlassian.jira.rest.client.api.ComponentRestClient;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.RestClientException;
import com.atlassian.jira.rest.client.api.domain.AssigneeType;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.Comment;
import com.atlassian.jira.rest.client.api.domain.Component;
import com.atlassian.jira.rest.client.api.domain.IssueField;
import com.atlassian.jira.rest.client.api.domain.input.ComponentInput;
import com.atlassian.jira.rest.client.api.domain.input.TransitionInput;
import com.atlassian.util.concurrent.Promise;
import org.apache.commons.lang.StringUtils;
import org.jibble.pircbot.PircBot;
import org.jibble.pircbot.User;
import org.kohsuke.github.GHEvent;
import org.kohsuke.github.GHOrganization;
import org.kohsuke.github.GHOrganization.Permission;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHTeam;
import org.kohsuke.github.GHUser;
import org.kohsuke.github.GitHub;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.*;
import javax.annotation.CheckForNull;
/**
* IRC Bot on irc.freenode.net as a means to delegate administrative work to committers.
*
* @author Kohsuke Kawaguchi
*/
public class IrcBotImpl extends PircBot {
private static final String FORK_TO_JIRA_FIELD = "customfield_10321";
private static final String FORK_FROM_JIRA_FIELD = "customfield_10320";
private static final String USER_LIST_JIRA_FIELD = "customfield_10323";
private static final int DONE_JIRA_RESOLUTION_ID = 10000;
/**
* Records commands that we didn't understand.
*/
private File unknownCommands;
/**
* Map from the issue number to the time it was last mentioned.
* Used so that we don't repeatedly mention the same issues.
*/
@SuppressWarnings("unchecked")
private final Map<String,Long> recentIssues = Collections.<String,Long>synchronizedMap(new HashMap<String,Long>(10));
public IrcBotImpl(File unknownCommands) {
setName(IrcBotConfig.NAME);
this.unknownCommands = unknownCommands;
}
@Override
protected void onMessage(String channel, String sender, String login, String hostname, String message) {
if (!IrcBotConfig.getChannels().contains(channel)) return; // not in this channel
if (sender.equals("jenkinsci_builds") || sender.equals("jenkins-admin") || sender.startsWith("ircbot-"))
return; // ignore messages from other bots
final String directMessagePrefix = getNick() + ":";
message = message.trim();
try {
if (message.startsWith(directMessagePrefix)) { // Direct command to the bot
// remove prefixes, trim whitespaces
String payload = message.substring(directMessagePrefix.length(), message.length()).trim();
payload = payload.replaceAll("\\s+", " ");
handleDirectCommand(channel, sender, login, hostname, payload);
} else { // Just a commmon message in the chat
replyBugStatuses(channel, message);
}
} catch (RuntimeException ex) { // Catch unhandled runtime issues
ex.printStackTrace();
sendMessage(channel, "An error ocurred in the Bot. Please submit a bug to Jenkins INFRA project.");
sendMessage(channel, ex.getMessage());
throw ex; // Propagate the error to the caller in order to let it log and handle the issue
}
}
private void replyBugStatuses(String channel, String message) {
Matcher m = Pattern.compile("(?:hudson-|jenkins-|bug )([0-9]{2,})",CASE_INSENSITIVE).matcher(message);
while (m.find()) {
replyBugStatus(channel,"JENKINS-"+m.group(1));
}
m = Pattern.compile("(?:infra-)([0-9]+)",CASE_INSENSITIVE).matcher(message);
while (m.find()) {
replyBugStatus(channel,"INFRA-"+m.group(1));
}
}
/**
* Handles direct commands coming to the bot.
* The handler presumes the external trimming of the payload.
*/
private void handleDirectCommand(String channel, String sender, String login, String hostname, String payload) {
Matcher m;
m = Pattern.compile("(?:create|make|add) (\\S+)(?: repository)? (?:on|in) github(?: for (\\S+))?",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
createGitHubRepository(channel, sender, m.group(1), m.group(2));
return;
}
m = Pattern.compile("fork (?:https://github\\.com/)?(\\S+)/(\\S+)(?: on github)?(?: as (\\S+))?",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
forkGitHub(channel, sender, m.group(1),m.group(2),m.group(3));
return;
}
m = Pattern.compile("rename (?:github )repo (\\S+) to (\\S+)",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
renameGitHubRepo(channel, sender, m.group(1), m.group(2));
return;
}
m = Pattern.compile("(?:make|give|grant|add) (\\S+)(?: as)? (?:a )?(?:committ?er|commit access) (?:of|on|to|at) (\\S+)",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
addGitHubCommitter(channel,sender,m.group(1),m.group(2));
return;
}
m = Pattern.compile("(?:make|give|grant|add) (\\S+)(?: as)? (a )?(committ?er|commit access).*",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
addGitHubCommitter(channel,sender,m.group(1),null);
return;
}
m = Pattern.compile("(?:create|make|add) (\\S+)(?: component)? in (?:the )?(?:issue|bug)(?: tracker| database)? for (\\S+)",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
createComponent(channel, sender, m.group(1), m.group(2));
return;
}
m = Pattern.compile("(?:rem|remove|del|delete) component (\\S+) and move its issues to (\\S+)",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
deleteComponent(channel, sender, m.group(1), m.group(2));
return;
}
m = Pattern.compile("rename component (\\S+) to (\\S+)",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
renameComponent(channel, sender, m.group(1), m.group(2));
return;
}
m = Pattern.compile("(?:rem|remove) (?:the )?(?:lead|default assignee) (?:for|of|from) (\\S+)",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
removeDefaultAssignee(channel, sender, m.group(1));
return;
}
m = Pattern.compile("(?:make|set) (\\S+) (?:the |as )?(?:lead|default assignee) (?:for|of) (\\S+)",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
setDefaultAssignee(channel, sender, m.group(2), m.group(1));
return;
}
m = Pattern.compile("set (?:the )?description (?:for|of) (?:component )?(\\S+) to \\\"(.*)\\\"",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
setComponentDescription(channel, sender, m.group(1) , m.group(2));
return;
}
m = Pattern.compile("(?:rem|remove) (?:the )?description (?:for|of) (?:component )?(\\S+)",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
setComponentDescription(channel, sender, m.group(1) , null);
return;
}
m = Pattern.compile("(?:make|give|grant|add) (\\S+) voice(?: on irc)?",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
grantAutoVoice(channel,sender,m.group(1));
return;
}
m = Pattern.compile("(?:rem|remove|ungrant|del|delete) (\\S+) voice(?: on irc)?",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
removeAutoVoice(channel,sender,m.group(1));
return;
}
m = Pattern.compile("(?:kick) (\\S+)",CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
kickUser(channel,sender,m.group(1));
return;
}
m = Pattern.compile("(?:host) (?:hosting-)(\\d+)((?:[ ]+)(\\S+))?", CASE_INSENSITIVE).matcher(payload);
if (m.matches()) {
String forkTo = "";
if(m.groupCount() > 1) {
forkTo = m.group(2);
}
setupHosting(channel,sender,m.group(1),forkTo);
return;
}
if (payload.equalsIgnoreCase("version")) {
version(channel);
return;
}
if (payload.equalsIgnoreCase("help")) {
help(channel);
return;
}
if (payload.equalsIgnoreCase("refresh")) {
// get the updated list
sendRawLine("NAMES " + channel);
return;
}
if (payload.equalsIgnoreCase("restart")) {
restart(channel,sender);
}
sendMessage(channel,"I didn't understand the command");
try {
PrintWriter w = new PrintWriter(new FileWriter(unknownCommands, true));
w.println(payload);
w.close();
} catch (IOException e) {// if we fail to write, let it be.
e.printStackTrace();
}
}
/**
* Restart ircbot.
*
* We just need to quit, and docker container manager will automatically restart
* another one. We've seen for some reasons sometimes jenkins-admin loses its +o flag,
* and when that happens a restart fixes it quickly.
*/
private void restart(String channel, String sender) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
sendMessage(channel,"I'll quit and come back");
System.exit(0);
}
private void kickUser(String channel, String sender, String target) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
kick(channel, target);
sendMessage(channel, "Kicked user" + target);
}
private void setupHosting(String channel, String sender, String hostingId, String forkTo) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
final String issueID = "HOSTING-" + hostingId;
sendMessage(channel, "Approving hosting request " + issueID);
replyBugStatus(channel, issueID);
try {
final JiraRestClient client = JiraHelper.createJiraClient();
final IssueRestClient issueClient = client.getIssueClient();
final Issue issue = JiraHelper.getIssue(client, issueID);
String forkFrom = "";
List<String> users = new ArrayList<String>();
String defaultAssignee = issue.getReporter().getName();
for(IssueField val : issue.getFields()) {
String fieldId = val.getId();
if(fieldId.equalsIgnoreCase(FORK_FROM_JIRA_FIELD)) {
Object _value = val.getValue();
if(_value != null) {
forkFrom = _value.toString();
}
}
if(fieldId.equalsIgnoreCase(USER_LIST_JIRA_FIELD)) {
Object _value = val.getValue();
if(_value != null) {
String userList = _value.toString();
for(String u : userList.split("\\n")) {
users.add(u.trim());
}
}
}
if(StringUtils.isBlank(forkTo) && fieldId.equalsIgnoreCase(FORK_TO_JIRA_FIELD)) {
Object _value = val.getValue();
if(_value != null) {
forkTo = _value.toString();
}
}
}
if(StringUtils.isBlank(forkFrom) || StringUtils.isBlank(forkTo) || users.size() == 0) {
sendMessage(channel,"Could not retrieve information (or information does not exist) from the HOSTING JIRA");
return;
}
// Parse forkFrom in order to determine original repo owner and repo name
Matcher m = Pattern.compile("(?:https:\\/\\/github\\.com/)?(\\S+)\\/(\\S+)",CASE_INSENSITIVE).matcher(forkFrom);
if (m.matches()) {
if(!forkGitHub(channel,sender,m.group(1),m.group(2),forkTo)) {
sendMessage(channel,"Hosting request failed to fork repository on Github");
return;
}
} else {
sendMessage(channel, "ERROR: Cannot parse repo " + forkFrom);
return;
}
// add the users to the repo
for(String user : users) {
if(!addGitHubCommitter(channel,sender,user,forkTo)) {
sendMessage(channel,"Hosting request failed to add "+user+" as committer, continuing anyway");
}
}
// create the JIRA component
if(!createComponent(channel,sender,forkTo,defaultAssignee)) {
sendMessage(channel,"Hosting request failed to create component "+forkTo+" in JIRA");
return;
}
// update the issue with information on next steps
String msg = "The code has been forked into the jenkinsci project on GitHub as "
+ "https://github.com/jenkinsci/" + forkTo
+ "\n\nA JIRA component named " + forkTo + " has also been created with "
+ defaultAssignee + " as the default assignee for issues."
+ "\n\nPlease remove your original repository so that the jenkinsci repository "
+ "is the definitive source for the code. Also, please make sure you have "
+ "a wiki page setup with the following guidelines in mind: "
+ "https://wiki.jenkins-ci.org/display/JENKINS/Hosting+Plugins#HostingPlugins-CreatingaWikipage"
+ "\n\nWelcome aboard!";
// add comment
issueClient.addComment(new URI(issue.getSelf().toString() + "/comment"), Comment.valueOf(msg)).
get(IrcBotConfig.JIRA_TIMEOUT_SEC, TimeUnit.SECONDS);
// mark as "done".
try {
//TODO: Better message
Comment closingComment = Comment.valueOf("Marking the issue as Done");
Promise<Void> transition = issueClient.transition(issue, new TransitionInput(DONE_JIRA_RESOLUTION_ID, closingComment));
JiraHelper.wait(transition);
} catch (RestClientException e) {
// if the issue cannot be put into the "resolved" state
// (perhaps it's already in that state), let it be. Or else
// we end up with the carpet bombing like HUDSON-2552.
// See HUDSON-5133 for the failure mode.
System.err.println("Failed to mark the issue as Done");
e.printStackTrace();
}
sendMessage(channel,"Hosting setup complete");
} catch(Exception e) {
e.printStackTrace();
sendMessage(channel,"Failed setting up hosting for HOSTING-" + hostingId + ". " + e.getMessage());
}
}
private void replyBugStatus(String channel, String ticket) {
Long time = recentIssues.get(ticket);
recentIssues.put(ticket,System.currentTimeMillis());
if (time!=null) {
if (System.currentTimeMillis()-time < 60*1000) {
return; // already mentioned recently. don't repeat
}
}
try {
sendMessage(channel, JiraHelper.getSummary(ticket));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Is the sender respected in the channel?
*
* IOW, does he have a voice of a channel operator?
*/
private boolean isSenderAuthorized(String channel, String sender) {
return isSenderAuthorized(channel, sender, true);
}
private boolean isSenderAuthorized(String channel, String sender, boolean acceptVoice) {
for (User u : getUsers(channel)) {
System.out.println(u.getPrefix()+u.getNick());
if (u.getNick().equals(sender)) {
String p = u.getPrefix();
if (p.contains("@") || (acceptVoice && p.contains("+"))
|| (IrcBotConfig.TEST_SUPERUSER != null && IrcBotConfig.TEST_SUPERUSER.equals(sender) ))
return true;
}
}
return false;
}
@Override
protected void onDisconnect() {
while (!isConnected()) {
try {
reconnect();
for (String channel : IrcBotConfig.getChannels()) {
joinChannel(channel);
}
} catch (Exception e) {
e.printStackTrace();
try {
Thread.sleep(15000);
} catch (InterruptedException _) {
return; // abort
}
}
}
}
private void help(String channel) {
sendMessage(channel,"See http://wiki.jenkins-ci.org/display/JENKINS/IRC+Bot");
}
private void version(String channel) {
try {
IrcBotBuildInfo buildInfo = IrcBotBuildInfo.readResourceFile("/versionInfo.properties");
sendMessage(channel,"My version is "+buildInfo);
sendMessage(channel,"Build URL: "+buildInfo.getBuildURL());
} catch (IOException e) {
e.printStackTrace();
sendMessage(channel,"I don't know who I am");
}
}
private void insufficientPermissionError(String channel) {
insufficientPermissionError(channel, true);
}
private void insufficientPermissionError(String channel, boolean acceptVoice ) {
final String requiredPrefix = acceptVoice ? "+ or @" : "@";
sendMessage(channel,"Only people with "+requiredPrefix+" can run this command.");
// I noticed that sometimes the bot just get out of sync, so ask the sender to retry
sendRawLine("NAMES " + channel);
sendMessage(channel,"I'll refresh the member list, so if you think this is an error, try again in a few seconds.");
}
/**
* Creates an issue tracker component.
*/
private boolean createComponent(String channel, String sender, String subcomponent, String owner) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return false;
}
sendMessage(channel,String.format("Adding a new JIRA subcomponent %s to the %s project, owned by %s",
subcomponent, IrcBotConfig.JIRA_DEFAULT_PROJECT, owner));
boolean result = false;
try {
final ComponentRestClient componentClient = JiraHelper.createJiraClient().getComponentClient();
final Promise<Component> createComponent = componentClient.createComponent(IrcBotConfig.JIRA_DEFAULT_PROJECT,
new ComponentInput(subcomponent, "subcomponent", owner, AssigneeType.COMPONENT_LEAD));
final Component component = JiraHelper.wait(createComponent);
component.getSelf();
sendMessage(channel,"New component created. URL is " + component.getSelf().toURL());
result = true;
} catch (Exception e) {
sendMessage(channel,"Failed to create a new component: "+e.getMessage());
e.printStackTrace();
}
return result;
}
/**
* Renames an issue tracker component.
*/
private void renameComponent(String channel, String sender, String oldName, String newName) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
sendMessage(channel,String.format("Renaming subcomponent %s to %s", oldName, newName));
try {
final JiraRestClient client = JiraHelper.createJiraClient();
final Component component = JiraHelper.getComponent(client, IrcBotConfig.JIRA_DEFAULT_PROJECT, oldName);
final ComponentRestClient componentClient = JiraHelper.createJiraClient().getComponentClient();
Promise<Component> updateComponent = componentClient.updateComponent(component.getSelf(),
new ComponentInput(newName, component.getDescription(), component.getLead().getName(),
component.getAssigneeInfo().getAssigneeType()));
JiraHelper.wait(updateComponent);
sendMessage(channel,"The component has been renamed");
} catch (Exception e) {
sendMessage(channel,e.getMessage());
e.printStackTrace();
}
}
/**
* Deletes an issue tracker component.
*/
private void deleteComponent(String channel, String sender, String deletedComponent, String backupComponent) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
sendMessage(channel,String.format("Deleting the subcomponent %s. All issues will be moved to %s", deletedComponent, backupComponent));
try {
final JiraRestClient client = JiraHelper.createJiraClient();
final Component component = JiraHelper.getComponent(client, IrcBotConfig.JIRA_DEFAULT_PROJECT, deletedComponent);
final Component componentBackup = JiraHelper.getComponent(client, IrcBotConfig.JIRA_DEFAULT_PROJECT, backupComponent);
Promise<Void> removeComponent = client.getComponentClient().removeComponent(component.getSelf(), componentBackup.getSelf());
JiraHelper.wait(removeComponent);
sendMessage(channel,"The component has been deleted");
} catch (Exception e) {
sendMessage(channel,e.getMessage());
e.printStackTrace();
}
}
/**
* Deletes an assignee from the specified component
*/
private void removeDefaultAssignee(String channel, String sender, String subcomponent) {
setDefaultAssignee(channel, sender, subcomponent, null);
}
/**
* Creates an issue tracker component.
* @param owner User ID or null if the owner should be removed
*/
private void setDefaultAssignee(String channel, String sender, String subcomponent, @CheckForNull String owner) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
sendMessage(channel,String.format("Changing default assignee of subcomponent %s to %s",subcomponent,owner));
try {
final JiraRestClient client = JiraHelper.createJiraClient();
final Component component = JiraHelper.getComponent(client, IrcBotConfig.JIRA_DEFAULT_PROJECT, subcomponent);
Promise<Component> updateComponent = client.getComponentClient().updateComponent(component.getSelf(),
new ComponentInput(component.getName(), component.getDescription(),
owner != null ? owner : "", AssigneeType.COMPONENT_LEAD));
JiraHelper.wait(updateComponent);
sendMessage(channel, owner != null ? "Default assignee set to " + owner : "Default assignee has been removed");
} catch (Exception e) {
sendMessage(channel,"Failed to set default assignee: "+e.getMessage());
e.printStackTrace();
}
}
/**
* Sets the component description.
* @param description Component description. Use null to remove the description
*/
private void setComponentDescription(String channel, String sender, String componentName, @CheckForNull String description) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
sendMessage(channel,String.format("Updating the description of component %s", componentName));
try {
final JiraRestClient client = JiraHelper.createJiraClient();
final Component component = JiraHelper.getComponent(client, IrcBotConfig.JIRA_DEFAULT_PROJECT, componentName);
Promise<Component> updateComponent = client.getComponentClient().updateComponent(component.getSelf(),
new ComponentInput(component.getName(),
description != null ? description : "",
component.getAssigneeInfo().getAssignee().getName(), AssigneeType.COMPONENT_LEAD));
JiraHelper.wait(updateComponent);
sendMessage(channel,"The component description has been " + (description != null ? "updated" : "removed"));
} catch (Exception e) {
sendMessage(channel,e.getMessage());
e.printStackTrace();
}
}
private void grantAutoVoice(String channel, String sender, String target) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
sendMessage("CHANSERV", "flags " + channel + " " + target + " +V");
sendMessage("CHANSERV", "voice " + channel + " " + target);
sendMessage(channel, "Voice privilege (+V) added for " + target);
}
private void removeAutoVoice(String channel, String sender, String target) {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
sendMessage("CHANSERV", "flags " + channel + " " + target + " -V");
sendMessage("CHANSERV", "devoice " + channel + " " + target);
sendMessage(channel, "Voice privilege (-V) removed for " + target);
}
private void createGitHubRepository(String channel, String sender, String name, String collaborator) {
try {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return;
}
GitHub github = GitHub.connect();
GHOrganization org = github.getOrganization(IrcBotConfig.GITHUB_ORGANIZATION);
GHRepository r = org.createRepository(name, "", "", IrcBotConfig.GITHUB_DEFAULT_TEAM, true);
setupRepository(r);
GHTeam t = getOrCreateRepoLocalTeam(org, r);
if (collaborator!=null)
t.add(github.getUser(collaborator));
sendMessage(channel,"New github repository created at "+r.getUrl());
} catch (IOException e) {
sendMessage(channel,"Failed to create a repository: "+e.getMessage());
e.printStackTrace();
}
}
/**
* Adds a new collaborator to existing repositories.
*
* @param justForThisRepo
* Null to add to add the default team ("Everyone"), otherwise add him to a team specific repository.
*/
private boolean addGitHubCommitter(String channel, String sender, String collaborator, String justForThisRepo) {
boolean result = false;
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return false;
}
try {
GitHub github = GitHub.connect();
GHUser c = github.getUser(collaborator);
GHOrganization o = github.getOrganization(IrcBotConfig.GITHUB_ORGANIZATION);
final GHTeam t;
if (justForThisRepo != null) {
GHRepository forThisRepo = o.getRepository(justForThisRepo);
if (forThisRepo == null) {
sendMessage(channel,"Could not find repository: "+justForThisRepo);
return false;
}
t = getOrCreateRepoLocalTeam(o, forThisRepo);
} else {
t = o.getTeams().get(IrcBotConfig.GITHUB_DEFAULT_TEAM);
}
if (t==null) {
sendMessage(channel,"No team for "+justForThisRepo);
return false;
}
t.add(c);
String successMsg = "Added "+collaborator+" as a GitHub committer";
if (justForThisRepo != null) {
successMsg += " for repository " + justForThisRepo;
}
sendMessage(channel,successMsg);
result = true;
} catch (IOException e) {
sendMessage(channel,"Failed to create a repository: "+e.getMessage());
e.printStackTrace();
}
return result;
}
private void renameGitHubRepo(String channel, String sender, String repo, String newName) {
try {
if (!isSenderAuthorized(channel, sender, false)) {
insufficientPermissionError(channel, false);
return;
}
sendMessage(channel, "Renaming " + repo + " to " + newName);
GitHub github = GitHub.connect();
GHOrganization o = github.getOrganization(IrcBotConfig.GITHUB_ORGANIZATION);
GHRepository orig = o.getRepository(repo);
if (orig == null) {
sendMessage(channel, "No such repository: " + repo);
return;
}
orig.renameTo(newName);
sendMessage(channel, "The repository has been renamed: https://github.com/" + IrcBotConfig.GITHUB_ORGANIZATION+"/"+newName);
} catch (IOException e) {
sendMessage(channel, "Failed to rename a repository: " + e.getMessage());
e.printStackTrace();
}
}
/**
* @param newName
* If not null, rename a epository after a fork.
*/
private boolean forkGitHub(String channel, String sender, String owner, String repo, String newName) {
boolean result = false;
try {
if (!isSenderAuthorized(channel,sender)) {
insufficientPermissionError(channel);
return false;
}
sendMessage(channel, "Forking "+repo);
GitHub github = GitHub.connect();
GHUser user = github.getUser(owner);
if (user==null) {
sendMessage(channel,"No such user: "+owner);
return false;
}
GHRepository orig = user.getRepository(repo);
if (orig==null) {
sendMessage(channel,"No such repository: "+repo);
return false;
}
GHOrganization org = github.getOrganization(IrcBotConfig.GITHUB_ORGANIZATION);
GHRepository r;
try {
r = orig.forkTo(org);
} catch (IOException e) {
// we started seeing 500 errors, presumably due to time out.
// give it a bit of time, and see if the repository is there
System.out.println("GitHub reported that it failed to fork "+owner+"/"+repo+". But we aren't trusting");
r = null;
for (int i=0; r==null && i<5; i++) {
Thread.sleep(1000);
r = org.getRepository(repo);
}
if (r==null)
throw e;
}
if (newName!=null) {
r.renameTo(newName);
r = null;
for (int i=0; r==null && i<5; i++) {
Thread.sleep(1000);
r = org.getRepository(newName);
}
if (r==null)
throw new IOException(repo+" renamed to "+newName+" but not finding the new repository");
}
// GitHub adds a lot of teams to this repo by default, which we don't want
Set<GHTeam> legacyTeams = r.getTeams();
GHTeam t = getOrCreateRepoLocalTeam(org, r);
try {
t.add(user); // the user immediately joins this team
} catch (IOException e) {
// if 'user' is an org, the above command would fail
sendMessage(channel,"Failed to add "+user+" to the new repository. Maybe an org?: "+e.getMessage());
// fall through
}
setupRepository(r);
sendMessage(channel, "Created https://github.com/" + IrcBotConfig.GITHUB_ORGANIZATION + "/" + (newName != null ? newName : repo));
// remove all the existing teams
for (GHTeam team : legacyTeams)
team.remove(r);
result = true;
} catch (InterruptedException e) {
sendMessage(channel,"Failed to fork a repository: "+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
sendMessage(channel,"Failed to fork a repository: "+e.getMessage());
e.printStackTrace();
}
return result;
}
/**
* Fix up the repository set up to our policy.
*/
private void setupRepository(GHRepository r) throws IOException {
r.setEmailServiceHook(IrcBotConfig.GITHUB_POST_COMMIT_HOOK_EMAIL);
r.enableIssueTracker(false);
r.enableWiki(false);
r.createHook(IrcBotConfig.IRC_HOOK_NAME,
IrcBotConfig.getIRCHookConfig(), (Collection<GHEvent>) null,
true);
}
/**
* Creates a repository local team, and grants access to the repository.
*/
private GHTeam getOrCreateRepoLocalTeam(GHOrganization org, GHRepository r) throws IOException {
String teamName = r.getName() + " Developers";
GHTeam t = org.getTeams().get(teamName);
if (t==null) {
t = org.createTeam(teamName, Permission.ADMIN, r);
} else {
if (!t.getRepositories().containsValue(r)) {
t.add(r);
}
}
return t;
}
public static void main(String[] args) throws Exception {
IrcBotImpl bot = new IrcBotImpl(new File("unknown-commands.txt"));
System.out.println("Connecting to "+IrcBotConfig.SERVER+" as "+IrcBotConfig.NAME);
System.out.println("GitHub organization = "+IrcBotConfig.GITHUB_ORGANIZATION);
bot.connect(IrcBotConfig.SERVER);
bot.setVerbose(true);
for (String channel : IrcBotConfig.getChannels()) {
bot.joinChannel(channel);
}
if (args.length>0) {
System.out.println("Authenticating with NickServ");
bot.sendMessage("nickserv","identify "+args[0]);
}
}
static {
class TrustAllManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}
}
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new TrustAllManager()}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
throw new Error(e);
}
}
} |
package org.jenkinsci.plugins;
import hudson.Launcher;
import hudson.Extension;
import hudson.util.FormValidation;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.AbstractProject;
import hudson.tasks.Builder;
import hudson.tasks.BuildStepDescriptor;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import javax.servlet.ServletException;
import java.io.IOException;
/**
* Sample {@link Builder}.
*
* <p>
* When the user configures the project and enables this builder,
* {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked
* and a new {@link TattletaleBuilder} is created. The created
* instance is persisted to the project configuration XML by using
* XStream, so this allows you to use instance fields (like {@link #inputDirectory})
* to remember the configuration.
*
* <p>
* When a build is performed, the {@link #perform(AbstractBuild, Launcher, BuildListener)}
* method will be invoked.
*
* @author Vaclav Tunka
*/
public class TattletaleBuilder extends Builder {
private final String inputDirectory;
private final String outputDirectory;
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public TattletaleBuilder(String inputDirectory, String outputDirectory) {
this.inputDirectory = inputDirectory;
this.outputDirectory = outputDirectory;
}
/**
* We'll use this from the <tt>config.jelly</tt>.
*/
public String getInputDirectory() {
return inputDirectory;
}
public String getOutputLocation() {
return outputDirectory;
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
// This is where you 'build' the project.
listener.getLogger().println("Input directory: " + inputDirectory);
listener.getLogger().println("Output directory: " + outputDirectory);
// This also shows how you can consult the global configuration of the builder
if (getDescriptor().getOverrideConfig()) {
listener.getLogger().println("Default global config overriden.");
listener.getLogger().println("Tattletale jar location: \n"
+ getDescriptor().getTattletaleJarLocation());
listener.getLogger().println("Javassist jar location: \n"
+ getDescriptor().getJavassistJarLocation());
listener.getLogger().println("Tattletale properties location: \n"
+ getDescriptor().getPropertiesLocation());
}
return true;
}
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
* See <tt>src/main/resources/org/jenkinsci/plugins/TattletaleBuilder/*.jelly</tt>
* for the actual HTML fragment for the configuration screen.
*/
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
/**
* To persist global configuration information,
* simply store it in a field and call save().
*
* <p>
* If you don't want fields to be persisted, use <tt>transient</tt>.
*/
private boolean overrideConfig;
private String tattletaleJarLocation;
private String javassistJarLocation;
private String propertiesLocation;
public DescriptorImpl() {
super(TattletaleBuilder.class);
load();
}
/**
* Performs on-the-fly validation of the form field 'inputDirectory'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
*/
public FormValidation doCheckInputDirectory(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please set a project location to be analyzed.");
return FormValidation.ok();
}
/**
* Performs on-the-fly validation of the form field 'outputDirectory'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
*/
public FormValidation doCheckOutputDirectory(@QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please set tattletale report directory");
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Invoke Tattletale";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
// To persist global configuration information,
// set that to properties and call save().
overrideConfig = formData.getBoolean("overrideConfig");
tattletaleJarLocation = formData.getString("tattletaleJarLocation");
javassistJarLocation = formData.getString("javassistJarLocation");
propertiesLocation = formData.getString("propertiesLocation");
// ^Can also use req.bindJSON(this, formData);
// (easier when there are many fields; need set* methods for this, like setUseFrench)
save();
return super.configure(req,formData);
}
public void setOverrideConfig(boolean overrideConfig) {
this.overrideConfig = overrideConfig;
}
public void setTattletaleJarLocation(String tattletaleJarLocation) {
this.tattletaleJarLocation = tattletaleJarLocation;
}
public void setJavassistJarLocation(String javassistJarLocation) {
this.javassistJarLocation = javassistJarLocation;
}
public void setPropertiesLocation(String propertiesLocation) {
this.propertiesLocation = propertiesLocation;
}
/**
*
* The method name is bit awkward because global.jelly calls this method to determine
* the initial state of the checkbox by the naming convention.
*/
public boolean getOverrideConfig() {
return overrideConfig;
}
public String getTattletaleJarLocation() {
return tattletaleJarLocation;
}
public String getJavassistJarLocation() {
return javassistJarLocation;
}
public String getPropertiesLocation() {
return propertiesLocation;
}
}
} |
package org.jenkinsci.plugins.p4.scm;
import com.perforce.p4java.core.file.FileSpecBuilder;
import com.perforce.p4java.core.file.IFileSpec;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.Items;
import jenkins.scm.api.SCMFile;
import jenkins.scm.api.SCMProbe;
import jenkins.scm.api.SCMProbeStat;
import org.jenkinsci.plugins.p4.client.TempClientHelper;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
public class P4SCMProbe extends SCMProbe {
@Initializer(before = InitMilestone.PLUGINS_STARTED)
public static void addAliases() {
Items.XSTREAM2.addCompatibilityAlias("org.jenkinsci.plugins.p4.scm.P4Probe", P4SCMProbe.class);
}
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(P4SCMProbe.class.getName());
private final P4SCMHead head;
private transient TempClientHelper p4;
public P4SCMProbe(TempClientHelper p4, P4SCMHead head) {
this.head = head;
this.p4 = p4;
}
@Override
public String name() {
return head.getName();
}
@Override
public long lastModified() {
long last = 0L;
try {
// use temp workspace and client syntax to get changes
long change = p4.getClientHead();
if (change > last) {
last = change;
}
} catch (Exception e) {
logger.warning("Unable to check changes: " + e.getMessage());
}
return last;
}
@Override
public SCMProbeStat stat(@NonNull String file) throws IOException {
try {
P4Path path = head.getPath();
String filePath = path.getPathBuilder(file); // Depot Path syntax
// When probing Streams, switch to use client path syntax. This works for
// all streams, including virtual streams(JENKINS-62699).
p4.log("Scanning for " + filePath);
String clientStream = p4.getClient().getStream();
if ( clientStream != null ) {
filePath = filePath.replaceFirst(clientStream, "//" + p4.getClientUUID());
}
if (p4.hasFile(filePath)) {
return SCMProbeStat.fromType(SCMFile.Type.REGULAR_FILE);
}
} catch (Exception e) {
throw new IOException("Unable to check file: " + e.getMessage());
}
return SCMProbeStat.fromType(SCMFile.Type.NONEXISTENT);
}
@Override
public void close() throws IOException {
// No need to close ConnectionHelper
}
} |
package Game;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LoadLevel {
static Scanner scanner;
//Load the level
public static Square[][] loadLevel(String filepath, int width){
Square[][] squareArray = new Square[width][World.worldHeight];
try {
scanner = new Scanner(new File(filepath + ".level"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for(int y = 0;y < width;y++){
for(int x = 0;x < World.worldHeight;x++){
squareArray[x][y] = new Square(x,y,scanner.nextInt());
System.out.println(squareArray[x][y].ID);
}
}
return squareArray;
}
//Load level info such as width, height etc.
public static int loadLevelInfo(String filepath){
int width;
try {
scanner = new Scanner(new File(filepath + ".levelinfo"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
width = scanner.nextInt();
return width;
}
} |
package org.konstructs.furnace;
import akka.actor.ActorRef;
import akka.actor.Props;
import konstructs.api.*;
import konstructs.api.messages.*;
import konstructs.plugin.KonstructsActor;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class FurnaceViewActor extends KonstructsActor {
/*
* [A] - Input
* [C] - Output
* [B] - Fuel
*
*/
private InventoryView inputView = new InventoryView(6, 2, 1, 1);
private InventoryView fuelView = new InventoryView(2, 2, 1, 1);
private InventoryView outputView = new InventoryView(4, 4, 1, 1);
private Map<InventoryId, InventoryView> inventoryViewMapping = new HashMap<>();
private ActorRef player;
private UUID blockId;
private static final InventoryId INV_FUEL = InventoryId.fromString("org/konstructs/FUEL");
public FurnaceViewActor(ActorRef universe, ActorRef player, UUID blockId) {
super(universe);
this.player = player;
this.blockId = blockId;
inventoryViewMapping.put(InventoryId.INPUT, inputView);
inventoryViewMapping.put(InventoryId.OUTPUT, outputView);
inventoryViewMapping.put(INV_FUEL, fuelView);
player.tell(new ConnectView(getSelf(), View.EMPTY), getSelf());
getUniverse().tell(new GetInventoriesView(blockId, inventoryViewMapping), player);
}
@Override
public void onReceive(Object message) {
if (message instanceof PutViewStack && outputView.contains(((PutViewStack)message).getPosition())) {
player.tell(new ReceiveStack(((PutViewStack)message).getStack()), getSelf());
} else if (View.manageViewMessagesForInventories(message, blockId, inventoryViewMapping, getUniverse(), player)) {
// pass
} else if(message instanceof CloseView) {
getContext().stop(getSelf());
} else {
super.onReceive(message);
}
}
public static Props props(ActorRef universe, ActorRef player, UUID blockId) {
return Props.create(FurnaceViewActor.class, universe, player, blockId);
}
} |
package org.ktc.soapui.maven.extension;
import java.util.Properties;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.SoapUIProTestCaseRunner;
public class TestMojo extends AbstractMojo {
private String projectFile;
private String testSuite;
private String testCase;
private String username;
private String password;
private String wssPasswordType;
private String domain;
private String host;
private String endpoint;
private String outputFolder;
private boolean printReport;
private boolean interactive;
private boolean exportAll;
private boolean junitReport;
private boolean openReport;
private String settingsFile;
private boolean skip;
private String projectPassword;
private String settingsPassword;
private boolean testFailIgnore;
private boolean coverage;
private String[] globalProperties;
private String[] projectProperties;
private boolean saveAfterRun;
private String reportFormat;
private String reportName;
private Properties soapuiProperties;
// for issue #2 and #3
private MavenProject project;
public void execute() throws MojoExecutionException, MojoFailureException {
if ((this.skip) || (System.getProperty("maven.test.skip", "false").equals("true"))) {
// #1 add log when skipping tests
getLog().info("SoapUI tests are skipped.");
return;
}
if (this.projectFile == null) {
throw new MojoExecutionException("soapui-project-file setting is required");
}
SoapUIProTestCaseRunner runner = new SoapUIProTestCaseRunner("SoapUI Pro " + SoapUI.SOAPUI_VERSION + " Maven2 TestCase Runner");
runner.setProjectFile(this.projectFile);
if (this.endpoint != null) {
runner.setEndpoint(this.endpoint);
}
if (this.testSuite != null) {
runner.setTestSuite(this.testSuite);
}
if (this.testCase != null) {
runner.setTestCase(this.testCase);
}
if (this.username != null) {
runner.setUsername(this.username);
}
if (this.password != null) {
runner.setPassword(this.password);
}
if (this.wssPasswordType != null) {
runner.setWssPasswordType(this.wssPasswordType);
}
if (this.domain != null) {
runner.setDomain(this.domain);
}
if (this.host != null) {
runner.setHost(this.host);
}
if (this.outputFolder != null) {
runner.setOutputFolder(this.outputFolder);
}
runner.setPrintReport(this.printReport);
runner.setExportAll(this.exportAll);
runner.setJUnitReport(this.junitReport);
runner.setEnableUI(this.interactive);
runner.setOpenReport(this.openReport);
runner.setIgnoreError(this.testFailIgnore);
runner.setSaveAfterRun(this.saveAfterRun);
if (this.settingsFile != null) {
runner.setSettingsFile(this.settingsFile);
}
if (this.projectPassword != null) {
runner.setProjectPassword(this.projectPassword);
}
if (this.settingsPassword != null) {
runner.setSoapUISettingsPassword(this.settingsPassword);
}
if (this.coverage) {
runner.initCoverageBuilder();
}
if (this.globalProperties != null) {
runner.setGlobalProperties(this.globalProperties);
}
if (this.projectProperties != null) {
runner.setProjectProperties(this.projectProperties);
}
if (this.reportName != null) {
runner.setReportName(this.reportName);
}
if (this.reportFormat != null)
runner.setReportFormats(this.reportFormat.split(","));
if ((this.soapuiProperties != null) && (this.soapuiProperties.size() > 0)) {
for (Object keyObject : this.soapuiProperties.keySet()) {
String key = (String) keyObject;
System.out.println("Setting " + key + " value " + this.soapuiProperties.getProperty(key));
System.setProperty(key, this.soapuiProperties.getProperty(key));
}
}
try {
runner.run();
// for issue #2 and #3
// if (testFailIgnore) {
// getLog().warn("The testFailIgnore parameter has been set to true but some tests may have failed");
// boolean hasErrors = ErrorHandler.hasErrors(runner);
// getLog().info("Has failing tests? " + hasErrors);
// if (hasErrors) {
// final String propertyName = "soapui.tests.have.failed";
// getLog().info("Setting project property " + propertyName);
// project.getProperties().setProperty(propertyName, "true");
// getLog().info(
// "Property " + propertyName + " set to " + project.getProperties().getProperty(propertyName));
} catch (Exception e) {
getLog().error(e.toString());
throw new MojoFailureException(this, "SoapUI Test(s) failed", e.getMessage());
}
}
} |
package org.lightmare.cache;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.persistence.EntityManagerFactory;
/**
* Container class for {@link EntityManagerFactory} with check if connection
* configuration is in progress and user count
*
* @author Levan Tsinadze
* @since 0.0.45-SNAPSHOT
* @see org.lightmare.deploy.BeanLoader#loadBean(org.lightmare.deploy.BeanLoader.BeanParameters)
* @see org.lightmare.cache.ConnectionContainer#cacheSemaphore(String, String)
* @see org.lightmare.cache.ConnectionContainer#getConnection(String)
* @see org.lightmare.cache.ConnectionContainer#getEntityManagerFactory(String)
* @see org.lightmare.cache.ConnectionContainer#getSemaphore(String)
* @see org.lightmare.cache.ConnectionContainer#isInProgress(String)
*/
public class ConnectionSemaphore {
// Flag if connection initialization is in progress
private final AtomicBoolean inProgress = new AtomicBoolean();
// Persistence unit name
private String unitName;
// JNDI name
private String jndiName;
// Checks if connection is already cached
private boolean cached;
// Check if connection is already bound to JNDI lookup
private boolean bound;
// EntityManagerFactory instance for persistence unit
private EntityManagerFactory emf;
// Number of user using the same connection
private final AtomicInteger users = new AtomicInteger();
// Check if needs configure EntityManagerFactory
private final AtomicBoolean check = new AtomicBoolean();
// Default semaphore capacity
public static final int MINIMAL_USERS = 1;
public boolean isInProgress() {
return inProgress.get();
}
public void setInProgress(boolean inProgress) {
this.inProgress.getAndSet(inProgress);
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
public boolean isCached() {
return cached;
}
public void setCached(boolean cached) {
this.cached = cached;
}
public boolean isBound() {
return bound;
}
public void setBound(boolean bound) {
this.bound = bound;
}
public EntityManagerFactory getEmf() {
return emf;
}
public void setEmf(EntityManagerFactory emf) {
this.emf = emf;
}
public int incrementUser() {
return users.incrementAndGet();
}
public int decrementUser() {
return users.decrementAndGet();
}
public int getUsers() {
return users.get();
}
public boolean isCheck() {
return check.getAndSet(Boolean.TRUE);
}
} |
package org.numenta.nupic.examples.qt;
import gnu.trove.list.array.TIntArrayList;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.numenta.nupic.ComputeCycle;
import org.numenta.nupic.Connections;
import org.numenta.nupic.Parameters;
import org.numenta.nupic.Parameters.KEY;
import org.numenta.nupic.algorithms.CLAClassifier;
import org.numenta.nupic.algorithms.SpatialPooler;
import org.numenta.nupic.algorithms.TemporalMemory;
//import org.numenta.nupic.algorithms.ClassifierResult;
import org.numenta.nupic.encoders.ScalarEncoder;
import org.numenta.nupic.model.Cell;
import org.numenta.nupic.util.ArrayUtils;
public class QuickTest {
static boolean isResetting = true;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Parameters params = getParameters();
System.out.println(params);
// Toggle this to switch between resetting on every week start day
isResetting = true;
//Layer components
ScalarEncoder.Builder dayBuilder =
ScalarEncoder.builder()
.n(8)
.w(3)
.radius(1.0)
.minVal(1.0)
.maxVal(8)
.periodic(true)
.forced(true)
.resolution(1);
ScalarEncoder encoder = dayBuilder.build();
SpatialPooler sp = new SpatialPooler();
TemporalMemory tm = new TemporalMemory();
CLAClassifier classifier = new CLAClassifier(new TIntArrayList(new int[] { 1 }), 0.1, 0.3, 0);
Layer<Double> layer = getLayer(params, encoder, sp, tm, classifier);
for(double i = 0, x = 0, j = 0;j < 1500;j = (i == 6 ? j + 1: j), i = (i == 6 ? 0 : i + 1), x++) { // USE "X" here to control run length
if (i == 0 && isResetting) {
System.out.println("reset:");
tm.reset(layer.getMemory());
}
// For 3rd argument: Use "i" for record num if re-cycling records (isResetting == true) - otherwise use "x" (the sequence number)
runThroughLayer(layer, i + 1, isResetting ? (int)i : (int)x, (int)x);
}
}
public static Parameters getParameters() {
Parameters parameters = Parameters.getAllDefaultParameters();
parameters.setParameterByKey(KEY.INPUT_DIMENSIONS, new int[] { 8 });
parameters.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 20 });
parameters.setParameterByKey(KEY.CELLS_PER_COLUMN, 6);
//SpatialPooler specific
parameters.setParameterByKey(KEY.POTENTIAL_RADIUS, 12);
parameters.setParameterByKey(KEY.POTENTIAL_PCT, 0.5);
parameters.setParameterByKey(KEY.GLOBAL_INHIBITIONS, false);
parameters.setParameterByKey(KEY.LOCAL_AREA_DENSITY, -1.0);
parameters.setParameterByKey(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 5.0);
parameters.setParameterByKey(KEY.STIMULUS_THRESHOLD, 1.0);
parameters.setParameterByKey(KEY.SYN_PERM_INACTIVE_DEC, 0.0005);
parameters.setParameterByKey(KEY.SYN_PERM_ACTIVE_INC, 0.0015);
parameters.setParameterByKey(KEY.SYN_PERM_TRIM_THRESHOLD, 0.05);
parameters.setParameterByKey(KEY.SYN_PERM_CONNECTED, 0.1);
parameters.setParameterByKey(KEY.MIN_PCT_OVERLAP_DUTY_CYCLE, 0.1);
parameters.setParameterByKey(KEY.MIN_PCT_ACTIVE_DUTY_CYCLE, 0.1);
parameters.setParameterByKey(KEY.DUTY_CYCLE_PERIOD, 10);
parameters.setParameterByKey(KEY.MAX_BOOST, 10.0);
parameters.setParameterByKey(KEY.SEED, 42);
parameters.setParameterByKey(KEY.SP_VERBOSITY, 0);
//Temporal Memory specific
parameters.setParameterByKey(KEY.INITIAL_PERMANENCE, 0.2);
parameters.setParameterByKey(KEY.CONNECTED_PERMANENCE, 0.8);
parameters.setParameterByKey(KEY.MIN_THRESHOLD, 5);
parameters.setParameterByKey(KEY.MAX_NEW_SYNAPSE_COUNT, 6);
parameters.setParameterByKey(KEY.PERMANENCE_INCREMENT, 0.1);//0.05
parameters.setParameterByKey(KEY.PERMANENCE_DECREMENT, 0.1);//0.05
parameters.setParameterByKey(KEY.ACTIVATION_THRESHOLD, 4);
return parameters;
}
public static <T> void runThroughLayer(Layer<T> l, T input, int recordNum, int sequenceNum) {
l.input(input, recordNum, sequenceNum);
}
public static Layer<Double> getLayer(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) {
Layer<Double> l = new LayerImpl(p, e, s, t, c);
return l;
}
////////////////// Preliminary Network API Toy ///////////////////
interface Layer<T> {
public void input(T value, int recordNum, int iteration);
public int[] getPredicted();
public Connections getMemory();
public int[] getActual();
}
/**
* I'm going to make an actual Layer, this is just temporary so I can
* work out the details while I'm completing this for Peter
*
* @author David Ray
*
*/
static class LayerImpl implements Layer<Double> {
private Parameters params;
private Connections memory = new Connections();
private ScalarEncoder encoder;
private SpatialPooler spatialPooler;
private TemporalMemory temporalMemory;
// private CLAClassifier classifier;
private Map<String, Object> classification = new LinkedHashMap<String, Object>();
private int columnCount;
private int cellsPerColumn;
// private int theNum;
private int[] predictedColumns;
private int[] actual;
private int[] lastPredicted;
public LayerImpl(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) {
this.params = p;
this.encoder = e;
this.spatialPooler = s;
this.temporalMemory = t;
// this.classifier = c;
params.apply(memory);
spatialPooler.init(memory);
temporalMemory.init(memory);
columnCount = memory.getPotentialPools().getMaxIndex() + 1; //If necessary, flatten multi-dimensional index
cellsPerColumn = memory.getCellsPerColumn();
}
public String stringValue(Double valueIndex) {
String recordOut = "";
BigDecimal bdValue = new BigDecimal(valueIndex).setScale(3, RoundingMode.HALF_EVEN);
switch(bdValue.intValue()) {
case 1: recordOut = "Monday (1)";break;
case 2: recordOut = "Tuesday (2)";break;
case 3: recordOut = "Wednesday (3)";break;
case 4: recordOut = "Thursday (4)";break;
case 5: recordOut = "Friday (5)";break;
case 6: recordOut = "Saturday (6)";break;
case 7: recordOut = "Sunday (7)";break;
}
return recordOut;
}
@Override
public void input(Double value, int recordNum, int sequenceNum) {
// String recordOut = stringValue(value);
if(value.intValue() == 1) {
// theNum++;
System.out.println("
// System.out.println("Iteration: " + theNum);
}
int[] output = new int[columnCount];
//Input through encoder
// System.out.println("ScalarEncoder Input = " + value);
int[] encoding = encoder.encode(value);
// System.out.println("ScalarEncoder Output = " + Arrays.toString(encoding));
int bucketIdx = encoder.getBucketIndices(value)[0];
//Input through spatial pooler
spatialPooler.compute(memory, encoding, output, true, true);
// System.out.println("SpatialPooler Output = " + Arrays.toString(output));
// Let the SpatialPooler train independently (warm up) first
// if(theNum < 200) return;
//Input through temporal memory
int[] input = actual = ArrayUtils.where(output, ArrayUtils.WHERE_1);
ComputeCycle cc = temporalMemory.compute(memory, input, true);
lastPredicted = predictedColumns;
predictedColumns = getSDR(cc.predictiveCells()); //Get the predicted column indexes
// int[] activeCellIndexes = Connections.asCellIndexes(cc.activeCells()).stream().mapToInt(i -> i).sorted().toArray(); //Get the active cells for classifier input
// System.out.println("TemporalMemory Input = " + Arrays.toString(input));
// System.out.println("TemporalMemory Prediction = " + Arrays.toString(predictedColumns));
classification.put("bucketIdx", bucketIdx);
classification.put("actValue", value);
// ClassifierResult<Double> result = classifier.compute(recordNum, classification, activeCellIndexes, true, true);
// System.out.print("CLAClassifier prediction = " + stringValue(result.getMostProbableValue(1)));
// System.out.println(" | CLAClassifier 1 step prob = " + Arrays.toString(result.getStats(1)) + "\n");
System.out.println("");
}
public int[] inflateSDR(int[] SDR, int len) {
int[] retVal = new int[len];
for(int i : SDR) {
retVal[i] = 1;
}
return retVal;
}
public int[] getSDR(Set<Cell> cells) {
int[] retVal = new int[cells.size()];
int i = 0;
for(Iterator<Cell> it = cells.iterator();i < retVal.length;i++) {
retVal[i] = it.next().getIndex();
retVal[i] /= cellsPerColumn; // Get the column index
}
Arrays.sort(retVal);
retVal = ArrayUtils.unique(retVal);
return retVal;
}
/**
* Returns the next predicted value.
*
* @return the SDR representing the prediction
*/
@Override
public int[] getPredicted() {
return lastPredicted;
}
/**
* Returns the actual columns in time t + 1 to compare
* with {@link #getPrediction()} which returns the prediction
* at time t for time t + 1.
* @return
*/
@Override
public int[] getActual() {
return actual;
}
/**
* Simple getter for external reset
* @return
*/
public Connections getMemory() {
return memory;
}
}
} |
package org.numenta.nupic.examples.qt;
import gnu.trove.list.array.TIntArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.numenta.nupic.Connections;
import org.numenta.nupic.Parameters;
import org.numenta.nupic.Parameters.KEY;
import org.numenta.nupic.algorithms.CLAClassifier;
import org.numenta.nupic.algorithms.ClassifierResult;
//import org.numenta.nupic.algorithms.ClassifierResult;
import org.numenta.nupic.encoders.ScalarEncoder;
import org.numenta.nupic.model.Cell;
import org.numenta.nupic.research.ComputeCycle;
import org.numenta.nupic.research.SpatialPooler;
import org.numenta.nupic.research.TemporalMemory;
import org.numenta.nupic.util.ArrayUtils;
public class QuickTest {
static boolean isResetting = true;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Parameters params = getParameters();
System.out.println(params);
// Toggle this to switch between resetting on every week start day
isResetting = false;
//Layer components
ScalarEncoder.Builder dayBuilder =
ScalarEncoder.builder()
.n(8)
.w(3)
.radius(1.0)
.minVal(1.0)
.maxVal(8)
.periodic(true)
.forced(true)
.resolution(1);
ScalarEncoder encoder = dayBuilder.build();
SpatialPooler sp = new SpatialPooler();
TemporalMemory tm = new TemporalMemory();
CLAClassifier classifier = new CLAClassifier(new TIntArrayList(new int[] { 1 }), 0.1, 0.3, 0);
Layer<Double> layer = getLayer(params, encoder, sp, tm, classifier);
for(double i = 0, x = 0;x < 10000;i = (i == 6 ? 0 : i + 1), x++) { // USE "X" here to control run length
if (i == 0 && isResetting) tm.reset(layer.getMemory());
// For 3rd argument: Use "i" for record num if re-cycling records (isResetting == true) - otherwise use "x" (the sequence number)
runThroughLayer(layer, i + 1, isResetting ? (int)i : (int)x, (int)x);
}
}
public static Parameters getParameters() {
Parameters parameters = Parameters.getAllDefaultParameters();
parameters.setParameterByKey(KEY.INPUT_DIMENSIONS, new int[] { 8 });
parameters.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 20 });
parameters.setParameterByKey(KEY.CELLS_PER_COLUMN, 6);
//SpatialPooler specific
parameters.setParameterByKey(KEY.POTENTIAL_RADIUS, 12);
parameters.setParameterByKey(KEY.POTENTIAL_PCT, 0.5);
parameters.setParameterByKey(KEY.GLOBAL_INHIBITIONS, false);
parameters.setParameterByKey(KEY.LOCAL_AREA_DENSITY, -1.0);
parameters.setParameterByKey(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 5.0);
parameters.setParameterByKey(KEY.STIMULUS_THRESHOLD, 1.0);
parameters.setParameterByKey(KEY.SYN_PERM_INACTIVE_DEC, 0.0005);
parameters.setParameterByKey(KEY.SYN_PERM_ACTIVE_INC, 0.0015);
parameters.setParameterByKey(KEY.SYN_PERM_TRIM_THRESHOLD, 0.05);
parameters.setParameterByKey(KEY.SYN_PERM_CONNECTED, 0.1);
parameters.setParameterByKey(KEY.MIN_PCT_OVERLAP_DUTY_CYCLE, 0.1);
parameters.setParameterByKey(KEY.MIN_PCT_ACTIVE_DUTY_CYCLE, 0.1);
parameters.setParameterByKey(KEY.DUTY_CYCLE_PERIOD, 10);
parameters.setParameterByKey(KEY.MAX_BOOST, 10.0);
parameters.setParameterByKey(KEY.SEED, 42);
parameters.setParameterByKey(KEY.SP_VERBOSITY, 0);
//Temporal Memory specific
parameters.setParameterByKey(KEY.INITIAL_PERMANENCE, 0.2);
parameters.setParameterByKey(KEY.CONNECTED_PERMANENCE, 0.8);
parameters.setParameterByKey(KEY.MIN_THRESHOLD, 5);
parameters.setParameterByKey(KEY.MAX_NEW_SYNAPSE_COUNT, 6);
parameters.setParameterByKey(KEY.PERMANENCE_INCREMENT, 0.05);
parameters.setParameterByKey(KEY.PERMANENCE_DECREMENT, 0.05);
parameters.setParameterByKey(KEY.ACTIVATION_THRESHOLD, 4);
return parameters;
}
public static <T> void runThroughLayer(Layer<T> l, T input, int recordNum, int sequenceNum) {
l.input(input, recordNum, sequenceNum);
}
public static Layer<Double> getLayer(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) {
Layer<Double> l = new LayerImpl(p, e, s, t, c);
return l;
}
////////////////// Preliminary Network API Toy ///////////////////
interface Layer<T> {
public void input(T value, int recordNum, int iteration);
public int[] getPredicted();
public Connections getMemory();
public int[] getActual();
}
/**
* I'm going to make an actual Layer, this is just temporary so I can
* work out the details while I'm completing this for Peter
*
* @author David Ray
*
*/
static class LayerImpl implements Layer<Double> {
private Parameters params;
private Connections memory = new Connections();
private ScalarEncoder encoder;
private SpatialPooler spatialPooler;
private TemporalMemory temporalMemory;
// private CLAClassifier classifier;
private Map<String, Object> classification = new LinkedHashMap<String, Object>();
private int columnCount;
private int cellsPerColumn;
// private int theNum;
private int[] predictedColumns;
private int[] actual;
private int[] lastPredicted;
public LayerImpl(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) {
this.params = p;
this.encoder = e;
this.spatialPooler = s;
this.temporalMemory = t;
// this.classifier = c;
params.apply(memory);
spatialPooler.init(memory);
temporalMemory.init(memory);
columnCount = memory.getPotentialPools().getMaxIndex() + 1; //If necessary, flatten multi-dimensional index
cellsPerColumn = memory.getCellsPerColumn();
}
@Override
public void input(Double value, int recordNum, int sequenceNum) {
// String recordOut = "";
// switch(recordNum) {
// case 1: recordOut = "Monday (1)";break;
// case 2: recordOut = "Tuesday (2)";break;
// case 3: recordOut = "Wednesday (3)";break;
// case 4: recordOut = "Thursday (4)";break;
// case 5: recordOut = "Friday (5)";break;
// case 6: recordOut = "Saturday (6)";break;
// case 7: recordOut = "Sunday (7)";break;
if(recordNum == 1) {
// theNum++;
// System.out.println("Iteration: " + theNum);
}
int[] output = new int[columnCount];
//Input through encoder
// System.out.println("ScalarEncoder Input = " + value);
int[] encoding = encoder.encode(value);
// System.out.println("ScalarEncoder Output = " + Arrays.toString(encoding));
int bucketIdx = encoder.getBucketIndices(value)[0];
//Input through spatial pooler
spatialPooler.compute(memory, encoding, output, true, true);
// System.out.println("SpatialPooler Output = " + Arrays.toString(output));
//Input through temporal memory
int[] input = actual = ArrayUtils.where(output, ArrayUtils.WHERE_1);
ComputeCycle cc = temporalMemory.compute(memory, input, true);
lastPredicted = predictedColumns;
predictedColumns = getSDR(cc.predictiveCells()); //Get the active column indexes
// System.out.println("TemporalMemory Input = " + Arrays.toString(input));
// System.out.print("TemporalMemory Prediction = " + Arrays.toString(predictedColumns));
classification.put("bucketIdx", bucketIdx);
classification.put("actValue", value);
// ClassifierResult<Double> result = classifier.compute(recordNum, classification, predictedColumns, true, true);
// System.out.println(" | CLAClassifier 1 step prob = " + Arrays.toString(result.getStats(1)) + "\n");
// System.out.println("");
}
public int[] inflateSDR(int[] SDR, int len) {
int[] retVal = new int[len];
for(int i : SDR) {
retVal[i] = 1;
}
return retVal;
}
public int[] getSDR(Set<Cell> cells) {
int[] retVal = new int[cells.size()];
int i = 0;
for(Iterator<Cell> it = cells.iterator();i < retVal.length;i++) {
retVal[i] = it.next().getIndex();
retVal[i] /= cellsPerColumn; // Get the column index
}
Arrays.sort(retVal);
retVal = ArrayUtils.unique(retVal);
return retVal;
}
/**
* Returns the next predicted value.
*
* @return the SDR representing the prediction
*/
@Override
public int[] getPredicted() {
return lastPredicted;
}
/**
* Returns the actual columns in time t + 1 to compare
* with {@link #getPrediction()} which returns the prediction
* at time t for time t + 1.
* @return
*/
@Override
public int[] getActual() {
return actual;
}
/**
* Simple getter for external reset
* @return
*/
public Connections getMemory() {
return memory;
}
}
} |
package org.owasp.esapi.util;
/**
* Conversion to/from byte arrays to/from short, int, long. The assumption
* is that they byte arrays are in network byte order (i.e., big-endian
* ordered).
*
* @see org.owasp.esapi.crypto.CipherTextSerializer
* @author kevin.w.wall@gmail.com
*/
public class ByteConversionUtil {
////////// Convert from short, int, long to byte array. //////////
/**
* Returns a byte array containing 2 network byte ordered bytes representing
* the given {@code short}.
*
* @param input An {@code short} to convert to a byte array.
* @return A byte array representation of an {@code short} in network byte
* order (i.e., big-endian order).
*/
public static byte[] fromShort(short input) {
byte[] output = new byte[2];
output[0] = (byte) (input >> 8);
output[1] = (byte) input;
return output;
}
/**
* Returns a byte array containing 4 network byte-ordered bytes representing the
* given {@code int}.
*
* @param input An {@code int} to convert to a byte array.
* @return A byte array representation of an {@code int} in network byte order
* (i.e., big-endian order).
*/
public static byte[] fromInt(int input) {
byte[] output = new byte[4];
output[0] = (byte) (input >> 24);
output[1] = (byte) (input >> 16);
output[2] = (byte) (input >> 8);
output[3] = (byte) input;
return output;
}
/**
* Returns a byte array containing 8 network byte-ordered bytes representing
* the given {@code long}.
*
* @param input The {@code long} to convert to a {@code byte} array.
* @return A byte array representation of a {@code long}.
*/
public static byte[] fromLong(long input) {
byte[] output = new byte[8];
output[0] = (byte) (input >> 56);
output[1] = (byte) (input >> 48);
output[2] = (byte) (input >> 40);
output[3] = (byte) (input >> 32);
output[4] = (byte) (input >> 24);
output[5] = (byte) (input >> 16);
output[6] = (byte) (input >> 8);
output[7] = (byte) input;
return output;
}
////////// Convert from byte array to short, int, long. //////////
/**
* Converts a given byte array to an {@code short}. Bytes are expected in
* network byte
* order.
*
* @param input A network byte-ordered representation of an {@code short}.
* @return The {@code short} value represented by the input array.
*/
public static short toShort(byte[] input) {
assert input.length == 2 : "toShort(): Byte array length must be 2.";
short output = 0;
output = (short)(((input[0] & 0xff) << 8) | (input[1] & 0xff));
return output;
}
/**
* Converts a given byte array to an {@code int}. Bytes are expected in
* network byte order.
*
* @param input A network byte-ordered representation of an {@code int}.
* @return The {@code int} value represented by the input array.
*/
public static int toInt(byte[] input) {
assert input.length == 4 : "toInt(): Byte array length must be 4.";
int output = 0;
output = ((input[0] & 0xff) << 24) | ((input[1] & 0xff) << 16) |
((input[2] & 0xff) << 8) | (input[3] & 0xff);
return output;
}
/**
* Converts a given byte array to a {@code long}. Bytes are expected in
* network byte
*
* @param input A network byte-ordered representation of a {@code long}.
* @return The {@code long} value represented by the input array
*/
public static long toLong(byte[] input) {
assert input.length == 8 : "toLong(): Byte array length must be 8.";
long output = 0;
output = ((long)(input[0] & 0xff) << 56);
output |= ((long)(input[1] & 0xff) << 48);
output |= ((long)(input[2] & 0xff) << 40);
output |= ((long)(input[3] & 0xff) << 32);
output |= ((long)(input[4] & 0xff) << 24);
output |= ((long)(input[5] & 0xff) << 16);
output |= ((long)(input[6] & 0xff) << 8);
output |= (input[7] & 0xff);
return output;
}
} |
package org.parboiled.matchers.join;
import org.parboiled.Rule;
import org.parboiled.matchers.CustomDefaultLabelMatcher;
import org.parboiled.matchers.Matcher;
import org.parboiled.matchervisitors.MatcherVisitor;
public abstract class JoinMatcher
extends CustomDefaultLabelMatcher<JoinMatcher>
{
private static final int JOINED_CHILD_INDEX = 0;
private static final int JOINING_CHILD_INDEX = 1;
protected final Matcher joined;
protected final Matcher joining;
protected JoinMatcher(final Rule joined, final Rule joining)
{
super(new Rule[] { joined, joining }, "Join");
this.joined = getChildren().get(JOINED_CHILD_INDEX);
this.joining = getChildren().get(JOINING_CHILD_INDEX);
}
public final Matcher getJoined()
{
return joined;
}
public final Matcher getJoining()
{
return joining;
}
/**
* Accepts the given matcher visitor.
*
* @param visitor the visitor
* @return the value returned by the given visitor
*/
@Override
public <R> R accept(final MatcherVisitor<R> visitor)
{
return null;
}
} |
package org.purl.wf4ever.robundle.fs;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchEvent.Modifier;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Iterator;
public class BundlePath implements Path {
private final BundleFileSystem fs;
private final Path zipPath;
protected BundlePath(BundleFileSystem fs, Path zipPath) {
if (fs == null || zipPath == null) {
throw new NullPointerException();
}
this.fs = fs;
this.zipPath = zipPath;
}
public int compareTo(Path other) {
return zipPath.compareTo(fs.unwrap(other));
}
public boolean endsWith(Path other) {
return zipPath.endsWith(fs.unwrap(other));
}
public boolean endsWith(String other) {
return zipPath.endsWith(other);
}
public boolean equals(Object other) {
if (!(other instanceof BundlePath)) {
return false;
}
BundlePath bundlePath = (BundlePath) other;
return zipPath.equals(fs.unwrap(bundlePath));
}
public BundlePath getFileName() {
return fs.wrap(zipPath.getFileName());
}
@Override
public BundleFileSystem getFileSystem() {
return fs;
}
public BundlePath getName(int index) {
return fs.wrap(zipPath.getName(index));
}
public int getNameCount() {
return zipPath.getNameCount();
}
public BundlePath getParent() {
return fs.wrap(zipPath.getParent());
}
public BundlePath getRoot() {
return fs.wrap(zipPath.getRoot());
}
protected Path getZipPath() {
return zipPath;
}
public int hashCode() {
return zipPath.hashCode();
}
public boolean isAbsolute() {
return zipPath.isAbsolute();
}
public Iterator<Path> iterator() {
return fs.wrapIterator(zipPath.iterator());
}
public BundlePath normalize() {
return fs.wrap(zipPath.normalize());
}
public WatchKey register(WatchService watcher, Kind<?>... events)
throws IOException {
throw new UnsupportedOperationException();
}
public WatchKey register(WatchService watcher, Kind<?>[] events,
Modifier... modifiers) throws IOException {
throw new UnsupportedOperationException();
}
public BundlePath relativize(Path other) {
return fs.wrap(zipPath.relativize(fs.unwrap(other)));
}
public BundlePath resolve(Path other) {
return fs.wrap(zipPath.resolve(fs.unwrap(other)));
}
public BundlePath resolve(String other) {
return fs.wrap(zipPath.resolve(other));
}
public BundlePath resolveSibling(Path other) {
return fs.wrap(zipPath.resolveSibling(fs.unwrap(other)));
}
public BundlePath resolveSibling(String other) {
return fs.wrap(zipPath.resolveSibling(other));
}
public boolean startsWith(Path other) {
return zipPath.startsWith(fs.unwrap(other));
}
public boolean startsWith(String other) {
return zipPath.startsWith(other);
}
public BundlePath subpath(int beginIndex, int endIndex) {
return fs.wrap(zipPath.subpath(beginIndex, endIndex));
}
public BundlePath toAbsolutePath() {
return fs.wrap(zipPath.toAbsolutePath());
}
public File toFile() {
throw new UnsupportedOperationException();
}
public BundlePath toRealPath(LinkOption... options) throws IOException {
return fs.wrap(zipPath.toRealPath(options));
}
public String toString() {
return zipPath.toString();
}
public URI toUri() {
Path abs = zipPath.toAbsolutePath();
String path = abs.toString();
return fs.getBaseURI().resolve(path);
}
} |
package org.rmatil.sync.network.core;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import net.tomp2p.connection.*;
import net.tomp2p.dht.PeerBuilderDHT;
import net.tomp2p.dht.PeerDHT;
import net.tomp2p.dht.StorageLayer;
import net.tomp2p.futures.BaseFuture;
import net.tomp2p.futures.FutureBootstrap;
import net.tomp2p.futures.FutureDirect;
import net.tomp2p.futures.FutureDiscover;
import net.tomp2p.p2p.PeerBuilder;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.PeerAddress;
import org.rmatil.sync.network.core.exception.ConnectionException;
import org.rmatil.sync.network.core.exception.ConnectionFailedException;
import org.rmatil.sync.network.core.messaging.EncryptedDataReplyHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
/**
* Use this class to open resp. close connections between
* peers.
*/
public class Connection {
private static final Logger logger = LoggerFactory.getLogger(Connection.class);
public static final int MAX_CONCURRENT_CONNECTIONS = 80;
/**
* The lowes port which could be used, if available.
* Note, that ports below this threshold are reserved
* for privileged services.
*/
public static final int MIN_PORT_NUMBER = 1024;
/**
* The highest port which could be used, if available.
* (unsigned 16-bit integer: 2^16)
*/
public static final int MAX_PORT_NUMBER = 65535;
protected PeerDHT peerDHT;
protected ConnectionConfiguration config;
protected EncryptedDataReplyHandler encryptedDataReplyHandler;
public static boolean isPortAvailable(int port) {
if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
throw new IllegalArgumentException("Invalid port number " + port + ". Port must be between " + MIN_PORT_NUMBER + " and " + MAX_PORT_NUMBER);
}
ServerSocket serverSocket = null;
DatagramSocket datagramSocket = null;
try {
serverSocket = new ServerSocket(port);
serverSocket.setReuseAddress(true);
datagramSocket = new DatagramSocket(port);
datagramSocket.setReuseAddress(true);
return true;
} catch (IOException e) {
// port is already in use
} finally {
if (datagramSocket != null) {
datagramSocket.close();
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// if an error occurred during closing the socket again...
}
}
}
return false;
}
public static int getNextFreePort(int port) {
try {
port++;
while (! Connection.isPortAvailable(port)) {
port++;
}
} catch (IllegalArgumentException e) {
throw new ConnectionException("No free port is available");
}
return port;
}
/**
* @param config The connection configuration
* @param encryptedDataReplyHandler The object data reply handler which is attached to the peer when opening the connection
*/
public Connection(ConnectionConfiguration config, EncryptedDataReplyHandler encryptedDataReplyHandler) {
this.config = config;
this.encryptedDataReplyHandler = encryptedDataReplyHandler;
}
/**
* Open a new connection, i.e. initialising a new node using
* the given keypair for domain protected values.
*
* @param keyPair The keypair to use for domain protected values. Note that this must be the same for all clients of the same user
*
* @throws ConnectionException If no free port could have been allocated to start this node or another error occurred during start up
* @throws InvalidKeyException If the given keypair does not have a RSA public and private key
*/
public void open(KeyPair keyPair)
throws ConnectionException, InvalidKeyException {
if (null == keyPair || null == keyPair.getPrivate() || null == keyPair.getPublic()) {
throw new InvalidKeyException("A RSA KeyPair must be provided");
}
if (! (keyPair.getPublic() instanceof RSAPublicKey)) {
throw new InvalidKeyException("The public key must be a RSA public key");
}
if (! (keyPair.getPrivate() instanceof RSAPrivateKey)) {
throw new InvalidKeyException("The private key must be a RSA private key");
}
int port = this.config.getPort();
if (! Connection.isPortAvailable(port)) {
logger.debug("Provided port " + port + " is already in use. Looking for the next free one");
// this throws a ConnectionException, if no port is available
port = Connection.getNextFreePort(port);
}
logger.debug("Setting node up at free port " + port);
Bindings bindings = new Bindings().listenAny();
ChannelServerConfiguration serverConfiguration = PeerBuilder.createDefaultChannelServerConfiguration();
serverConfiguration.signatureFactory(new RSASignatureFactory());
serverConfiguration.pipelineFilter(new PeerBuilder.EventExecutorGroupFilter(new DefaultEventExecutorGroup(MAX_CONCURRENT_CONNECTIONS)));
serverConfiguration.ports(new Ports(port, port));
ChannelClientConfiguration clientConfiguration = PeerBuilder.createDefaultChannelClientConfiguration();
clientConfiguration.signatureFactory(new RSASignatureFactory());
clientConfiguration.pipelineFilter(new PeerBuilder.EventExecutorGroupFilter(new DefaultEventExecutorGroup(MAX_CONCURRENT_CONNECTIONS)));
PeerBuilder peerBuilder = new PeerBuilder(Number160.createHash(this.config.getNodeId()))
.ports(port)
.keyPair(keyPair) // note, that this enables signing of messages by default: @see Message#isSign()
.bindings(bindings)
.channelServerConfiguration(serverConfiguration)
.channelClientConfiguration(clientConfiguration);
try {
this.peerDHT = new PeerBuilderDHT(peerBuilder.start()).start();
} catch (IOException e) {
this.close();
throw new ConnectionException("Failed to start peer", e);
}
if (this.config.isFirewalled()) {
PeerAddress peerAddress = this.peerDHT
.peerAddress()
.changeFirewalledTCP(true)
.changeFirewalledUDP(true);
peerDHT.peer().peerBean().serverPeerAddress(peerAddress);
}
// TODO: 1. join network without public key
// TODO: 2. fetch public key, private key, salt
// TODO: 3. generate secret key for user with salt and pw
// TODO: 4. add secret key to user
// TODO: 5. decrypt private key with secret key from user
// TODO: 6. set public-private keypair in the DHT
if (null != this.encryptedDataReplyHandler) {
logger.info("Setting ObjectDataReplyHandler " + this.encryptedDataReplyHandler.getClass().getName());
this.peerDHT.peer().objectDataReply(this.encryptedDataReplyHandler);
}
// set storage layer protection
this.peerDHT.storageLayer().protection(
StorageLayer.ProtectionEnable.ALL,
StorageLayer.ProtectionMode.NO_MASTER,
StorageLayer.ProtectionEnable.ALL,
StorageLayer.ProtectionMode.NO_MASTER
);
}
public void connect(String bootstrapIpAddress, int bootstrapPort)
throws ConnectionFailedException, IllegalStateException {
if (null == this.peerDHT) {
throw new IllegalStateException("Open the connection first");
}
logger.info("Trying to connect to " +
bootstrapIpAddress +
":" +
bootstrapPort
);
InetAddress address;
try {
address = InetAddress.getByName(bootstrapIpAddress);
} catch (UnknownHostException e) {
this.close();
throw new ConnectionFailedException("Could not get inet address for provided bootstrap address", e);
}
FutureDiscover futureDiscover = this.peerDHT
.peer()
.discover()
.discoverTimeoutSec((int) Math.ceil(this.config.getPeerDiscoveryTimeout() / 1000L))
.inetAddress(address)
.ports(bootstrapPort)
.start();
futureDiscover.awaitUninterruptibly();
if (futureDiscover.isFailed()) {
if (this.config.isFirewalled) {
// TODO: implement UPnP
}
this.close();
throw new ConnectionFailedException("Can not discover other peer at " +
bootstrapIpAddress +
":" +
bootstrapPort +
": " +
futureDiscover.failedReason()
);
}
logger.debug("Peer discovery was successful");
FutureBootstrap futureBootstrap = this.peerDHT
.peer()
.bootstrap()
.inetAddress(address)
.ports(bootstrapPort)
.start();
futureBootstrap.awaitUninterruptibly(this.config.getPeerBootstrapTimeout());
if (futureBootstrap.isFailed()) {
this.close();
throw new ConnectionFailedException("Can not bootstrap to other peer at " +
bootstrapIpAddress +
":" +
bootstrapPort +
": " +
futureBootstrap.failedReason()
);
}
logger.debug("Bootstrap succeeded");
}
/**
* Send the given data to the specified receiver
*
* @param receiverAddress The address to which to send the data
* @param dataToSend The data to send
*
* @return The future
*/
public FutureDirect sendDirect(PeerAddress receiverAddress, Object dataToSend) {
return this.peerDHT
.peer()
.sendDirect(receiverAddress)
.object(dataToSend)
.start();
}
/**
* Close the connection of this peer in means of a friendly (i.e. announced)
* shutdown.
*
* @throws ConnectionException If waiting for shutdown timed out
*/
public void close()
throws ConnectionException {
if (null == this.peerDHT) {
logger.trace("Can not shutdown peer: PeerDHT was not initialized yet");
return;
}
if (this.peerDHT.peer().isShutdown()) {
logger.trace("Can not shutdown peer: PeerDHT is already shut down");
return;
}
// notify the shutdown to next neighbours
boolean announceSuccessful = this.peerDHT.peer()
.announceShutdown()
.start()
.awaitUninterruptibly(this.config.getShutdownAnnounceTimeout());
if (! announceSuccessful) {
logger.debug("Shutdown announce was not yet completed. Shutting node down now");
}
BaseFuture shutdownFuture = this.peerDHT.shutdown();
if (shutdownFuture.isFailed()) {
throw new ConnectionException("Failed to shut down node: " + shutdownFuture.failedReason());
}
logger.trace("Shutdown of peer succeeded");
}
/**
* Returns true, if this connection is closed, i.e. no peer is started.
*
* @return True, if closed, false otherwise
*/
public boolean isClosed() {
// returns true, if no peer dht is specified or already shutdown
return (null != this.peerDHT && this.peerDHT.peer().isShutdown()) || null == this.peerDHT;
}
/**
* Returns the peer DHT backed by this connection
*
* @return The peer dht
*/
public PeerDHT getPeerDHT() {
return peerDHT;
}
} |
package org.robolectric.util;
import android.app.Activity;
import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.view.View;
import android.view.Window;
import org.robolectric.RoboInstrumentation;
import org.robolectric.Robolectric;
import org.robolectric.shadows.ShadowActivity;
import org.robolectric.shadows.ShadowActivityThread;
import org.robolectric.shadows.ShadowLooper;
import static org.fest.reflect.core.Reflection.constructor;
import static org.fest.reflect.core.Reflection.field;
import static org.fest.reflect.core.Reflection.method;
import static org.fest.reflect.core.Reflection.type;
import static org.robolectric.Robolectric.shadowOf_;
@SuppressWarnings("UnusedDeclaration")
public class ActivityController<T extends Activity> {
private final T activity;
private final ShadowActivity shadowActivity;
private final ShadowLooper shadowMainLooper;
private Application application;
private Context baseContext;
private Intent intent;
private boolean attached;
public static <T extends Activity> ActivityController<T> of(Class<T> activityClass) {
return new ActivityController<T>(activityClass);
}
public static <T extends Activity> ActivityController<T> of(T activity) {
return new ActivityController<T>(activity);
}
public ActivityController(Class<T> activityClass) {
this.activity = constructor().in(activityClass).newInstance();
shadowActivity = shadowOf_(activity);
shadowMainLooper = shadowOf_(Looper.getMainLooper());
}
public ActivityController(T activity) {
this.activity = activity;
shadowActivity = shadowOf_(activity);
shadowMainLooper = shadowOf_(Looper.getMainLooper());
attached = true;
}
public T get() {
return activity;
}
public ActivityController<T> withApplication(Application application) {
this.application = application;
return this;
}
public ActivityController<T> withBaseContext(Context baseContext) {
this.baseContext = baseContext;
return this;
}
public ActivityController<T> withIntent(Intent intent) {
this.intent = intent;
return this;
}
public ActivityController<T> attach() {
Application application = this.application == null ? Robolectric.application : this.application;
Context baseContext = this.baseContext == null ? application : this.baseContext;
Intent intent = this.intent == null ? new Intent(application, activity.getClass()) : this.intent;
ActivityInfo activityInfo = new ActivityInfo();
ClassLoader cl = baseContext.getClassLoader();
Class<?> activityThreadClass = type(ShadowActivityThread.CLASS_NAME).withClassLoader(cl).load();
Class<?> nonConfigurationInstancesClass = type("android.app.Activity$NonConfigurationInstances")
.withClassLoader(cl).load();
method("attach").withParameterTypes(
Context.class /* context */, activityThreadClass /* aThread */,
Instrumentation.class /* instr */, IBinder.class /* token */, int.class /* ident */,
Application.class /* application */, Intent.class /* intent */, ActivityInfo.class /* info */,
CharSequence.class /* title */, Activity.class /* parent */, String.class /* id */,
nonConfigurationInstancesClass /* lastNonConfigurationInstances */,
Configuration.class /* config */
).in(activity).invoke(baseContext, null /* aThread */,
new RoboInstrumentation(), null /* token */, 0 /* ident */,
application, intent /* intent */, activityInfo,
"title", null /* parent */, "id",
null /* lastNonConfigurationInstances */,
application.getResources().getConfiguration());
shadowActivity.setThemeFromManifest();
attached = true;
return this;
}
public ActivityController<T> create(final Bundle bundle) {
shadowMainLooper.runPaused(new Runnable() {
@Override
public void run() {
if (!attached) attach();
method("performCreate").withParameterTypes(Bundle.class).in(activity).invoke(bundle);
}
});
return this;
}
public ActivityController<T> create() {
return create(null);
}
public ActivityController<T> restoreInstanceState(Bundle bundle) {
method("performRestoreInstanceState").withParameterTypes(Bundle.class).in(activity).invoke(bundle);
return this;
}
public ActivityController<T> postCreate(final Bundle bundle) {
shadowMainLooper.runPaused(new Runnable() {
@Override
public void run() {
shadowActivity.callOnPostCreate(bundle);
}
});
return this;
}
public ActivityController<T> start() {
invokeWhilePaused("performStart");
return this;
}
public ActivityController<T> restart() {
invokeWhilePaused("performRestart");
return this;
}
public ActivityController<T> resume() {
invokeWhilePaused("performResume");
return this;
}
public ActivityController<T> postResume() {
shadowMainLooper.runPaused(new Runnable() {
@Override
public void run() {
shadowActivity.callOnPostResume();
}
});
return this;
}
public ActivityController<T> newIntent(final android.content.Intent intent) {
shadowMainLooper.runPaused(new Runnable() {
@Override
public void run() {
shadowActivity.callOnNewIntent(intent);
}
});
return this;
}
public ActivityController<T> saveInstanceState(android.os.Bundle outState) {
method("performSaveInstanceState").withParameterTypes(Bundle.class).in(activity).invoke(outState);
return this;
}
public ActivityController<T> visible() {
shadowMainLooper.runPaused(new Runnable() {
@Override
public void run() {
field("mDecor").ofType(View.class).in(activity).set(activity.getWindow().getDecorView());
method("makeVisible").in(activity).invoke();
}
});
return this;
}
public ActivityController<T> pause() {
invokeWhilePaused("performPause");
return this;
}
public ActivityController<T> userLeaving() {
invokeWhilePaused("performUserLeaving");
return this;
}
public ActivityController<T> stop() {
invokeWhilePaused("performStop");
return this;
}
public ActivityController<T> destroy() {
invokeWhilePaused("performDestroy");
return this;
}
private ActivityController<T> invokeWhilePaused(final String performStart) {
shadowMainLooper.runPaused(new Runnable() {
@Override public void run() {
method(performStart).in(activity).invoke();
}
});
return this;
}
} |
package pitt.search.semanticvectors;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.TreeSet;
import java.util.logging.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.AtomicReader;
import org.apache.lucene.index.BaseCompositeReader;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.DocsEnum;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import pitt.search.semanticvectors.utils.StringUtils;
import pitt.search.semanticvectors.utils.VerbatimLogger;
/**
* Class to support reading extra information from Lucene indexes,
* including term frequency, doc frequency.
*/
public class LuceneUtils {
public static final Version LUCENE_VERSION = Version.LUCENE_46;
private static final Logger logger = Logger.getLogger(DocVectors.class.getCanonicalName());
private FlagConfig flagConfig;
private BaseCompositeReader<AtomicReader> compositeReader;
private AtomicReader atomicReader;
private Hashtable<Term, Float> termEntropy = new Hashtable<Term, Float>();
private Hashtable<Term, Float> termIDF = new Hashtable<>();
private TreeSet<String> stopwords = null;
private TreeSet<String> startwords = null;
/**
* Determines which term-weighting strategy to use in indexing,
* and in search if {@link FlagConfig#usetermweightsinsearch()} is set.
*
* <p>Names may be passed as command-line arguments, so underscores are avoided.
*/
public enum TermWeight {
/** No term weighting: all terms have weight 1. */
NONE,
/** Use inverse document frequency: see {@link LuceneUtils#getIDF}. */
IDF,
/** Use log entropy: see {@link LuceneUtils#getEntropy}. */
LOGENTROPY,
/** Use square root of term frequency. */
SQRT,
}
/**
* @param flagConfig Contains all information necessary for configuring LuceneUtils.
* {@link FlagConfig#luceneindexpath()} must be non-empty.
*/
public LuceneUtils(FlagConfig flagConfig) throws IOException {
if (flagConfig.luceneindexpath().isEmpty()) {
throw new IllegalArgumentException(
"-luceneindexpath is a required argument for initializing LuceneUtils instance.");
}
this.compositeReader = DirectoryReader.open(FSDirectory.open(new File(flagConfig.luceneindexpath())));
this.atomicReader = SlowCompositeReaderWrapper.wrap(compositeReader);
MultiFields.getFields(compositeReader);
this.flagConfig = flagConfig;
if (!flagConfig.stoplistfile().isEmpty())
loadStopWords(flagConfig.stoplistfile());
if (!flagConfig.startlistfile().isEmpty())
loadStartWords(flagConfig.startlistfile());
VerbatimLogger.info("Initialized LuceneUtils from Lucene index in directory: " + flagConfig.luceneindexpath() + "\n");
}
/**
* Loads the stopword file into the {@link #stopwords} data structure.
* @param stoppath Path to stopword file.
* @throws IOException If stopword file cannot be read.
*/
public void loadStopWords(String stoppath) throws IOException {
logger.info("Using stopword file: " + stoppath);
stopwords = new TreeSet<String>();
try {
BufferedReader readIn = new BufferedReader(new FileReader(stoppath));
String in = readIn.readLine();
while (in != null) {
stopwords.add(in);
in = readIn.readLine();
}
readIn.close();
}
catch (IOException e) {
throw new IOException("Couldn't open file " + stoppath);
}
}
/**
* Loads the startword file into the {@link #startwords} data structure.
* @param startpath Path to startword file
* @throws IOException If startword file cannot be read.
*/
public void loadStartWords(String startpath) throws IOException {
System.err.println("Using startword file: " + startpath);
startwords = new TreeSet<String>();
try {
BufferedReader readIn = new BufferedReader(new FileReader(startpath));
String in = readIn.readLine();
while (in != null) {
startwords.add(in);
in = readIn.readLine();
}
readIn.close();
}
catch (IOException e) {
throw new IOException("Couldn't open file "+startpath);
}
}
/**
* Returns true if term is in stoplist, false otherwise.
*/
public boolean stoplistContains(String x) {
if (stopwords == null) return false;
return stopwords.contains(x);
}
/**
* Returns false if term is not in startlist, true otherwise (including if no startlist exists).
*/
public boolean startlistContains(String x) {
if (startwords == null) return false;
return startwords.contains(x);
}
public Document getDoc(int docID) throws IOException {
return this.atomicReader.document(docID);
}
public String getExternalDocId(int docID) throws IOException {
String externalDocId;
try {
externalDocId = this.getDoc(docID).getField(flagConfig.docidfield()).stringValue();
} catch (IOException e) {
logger.severe(String.format(
"Failed to get external doc ID from doc no. %d in Lucene index." +
"\nThis is almost certain to lead to problems." +
"\nCheck that -docidfield was set correctly and exists in the Lucene index",
docID));
throw e;
}
return externalDocId;
}
/**
* Gets the terms for a given field. Throws {@link java.lang.NullPointerException} if this is null.
*/
public Terms getTermsForField(String field) throws IOException {
Terms terms = atomicReader.terms(field);
if (terms == null) {
throw new NullPointerException(String.format(
"No terms for field: '%s'.\nKnown fields are: '%s'.", field, StringUtils.join(this.getFieldNames())));
}
return atomicReader.terms(field);
}
public DocsEnum getDocsForTerm(Term term) throws IOException {
return this.atomicReader.termDocsEnum(term);
}
public Terms getTermVector(int docID, String field) throws IOException {
return this.atomicReader.getTermVector(docID, field);
}
public FieldInfos getFieldInfos() {
return this.atomicReader.getFieldInfos();
}
public List<String> getFieldNames() {
List<String> fieldNames = new ArrayList<>();
for(FieldInfo fieldName : this.atomicReader.getFieldInfos()) {
fieldNames.add(fieldName.name);
}
return fieldNames;
}
/**
* Gets the global term frequency of a term,
* i.e. how may times it occurs in the whole corpus
* @param term whose frequency you want
* @return Global term frequency of term, or 1 if unavailable.
*/
public int getGlobalTermFreq(Term term) {
int tf = 0;
try {
tf = (int) compositeReader.totalTermFreq(term);
}
catch (IOException e) {
logger.info("Couldn't get term frequency for term " + term.text());
return 1;
}
if (tf == -1) {
logger.warning("Lucene StandardDirectoryReader returned -1 for term: '"
+ term.text() + "' in field: '" + term.field() + "'. Changing to 0."
+ "\nThis may be due to a version-mismatch and might be solved by rebuilding your Lucene index.");
tf = 0;
}
return tf;
}
/**
* Gets a term weight for a string, adding frequency over occurrences
* in all contents fields.
*/
public float getGlobalTermWeightFromString(String termString) {
float freq = 0;
for (String field: flagConfig.contentsfields())
freq += getGlobalTermWeight(new Term(field, termString));
return freq;
}
/**
* Gets a global term weight for a term, depending on the setting for
* {@link FlagConfig#termweight()}.
*
* Used in indexing. Used in query weighting if
* {@link FlagConfig#usetermweightsinsearch} is true.
*
* @param term whose frequency you want
* @return Global term weight, or 1 if unavailable.
*/
public float getGlobalTermWeight(Term term) {
switch (flagConfig.termweight()) {
case NONE:
case SQRT:
return 1;
case IDF:
return getIDF(term);
case LOGENTROPY:
return getEntropy(term);
}
VerbatimLogger.severe("Unrecognized termweight option: " + flagConfig.termweight()
+ ". Returning 1.\n");
return 1;
}
/**
* Gets a local term weight for a term based on its document frequency, depending on the setting for
* {@link FlagConfig#termweight()}.
*
* Used in indexing.
*
* @param docfreq the frequency of the term concerned in the document of interest
* @return Local term weight
*/
public float getLocalTermWeight(int docfreq) {
switch (flagConfig.termweight()) {
case NONE:
return 1;
case IDF:
return docfreq;
case LOGENTROPY:
return (float) Math.log10(1+docfreq);
case SQRT:
return (float) Math.sqrt(docfreq);
}
VerbatimLogger.severe("Unrecognized termweight option: " + flagConfig.termweight()
+ ". Returning 1.");
return 1;
}
/**
* Returns the number of documents in the Lucene index.
*/
public int getNumDocs() { return compositeReader.numDocs(); }
/**
* Gets the IDF (i.e. log10(numdocs/doc frequency)) of a term
* @param term the term whose IDF you would like
*/
private float getIDF(Term term) {
if (termIDF.containsKey(term)) {
return termIDF.get(term);
} else {
try {
int freq = compositeReader.docFreq(term);
if (freq == 0) {
return 0;
}
float idf = (float) Math.log10(compositeReader.numDocs()/freq);
termIDF.put(term, idf);
return idf;
} catch (IOException e) {
// Catches IOException from looking up doc frequency, never seen yet in practice.
e.printStackTrace();
return 1;
}
}
}
/**
* Gets the 1 - entropy (i.e. 1+ plogp) of a term,
* a function that favors terms that are focally distributed
* We use the definition of log-entropy weighting provided in
* Martin and Berry (2007):
* Entropy = 1 + sum ((Pij log2(Pij)) / log2(n))
* where Pij = frequency of term i in doc j / global frequency of term i
* n = number of documents in collection
* @param term whose entropy you want
* Thanks to Vidya Vasuki for adding the hash table to
* eliminate redundant calculation
*/
private float getEntropy(Term term){
if(termEntropy.containsKey(term))
return termEntropy.get(term);
int gf = getGlobalTermFreq(term);
double entropy = 0;
try {
DocsEnum docsEnum = this.getDocsForTerm(term);
while((docsEnum.nextDoc()) != DocsEnum.NO_MORE_DOCS) {
double p = docsEnum.freq(); //frequency in this document
p = p / gf; //frequency across all documents
entropy += p * (Math.log(p) / Math.log(2)); //sum of Plog(P)
}
int n= this.getNumDocs();
double log2n = Math.log(n)/Math.log(2);
entropy = entropy/log2n;
}
catch (IOException e) {
logger.info("Couldn't get term entropy for term " + term.text());
}
termEntropy.put(term, 1 + (float)entropy);
return (float) (1 + entropy);
}
/**
* Public version of {@link #termFilter} that gets all its inputs from the
* {@link #flagConfig} and the provided term.
*
* External callers should normally use this method, so that new filters are
* available through different codepaths provided they pass a {@code FlagConfig}.
*
* @param term Term to be filtered in or out, depending on Lucene index and flag configs.
*/
public boolean termFilter(Term term) {
return termFilter(term, flagConfig.contentsfields(),
flagConfig.minfrequency(), flagConfig.maxfrequency(),
flagConfig.maxnonalphabetchars(), flagConfig.filteroutnumbers(),
flagConfig.mintermlength());
}
/**
* Filters out non-alphabetic terms and those of low frequency.
*
* Thanks to Vidya Vasuki for refactoring and bug repair
*
* @param term Term to be filtered.
* @param desiredFields Terms in only these fields are filtered in
* @param minFreq minimum term frequency accepted
* @param maxFreq maximum term frequency accepted
* @param maxNonAlphabet reject terms with more than this number of non-alphabetic characters
*/
protected boolean termFilter(
Term term, String[] desiredFields, int minFreq, int maxFreq, int maxNonAlphabet, int minTermLength) {
// Field filter.
boolean isDesiredField = false;
for (int i = 0; i < desiredFields.length; ++i) {
if (term.field().compareToIgnoreCase(desiredFields[i]) == 0) {
isDesiredField = true;
}
}
// Stoplist (if active)
if (stoplistContains(term.text()))
return false;
// Startlist (if active)
if (startlistContains(term.text()))
return true;
if (!isDesiredField) {
return false;
}
// Character filter.
if (maxNonAlphabet != -1) {
int nonLetter = 0;
String termText = term.text();
//Must meet minimum term length requirement
if (termText.length() < minTermLength) return false;
for (int i = 0; i < termText.length(); ++i) {
if (!Character.isLetter(termText.charAt(i)))
nonLetter++;
if (nonLetter > maxNonAlphabet)
return false;
}
}
// Frequency filter.
int termfreq = getGlobalTermFreq(term);
if (termfreq < minFreq | termfreq > maxFreq) {
return false;
}
// If we've passed each filter, return true.
return true;
}
/**
* Applies termFilter and additionally (if requested) filters out digit-only words.
*
* @param term Term to be filtered.
* @param desiredFields Terms in only these fields are filtered in
* @param minFreq minimum term frequency accepted
* @param maxFreq maximum term frequency accepted
* @param maxNonAlphabet reject terms with more than this number of non-alphabetic characters
* @param filterNumbers if true, filters out tokens that represent a number
*/
private boolean termFilter(
Term term, String[] desiredFields, int minFreq, int maxFreq,
int maxNonAlphabet, boolean filterNumbers, int minTermLength) {
// number filter
if (filterNumbers) {
try {
// if the token can be parsed as a floating point number, no exception is thrown and false is returned
// if not, an exception is thrown and we continue with the other termFilter method.
// remark: this does not filter out e.g. Java or C++ formatted numbers like "1f" or "1.0d"
Double.parseDouble( term.text() );
return false;
} catch (Exception e) {}
}
return termFilter(term, desiredFields, minFreq, maxFreq, maxNonAlphabet, minTermLength);
}
/**
* TODO(dwiddows): Check that no longer needed in Lucene 4.x and above.
*
* Static method for compressing an index.
*
* This small preprocessing step makes sure that the Lucene index
* is optimized to use contiguous integers as identifiers.
* Otherwise exceptions can occur if document id's are greater
* than indexReader.numDocs().
*/
static void compressIndex(String indexDir) {
return;
}
/*
try {
IndexWriter compressor = new IndexWriter(FSDirectory.open(new File(indexDir)),
new StandardAnalyzer(Version.LUCENE_30),
false,
MaxFieldLength.UNLIMITED);
compressor.optimize();
compressor.close();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
} |
package pixlepix.auracascade.block.tile;
import cpw.mods.fml.common.network.NetworkRegistry;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.commons.lang3.StringUtils;
import pixlepix.auracascade.AuraCascade;
import pixlepix.auracascade.main.AuraUtil;
import pixlepix.auracascade.network.PacketBurst;
import java.util.List;
public class OreTile extends ConsumerTile {
public static final int COST_PER_SMELT = 2000;
int heat = 0;
public void readCustomNBT(NBTTagCompound nbt) {
super.readCustomNBT(nbt);
heat = nbt.getInteger("heat");
}
public void writeCustomNBT(NBTTagCompound nbt) {
super.writeCustomNBT(nbt);
nbt.setInteger("heat", heat);
}
@Override
public void updateEntity() {
super.updateEntity();
if (!worldObj.isRemote) {
if (worldObj.getTotalWorldTime() % 2400 == 0) {
AuraUtil.keepAlive(this, 3);
}
heat += (storedPower);
storedPower = 0;
if (heat >= COST_PER_SMELT) {
heat = 0;
int range = 3;
List<EntityItem> nearbyItems = worldObj.getEntitiesWithinAABB(EntityItem.class, AxisAlignedBB.getBoundingBox(xCoord - range, yCoord - range, zCoord - range, xCoord + range, yCoord + range, zCoord + range));
for (EntityItem entityItem : nearbyItems) {
ItemStack stack = entityItem.getEntityItem();
if (getTripleResult(stack) != null) {
ItemStack dustStack = getTripleResult(stack);
dustStack.stackSize = 3;
//Kill the stack
if (stack.stackSize == 0) {
entityItem.setDead();
} else {
stack.stackSize
}
EntityItem newEntity = new EntityItem(worldObj, entityItem.posX, entityItem.posY, entityItem.posZ, dustStack);
newEntity.delayBeforeCanPickup = entityItem.delayBeforeCanPickup;
newEntity.motionX = entityItem.motionX;
newEntity.motionY = entityItem.motionY;
newEntity.motionZ = entityItem.motionZ;
worldObj.spawnEntityInWorld(newEntity);
AuraCascade.proxy.networkWrapper.sendToAllAround(new PacketBurst(1, newEntity.posX, newEntity.posY, newEntity.posZ), new NetworkRegistry.TargetPoint(worldObj.provider.dimensionId, xCoord, yCoord, zCoord, 32));
break;
}
}
}
}
}
public static ItemStack getTripleResult(ItemStack stack){
int[] oreIds = OreDictionary.getOreIDs(stack);
for(int id:oreIds){
String oreName = OreDictionary.getOreName(id);
if(StringUtils.startsWith(oreName, "ore")){
String dustName = StringUtils.replace(oreName, "ore", "dust");
return OreDictionary.getOres(dustName).get(0);
}
}
return null;
}
} |
package rst.pdfbox.layout.text;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import rst.pdfbox.layout.elements.Dividable.Divided;
import rst.pdfbox.layout.elements.Paragraph;
/**
* Utility methods for dealing with text sequences.
*/
public class TextSequenceUtil {
/**
* Dissects the given sequence into {@link TextLine}s.
*
* @param text
* the text to extract the lines from.
* @return the list of text lines.
* @throws IOException
* by pdfbox
*/
public static List<TextLine> getLines(final TextSequence text)
throws IOException {
final List<TextLine> result = new ArrayList<TextLine>();
TextLine line = new TextLine();
for (TextFragment fragment : text) {
if (fragment instanceof NewLine) {
line.setNewLine((NewLine) fragment);
result.add(line);
line = new TextLine();
} else {
line.add((StyledText) fragment);
}
}
if (!line.isEmpty()) {
result.add(line);
}
return result;
}
/**
* Word-wraps and divides the given text sequence.
*
* @param text
* the text to divide.
* @param maxWidth
* the max width used for word-wrapping.
* @param maxHeight
* the max height for divide.
* @return the Divided element containing the parts.
* @throws IOException
* by pdfbox
*/
public static Divided divide(final TextSequence text, final float maxWidth,
final float maxHeight) throws IOException {
TextFlow wrapped = wordWrap(text, maxWidth);
List<TextLine> lines = getLines(wrapped);
Paragraph first = new Paragraph();
Paragraph tail = new Paragraph();
if (text instanceof TextFlow) {
TextFlow flow = (TextFlow) text;
first.setMaxWidth(flow.getMaxWidth());
first.setLineSpacing(flow.getLineSpacing());
tail.setMaxWidth(flow.getMaxWidth());
tail.setLineSpacing(flow.getLineSpacing());
}
int index = 0;
do {
TextLine line = lines.get(index);
first.add(line);
++index;
} while (index < lines.size() && first.getHeight() < maxHeight);
if (first.getHeight() > maxHeight) {
// remove last line
--index;
TextLine line = lines.get(index);
for (@SuppressWarnings("unused")
TextFragment textFragment : line) {
first.removeLast();
}
}
for (int i = index; i < lines.size(); ++i) {
tail.add(lines.get(i));
}
return new Divided(first, tail);
}
/**
* Word-wraps the given text sequence in order to fit the max width.
*
* @param text
* the text to word-wrap.
* @param maxWidth
* the max width to fit.
* @return the word-wrapped text.
* @throws IOException
* by pdfbox
*/
public static TextFlow wordWrap(final TextSequence text,
final float maxWidth) throws IOException {
TextFlow result = new TextFlow();
float lineLength = 0;
for (TextFragment fragment : text) {
if (fragment instanceof NewLine) {
result.add(fragment);
lineLength = 0;
} else {
TextFlow words = splitWords(fragment);
for (TextFragment word : words) {
FontDescriptor fontDescriptor = word.getFontDescriptor();
float length = fontDescriptor.getSize()
* fontDescriptor.getFont().getStringWidth(
word.getText()) / 1000;
float extraSpace = 0;
if (lineLength > 0 && word.getText().length() > 0) {
// not the first word in line, so separate by blank
extraSpace = fontDescriptor.getSize()
* fontDescriptor.getFont().getSpaceWidth()
/ 1000;
}
if (maxWidth > 0 && lineLength > 0
&& lineLength + length + extraSpace > maxWidth) {
// word exceeds max width, so create new line
result.add(new WrappingNewLine(fontDescriptor));
lineLength = 0;
}
if (lineLength == 0) {
String newText = word.getText();
while (newText.startsWith(" ")) {
// skip leading blanks at begin of line
newText = newText.substring(1);
}
if (newText != word.getText()) {
// text has changed, blanks have been skipped
word = new StyledText(newText,
word.getFontDescriptor());
}
}
result.add(word);
lineLength += length + extraSpace;
}
}
}
return result;
}
/**
* Convencience function that {@link #wordWrap(TextSequence, float)
* word-wraps} into {@link #getLines(TextSequence)}.
*
* @param text
* the text to word-wrap.
* @param maxWidth
* the max width to fit.
* @return the word-wrapped text lines.
* @throws IOException
* by pdfbox
*/
public static List<TextLine> wordWrapToLines(final TextSequence text,
final float maxWidth) throws IOException {
TextFlow wrapped = wordWrap(text, maxWidth);
List<TextLine> lines = getLines(wrapped);
return lines;
}
/**
* Splits the fragment into words.
*
* @param text
* the text to split.
* @return the words as a text flow.
*/
public static TextFlow splitWords(final TextFragment text) {
TextFlow result = new TextFlow();
if (text instanceof NewLine) {
result.add(text);
} else {
String[] words = text.getText().split(" ", -1);
boolean firstWord = true;
for (String word : words) {
String newWord = word;
if (!firstWord) {
newWord = " " + newWord;
}
result.add(new StyledText(newWord, text.getFontDescriptor()));
firstWord = false;
}
}
return result;
}
/**
* Draws the given text sequence to the PDPageContentStream at the given
* position.
*
* @param text
* the text to draw.
* @param contentStream
* the stream to draw to
* @param upperLeft
* the position of the start of the first line.
* @param alignment
* how to align the text lines.
* @param maxWidth
* if > 0, the text may be word-wrapped to match the width.
* @param lineSpacing
* the line spacing factor.
* @throws IOException
* by pdfbox
*/
public static void drawText(TextSequence text,
PDPageContentStream contentStream, Position upperLeft,
Alignment alignment, float maxWidth, final float lineSpacing)
throws IOException {
List<TextLine> lines = wordWrapToLines(text, maxWidth);
float targetWidth = getMaxWidth(lines);
Position position = upperLeft;
float lastLineHeight = 0;
for (int i = 0; i < lines.size(); i++) {
TextLine textLine = lines.get(i);
float currentLineHeight = textLine.getHeight();
float lead = lastLineHeight
+ (currentLineHeight * (lineSpacing - 1));
lastLineHeight = currentLineHeight;
position = position.add(0, -lead);
float offset = getOffset(textLine, targetWidth, alignment);
position = new Position(upperLeft.getX() + offset, position.getY());
textLine.drawText(contentStream, position, alignment);
}
}
/**
* Gets the (left) offset of the line with respect to the target width and
* alignment.
*
* @param textLine
* the text
* @param targetWidth
* the target width
* @param alignment
* the alignment of the line.
* @return the left offset.
* @throws IOException
* by pdfbox
*/
public static float getOffset(final TextSequence textLine,
final float targetWidth, final Alignment alignment)
throws IOException {
switch (alignment) {
case Right:
return targetWidth - textLine.getWidth();
case Center:
return (targetWidth - textLine.getWidth()) / 2f;
default:
return 0;
}
}
/**
* Calculates the max width of all text lines.
*
* @param lines
* the lines for which to calculate the max width.
* @return the max width of the lines.
* @throws IOException
* by pdfbox.
*/
public static float getMaxWidth(final Iterable<TextLine> lines)
throws IOException {
float max = 0;
for (TextLine line : lines) {
max = Math.max(max, line.getWidth());
}
return max;
}
/**
* Calculates the width of the text
*
* @param textSequence
* the text.
* @param maxWidth
* if > 0, the text may be word-wrapped to match the width.
* @return the width of the text.
* @throws IOException
* by pdfbox.
*/
public static float getWidth(final TextSequence textSequence,
final float maxWidth) throws IOException {
List<TextLine> lines = wordWrapToLines(textSequence, maxWidth);
float max = 0;
for (TextLine line : lines) {
max = Math.max(max, line.getWidth());
}
return max;
}
/**
* Calculates the height of the text
*
* @param textSequence
* the text.
* @param maxWidth
* if > 0, the text may be word-wrapped to match the width.
* @param lineSpacing
* the line spacing factor.
* @return the height of the text.
* @throws IOException
* by pdfbox
*/
public static float getHeight(final TextSequence textSequence,
final float maxWidth, final float lineSpacing) throws IOException {
List<TextLine> lines = wordWrapToLines(textSequence, maxWidth);
float sum = 0;
for (int i = 0; i < lines.size(); i++) {
TextLine line = lines.get(i);
float lineHeight = line.getHeight() * lineSpacing;
sum += lineHeight;
}
return sum;
}
} |
package gov.nih.nci.calab.domain;
import java.util.Collection;
import java.util.HashSet;
public class InstrumentType {
private static final long serialVersionUID = 1234567890L;
private Long id;
private String name;
private String description;
private String abbreviation;
private Collection<Manufacturer> manufacturerCollection = new HashSet<Manufacturer>();
public InstrumentType() {
super();
// TODO Auto-generated constructor stub
}
public String getAbbreviation() {
return abbreviation;
}
public void setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Manufacturer> getManufacturerCollection() {
return manufacturerCollection;
}
public void setManufacturerCollection(
Collection<Manufacturer> manufacturerCollection) {
this.manufacturerCollection = manufacturerCollection;
}
} |
package seedu.address.logic.commands;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.person.*;
import seedu.address.model.tag.Tag;
import seedu.address.model.tag.UniqueTagList;
import java.util.HashSet;
import java.util.Set;
/**
* Adds a task to the task manager.
*/
public class AddCommand extends Command {
public static final String COMMAND_WORD = "add";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a task to the task manager. "
+ "Parameters: \"TASK_DESCRIPTION\" [on DATE] [by DEADLINE_TIME] [from START_TIME] [to END_TIME] [#TAGS]...\n"
+ "Example: " + COMMAND_WORD
+ " add \"CS2103T Lecture\" on 7 Oct 2016 from 2pm to 4pm #Important";
public static final String MESSAGE_SUCCESS = "New person added: %1$s";
public static final String MESSAGE_DUPLICATE_PERSON = "This person already exists in the address book";
private final Person toAdd;
public AddCommand(String name, String phone, String email, String address, Set<String> tags)
throws IllegalValueException {
final Set<Tag> tagSet = new HashSet<>();
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
}
this.toAdd = new Person(
new Name(name),
new Phone(phone),
new Email(email),
new Address(address),
new UniqueTagList(tagSet)
);
}
@Override
public CommandResult execute() {
assert model != null;
try {
model.addPerson(toAdd);
return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd));
} catch (UniquePersonList.DuplicatePersonException e) {
return new CommandResult(MESSAGE_DUPLICATE_PERSON);
}
}
} |
package seedu.todo.controllers;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;
import seedu.todo.commons.EphemeralDB;
import seedu.todo.commons.exceptions.InvalidNaturalDateException;
import seedu.todo.commons.exceptions.ParseException;
import seedu.todo.controllers.concerns.DateParser;
import seedu.todo.controllers.concerns.Renderer;
import seedu.todo.controllers.concerns.Tokenizer;
import seedu.todo.models.CalendarItem;
import seedu.todo.models.Event;
import seedu.todo.models.Task;
import seedu.todo.models.TodoListDB;
/**
* @@author A0093907W
*
* Controller to update a CalendarItem.
*/
public class UpdateController implements Controller {
private static final String NAME = "Update";
private static final String DESCRIPTION = "Updates a task by listed index.";
private static final String COMMAND_SYNTAX = "update <index> <task> by <deadline>";
private static final String MESSAGE_UPDATE_SUCCESS = "Item successfully updated!";
private static CommandDefinition commandDefinition =
new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX);
public static CommandDefinition getCommandDefinition() {
return commandDefinition;
}
@Override
public float inputConfidence(String input) {
// TODO
return (input.toLowerCase().startsWith("update")) ? 1 : 0;
}
/**
* Get the token definitions for use with <code>tokenizer</code>.<br>
* This method exists primarily because Java does not support HashMap
* literals...
*
* @return tokenDefinitions
*/
private static Map<String, String[]> getTokenDefinitions() {
Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>();
tokenDefinitions.put("default", new String[] {"update"});
tokenDefinitions.put("name", new String[] {"name"});
tokenDefinitions.put("time", new String[] { "at", "by", "on", "before", "time" });
tokenDefinitions.put("timeFrom", new String[] { "from" });
tokenDefinitions.put("timeTo", new String[] { "to" });
return tokenDefinitions;
}
@Override
public void process(String input) throws ParseException {
// TODO: Example of last minute work
Map<String, String[]> parsedResult;
parsedResult = Tokenizer.tokenize(getTokenDefinitions(), input);
// Record index
Integer recordIndex = parseIndex(parsedResult);
// Retrieve record and check if task or event
EphemeralDB edb = EphemeralDB.getInstance();
CalendarItem calendarItem = null;
try {
calendarItem = edb.getCalendarItemsByDisplayedId(recordIndex);
} catch (NullPointerException e) {
System.out.println("Wrong index!");
}
boolean isTask = calendarItem.getClass() == Task.class;
// Name
String name = parseName(parsedResult);
// Time
String[] naturalDates = DateParser.extractDatePair(parsedResult);
String naturalFrom = naturalDates[0];
String naturalTo = naturalDates[1];
}
/**
* Extracts the record index from parsedResult.
*
* @param parsedResult
* @return Integer index if parse was successful, null otherwise.
*/
private Integer parseIndex(Map<String, String[]> parsedResult) {
String indexStr = null;
if (parsedResult.get("default") != null && parsedResult.get("default")[1] != null) {
indexStr = parsedResult.get("default")[1].trim();
return Integer.decode(indexStr);
} else {
return null;
}
}
/**
* Extracts the name to be updated from parsedResult.
*
* @param parsedResult
* @return String name if found, null otherwise.
*/
private String parseName(Map<String, String[]> parsedResult) {
if (parsedResult.get("name") != null && parsedResult.get("name")[1] != null) {
return parsedResult.get("name")[1];
}
return null;
}
/**
* Updates and persists a CalendarItem to the DB.
*
* @param db
* TodoListDB instance
* @param record
* Record to update
* @param isTask
* true if CalendarItem is a Task, false if Event
* @param name
* Display name of CalendarItem object
* @param dateFrom
* Due date for Task or start date for Event
* @param dateTo
* End date for Event
*/
private void updateCalendarItem(TodoListDB db, CalendarItem record,
boolean isTask, String name, LocalDateTime dateFrom, LocalDateTime dateTo) {
// Update name if not null
if (name != null) {
record.setName(name);
}
// Update time
if (isTask) {
Task task = (Task) record;
if (dateFrom != null) {
task.setDueDate(dateFrom);
}
} else {
Event event = (Event) record;
if (dateFrom != null) {
event.setStartDate(dateFrom);
}
if (dateTo != null) {
event.setEndDate(dateTo);
}
}
// Persist
db.save();
}
} |
package sg.ncl.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.ConfigurableEnvironment;
import sg.ncl.service.authentication.AuthenticationApplication;
import sg.ncl.service.experiment.ExperimentApplication;
import sg.ncl.service.realization.RealizationApplication;
import sg.ncl.service.registration.RegistrationApplication;
import sg.ncl.service.team.TeamApplication;
import sg.ncl.service.user.UserApplication;
import sg.ncl.service.version.VersionApplication;
import java.sql.SQLException;
/**
* @author Christopher Zhong
*/
@SpringBootApplication
@Import({
AuthenticationApplication.class,
ExperimentApplication.class,
RealizationApplication.class,
RegistrationApplication.class,
TeamApplication.class,
UserApplication.class,
VersionApplication.class
})
public class ServicesInOneApplication {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
final ConfigurableApplicationContext context = SpringApplication.run(ServicesInOneApplication.class, args);
final ConfigurableEnvironment environment = context.getEnvironment();
final FirstRun firstRun = context.getBean(FirstRun.class);
if (environment.containsProperty("reset")) {
firstRun.reset();
}
}
} |
package synapticloop.b2.response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import synapticloop.b2.exception.B2ApiException;
import java.util.Iterator;
public abstract class BaseB2Response {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseB2Response.class);
private final JSONObject response;
/**
* Create a new B2 Response object by parsing the passed in String
*
* @param json the Response (in json format)
* @throws B2ApiException if there was an error in the parsing of the reponse
*/
public BaseB2Response(final String json) throws B2ApiException {
this(parse(json));
}
/**
* Create a new B2 Response with a pre parsed JSONObject response
*
* @param response the pre-parsed json object
* @throws B2ApiException if there was an error in the response
*/
public BaseB2Response(final JSONObject response) throws B2ApiException {
this.response = response;
}
/**
* Parse a string into a JSON object
*
* @param json the data to parse to an object
* @return the parsed JSON object
* @throws B2ApiException if there was an error parsing the object
*/
private static JSONObject parse(String json) throws B2ApiException {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(json);
} catch (JSONException ex) {
throw new B2ApiException(ex);
}
return jsonObject;
}
/**
* Read and remove object with key from JSON
*/
protected String readString(String key) {
return this.readString(response, key);
}
protected String readString(JSONObject response, String key) {
final Object value = response.remove(key);
if (null == value) {
LOGGER.warn("No field for key {}", key);
return null;
}
return value.toString();
}
/**
* Read and remove object with key from JSON
*/
protected int readInt(String key) {
final Object value = response.remove(key);
if (null == value) {
LOGGER.warn("No field for key {}", key);
return -1;
}
return value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString());
}
/**
* Read and remove object with key from JSON
*/
protected long readLong(String key) {
final Object value = response.remove(key);
if (null == value) {
LOGGER.warn("No field for key {}", key);
return -1L;
}
return value instanceof Number ? ((Number) value).longValue() : Long.parseLong(value.toString());
}
protected JSONObject readObject(String key) {
return this.readObject(response, key);
}
protected JSONObject readObject(JSONObject response, String key) {
final Object value = response.remove(key);
if (null == value) {
LOGGER.warn("No field for key {}", key);
return null;
}
return value instanceof JSONObject ? (JSONObject) value : null;
}
/**
* Read and remove object with key from JSON
*/
protected JSONArray readObjects(String key) {
final Object value = response.remove(key);
if (null == value) {
LOGGER.warn("No field for key {}", key);
return null;
}
return value instanceof JSONArray ? (JSONArray) value : null;
}
/**
* Parse through the expected keys to determine whether any of the keys in
* the response will not be mapped. This will loop through the JSON object
* and any key left in the object will generate a 'WARN' message. The
* response class __MUST__ remove the object (i.e. jsonObject.remove(KEY_NAME))
* after getting the value
*
* @param LOGGER The logger to use
*/
@SuppressWarnings("rawtypes")
protected void warnOnMissedKeys(Logger LOGGER) {
if (LOGGER.isWarnEnabled()) {
Iterator keys = response.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
LOGGER.warn("Found an unexpected key of '{}' in JSON that is not mapped to a field.", key);
}
}
}
} |
package uk.ac.standrews.cs.jetson;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import uk.ac.standrews.cs.jetson.JsonRpcResponse.JsonRpcResponseError;
import uk.ac.standrews.cs.jetson.JsonRpcResponse.JsonRpcResponseResult;
import uk.ac.standrews.cs.jetson.exception.AccessException;
import uk.ac.standrews.cs.jetson.exception.InternalException;
import uk.ac.standrews.cs.jetson.exception.InvalidJsonException;
import uk.ac.standrews.cs.jetson.exception.InvalidParameterException;
import uk.ac.standrews.cs.jetson.exception.InvalidRequestException;
import uk.ac.standrews.cs.jetson.exception.InvocationException;
import uk.ac.standrews.cs.jetson.exception.JsonRpcException;
import uk.ac.standrews.cs.jetson.exception.MethodNotFoundException;
import uk.ac.standrews.cs.jetson.exception.ParseException;
import uk.ac.standrews.cs.jetson.exception.ServerException;
import uk.ac.standrews.cs.jetson.exception.ServerRuntimeException;
import uk.ac.standrews.cs.jetson.util.CloseableUtil;
import uk.ac.standrews.cs.jetson.util.ReflectionUtil;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
public class JsonRpcServer {
private static final Logger LOGGER = Logger.getLogger(JsonRpcServer.class.getName());
private static final JsonEncoding DEFAULT_JSON_ENCODING = JsonEncoding.UTF8;
private static final int DEFAULT_SOCKET_READ_TIMEOUT_MILLISECONDS = 10 * 1000;
private static final AtomicLong NEXT_REQUEST_HANDLER_ID = new AtomicLong();
private final Object service;
private final ServerSocket server_socket;
private final JsonFactory json_factory;
private final ExecutorService executor;
private final Thread server_thread;
private final Map<String, Method> dispatch;
private final ConcurrentSkipListSet<JsonRpcRequestHandler> request_handlers;
private volatile JsonEncoding encoding;
private volatile int socket_read_timeout;
private volatile InetSocketAddress endpoint;
public <T> JsonRpcServer(final Class<T> service_interface, final T service, final JsonFactory json_factory, final ExecutorService executor) throws IOException {
this(new InetSocketAddress(0), service_interface, service, json_factory, executor);
}
public <T> JsonRpcServer(final InetSocketAddress endpoint, final Class<T> service_interface, final T service, final JsonFactory json_factory, final ExecutorService executor) throws IOException {
this.endpoint = endpoint;
this.server_socket = new ServerSocket();
this.service = service;
this.json_factory = json_factory;
this.executor = executor;
request_handlers = new ConcurrentSkipListSet<JsonRpcRequestHandler>();
dispatch = ReflectionUtil.mapNamesToMethods(service_interface);
server_thread = new ServerThread();
setDefaultConfigurations();
}
private void setDefaultConfigurations() {
setEncoding(DEFAULT_JSON_ENCODING);
setSocketReadTimeout(DEFAULT_SOCKET_READ_TIMEOUT_MILLISECONDS);
}
public void setSocketReadTimeout(final int milliseconds) {
socket_read_timeout = milliseconds;
}
public void setEncoding(final JsonEncoding encoding) {
this.encoding = encoding;
}
public void expose() throws IOException {
server_socket.bind(endpoint);
server_thread.start();
endpoint = new InetSocketAddress(server_socket.getInetAddress(), server_socket.getLocalPort());
}
public void unexpose() {
server_thread.interrupt();
}
public InetSocketAddress getLocalSocketAddress() {
return server_socket.isBound() ? endpoint : null;
}
public void shutdown() {
unexpose();
shutdownRequestHandlers();
executor.shutdownNow();
CloseableUtil.closeQuietly(CloseableUtil.toCloseable(server_socket));
}
private void shutdownRequestHandlers() {
for (final JsonRpcRequestHandler request_handler : request_handlers) {
request_handler.shutdown();
}
}
private Method findServiceMethodByName(final String method_name) throws MethodNotFoundException {
if (!dispatch.containsKey(method_name)) { throw new MethodNotFoundException(); }
return dispatch.get(method_name);
}
private Class<?>[] findParameterTypesByMethodName(final String method_name) {
final Method method = dispatch.get(method_name);
return method != null ? method.getParameterTypes() : null;
}
private Object invoke(final Method method, final Object... parameters) throws IllegalAccessException, InvocationTargetException {
return method.invoke(service, parameters);
}
private void handleSocket(final Socket socket) {
try {
final JsonRpcRequestHandler request_handler = new JsonRpcRequestHandler(socket);
executor.execute(request_handler);
request_handlers.add(request_handler);
}
catch (final IOException e) {
LOGGER.log(Level.WARNING, "failed to handle established socket", e);
}
}
static JsonParser createJsonParser(final Socket socket, final JsonFactory json_factory, final JsonEncoding encoding) throws IOException {
final BufferedReader buffered_reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), encoding.getJavaName()));
return json_factory.createParser(buffered_reader);
}
static JsonGenerator createJsonGenerator(final Socket socket, final JsonFactory json_factory, final JsonEncoding encoding) throws IOException {
final BufferedWriter buffered_writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), encoding.getJavaName()));
return json_factory.createGenerator(buffered_writer);
}
private class ServerThread extends Thread {
public ServerThread() {
setName("server_thread_" + server_socket.getLocalPort());
}
@Override
public void run() {
while (!isInterrupted() && !server_socket.isClosed()) {
try {
final Socket socket = server_socket.accept();
socket.setSoTimeout(socket_read_timeout);
handleSocket(socket);
}
catch (final Exception e) {
interrupt();
}
}
LOGGER.fine("server stopped listening for incomming connections");
}
}
private class JsonRpcRequestHandler implements Runnable, Comparable<JsonRpcRequestHandler> {
private final Long id;
private final Socket socket;
private final JsonGenerator json_generator;
private final JsonParser parser;
private volatile Long current_request_id;
public JsonRpcRequestHandler(final Socket socket) throws IOException {
id = NEXT_REQUEST_HANDLER_ID.getAndIncrement();
this.socket = socket;
json_generator = createJsonGenerator(socket, json_factory, encoding);
parser = createJsonParser(socket, json_factory, encoding);
}
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted() && !socket.isClosed()) {
final JsonRpcRequest request = readRequest();
final JsonRpcResponseResult result = handleRequest(request);
writeResponse(result);
}
}
catch (final RuntimeException e) {
handleException(new ServerRuntimeException(e));
}
catch (final JsonRpcException e) {
handleException(e);
}
finally {
shutdown();
}
}
@Override
public int compareTo(final JsonRpcRequestHandler other) {
return id.compareTo(other.id);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final JsonRpcRequestHandler other = (JsonRpcRequestHandler) obj;
if (!getOuterType().equals(other.getOuterType())) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
}
else if (!id.equals(other.id)) {
return false;
}
return true;
}
private void shutdown() {
Thread.currentThread().interrupt();
CloseableUtil.closeQuietly(json_generator, parser, CloseableUtil.toCloseable(socket));
request_handlers.remove(this);
}
private void handleException(final JsonRpcException exception) {
final JsonRpcResponseError error = new JsonRpcResponseError(current_request_id, exception);
try {
writeResponse(error);
}
catch (final IOException e) {
LOGGER.log(Level.FINE, "failed to notify JSON RPC error", e);
}
}
private JsonRpcResponseResult handleRequest(final JsonRpcRequest request) throws ServerException {
final String method_name = request.getMethodName();
final Method method = findServiceMethodByName(method_name);
final Object[] parameters = request.getParameters();
try {
final Object result = invoke(method, parameters);
return new JsonRpcResponseResult(request.getId(), result);
}
catch (final IllegalArgumentException e) {
throw new InvalidParameterException(e);
}
catch (final RuntimeException e) {
throw new ServerRuntimeException(e);
}
catch (final InvocationTargetException e) {
throw new InvocationException(e);
}
catch (final IllegalAccessException e) {
throw new AccessException(e);
}
catch (final ExceptionInInitializerError e) {
throw new InternalException(e);
}
}
private void setCurrentRequestId(final Long request_id) {
this.current_request_id = request_id;
}
private void resetCurrentRequestId() {
setCurrentRequestId(null);
}
private JsonRpcRequest readRequest() throws ServerException, ParseException {
try {
resetCurrentRequestId();
final JsonRpcRequest request = new JsonRpcRequest();
parser.nextToken();
while (parser.nextToken() != JsonToken.END_OBJECT && parser.getCurrentToken() != null) {
final String key = parser.getCurrentName();
parser.nextToken();
if (JsonRpcMessage.VERSION_KEY.equals(key)) {
request.setVersion(parser.getText());
}
if (JsonRpcRequest.METHOD_KEY.equals(key)) {
request.setMethodName(parser.getText());
}
if (JsonRpcMessage.ID_KEY.equals(key)) {
request.setId(parser.getLongValue());
}
if (JsonRpcRequest.PARAMETERS_KEY.equals(key)) {
final String method_name = request.getMethodName();
final Object[] params = readRequestParameters(method_name);
request.setParams(params);
}
}
setCurrentRequestId(request.getId());
return request;
}
catch (final JsonParseException e) {
throw new InvalidJsonException(e);
}
catch (final JsonGenerationException e) {
throw new InternalException(e);
}
catch (final JsonProcessingException e) {
throw new InvalidRequestException(e);
}
catch (final IOException e) {
throw new InternalException(e);
}
}
private Object[] readRequestParameters(final String method_name) throws IOException, JsonProcessingException, JsonParseException {
final Object[] params;
if (method_name == null) {
LOGGER.warning("unspecified method name, or params is passed before method name in JSON request; deserializing parameters without type information.");
params = readRequestParametersWithoutTypeInformation();
}
else {
final Class<?>[] param_types = findParameterTypesByMethodName(method_name);
if (param_types == null) {
LOGGER.warning("no parameter types was found for method " + method_name + "; deserializing parameters without type information.");
return readRequestParametersWithoutTypeInformation();
}
else {
params = readRequestParametersWithTypes(param_types);
}
}
return params;
}
private Object[] readRequestParametersWithTypes(final Class<?>[] types) throws IOException, JsonParseException, JsonProcessingException {
final Object[] params = new Object[types.length];
int index = 0;
while (parser.nextToken() != JsonToken.END_ARRAY && parser.getCurrentToken() != null) {
params[index] = parser.readValueAs(types[index]);
index++;
}
return params;
}
private Object[] readRequestParametersWithoutTypeInformation() throws IOException, JsonProcessingException {
return parser.readValueAs(Object[].class);
}
private void writeResponse(final JsonRpcResponse response) throws ServerException {
try {
json_generator.writeObject(response);
}
catch (final IOException e) {
throw new InternalException(e);
}
}
private JsonRpcServer getOuterType() {
return JsonRpcServer.this;
}
}
} |
package ibis.ipl.impl;
import ibis.io.DataInputStream;
import ibis.io.SerializationFactory;
import ibis.io.SerializationInput;
import java.io.IOException;
import org.apache.log4j.Logger;
/**
* This class represents the information about a particular sendport/receiveport
* connection, on the receiver side.
*/
public class ReceivePortConnectionInfo {
/** Debugging. */
protected static final Logger logger
= Logger.getLogger("ibis.ipl.impl.ReceivePortConnectionInfo");
/** Identifies the sendport side of the connection. */
public final SendPortIdentifier origin;
/** The serialization input stream of the connection. */
public SerializationInput in;
/** The receiveport of the connection. */
public final ReceivePort port;
/** The message that arrives on this connection. */
public ReadMessage message;
/**
* The underlying data stream for this connection.
* The serialization stream lies on top of this.
*/
public DataInputStream dataIn;
private long cnt = 0;
/**
* Constructs a new <code>ReceivePortConnectionInfo</code> with the
* specified parameters.
* @param origin identifies the sendport of this connection.
* @param port the receiveport.
* @param dataIn the inputstream on which a serialization input stream
* can be built.
* @exception IOException is thrown in case of trouble.
*/
public ReceivePortConnectionInfo(SendPortIdentifier origin,
ReceivePort port, DataInputStream dataIn) throws IOException {
this.origin = origin;
this.port = port;
this.dataIn = dataIn;
// newStream();
// Moved to subtypes. Calling it here may cause deadlocks!
port.addInfo(origin, this);
}
/**
* Returns the number of bytes read from the data stream.
* @return the number of bytes.
*/
public long bytesRead() {
long rd = dataIn.bytesRead();
if (rd != 0) {
dataIn.resetBytesRead();
port.addDataIn(rd);
cnt += rd;
}
return cnt;
}
/**
* This method must be called each time a connected sendport adds a new
* connection. This new connection may either be to the current receiveport,
* or to another one. In both cases, the serialization stream must be
* recreated.
* @exception IOException is thrown in case of trouble.
*/
public void newStream() throws IOException {
bytesRead();
if (in != null) {
in.close();
}
in = SerializationFactory.createSerializationInput(port.serialization,
dataIn);
message = port.createReadMessage(in, this);
}
/**
* This method closes the connection, as the result of the specified
* exception. Implementations may need to redefine this method
* @param e the exception.
*/
public void close(Throwable e) {
try {
in.close();
} catch(Throwable z) {
// ignore
}
try {
dataIn.close();
} catch(Throwable z) {
// ignore
}
in = null;
if (logger.isDebugEnabled()) {
logger.debug(port.name + ": connection with " + origin
+ " closing", e);
}
port.lostConnection(origin, e);
}
/**
* This method gets called when the upcall for the message explicitly
* called {@link ReadMessage#finish()}.
* The default implementation just allocates a new message.
*/
protected void upcallCalledFinish() {
message = port.createReadMessage(in, this);
if (logger.isDebugEnabled()) {
logger.debug(port.name + ": new connection handler for " + origin
+ ", finish called from upcall");
}
}
} |
package ibis.ipl.impl.registry.gossip;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ibis.ipl.impl.IbisIdentifier;
import ibis.ipl.impl.registry.statistics.Statistics;
import ibis.util.TypedProperties;
class MemberSet extends Thread {
private static final Logger logger = LoggerFactory
.getLogger(MemberSet.class);
private final TypedProperties properties;
private final Registry registry;
private final Statistics statistics;
private final HashSet<UUID> deceased;
private final HashSet<UUID> left;
private final HashMap<UUID, Member> members;
private Member self;
private final Random random;
/**
* Members that are actually reachable.
*/
private int liveMembers;
MemberSet(TypedProperties properties, Registry registry,
Statistics statistics) {
this.properties = properties;
this.registry = registry;
this.statistics = statistics;
deceased = new HashSet<UUID>();
left = new HashSet<UUID>();
members = new HashMap<UUID, Member>();
random = new Random();
}
@Override
public synchronized void start() {
this.setDaemon(true);
super.start();
}
private synchronized Member getMember(IbisIdentifier ibis, boolean create) {
Member result;
UUID id = UUID.fromString(ibis.getID());
if (deceased.contains(id) || left.contains(id)) {
return null;
}
result = members.get(id);
if (result == null && create) {
result = new Member(ibis, properties);
members.put(id, result);
registry.ibisJoined(ibis);
if (statistics != null) {
statistics.newPoolSize(members.size());
}
}
return result;
}
public synchronized void maybeDead(IbisIdentifier ibis) {
Member member = getMember(ibis, false);
if (member == null) {
return;
}
member.suspectDead(registry.getIbisIdentifier());
cleanup(member);
}
public synchronized void assumeDead(IbisIdentifier ibis) {
Member member = getMember(ibis, false);
if (member == null) {
return;
}
member.declareDead();
cleanup(member);
}
public synchronized void leave(IbisIdentifier ibis) {
Member member = getMember(ibis, true);
if (member == null) {
return;
}
member.setLeft();
cleanup(member);
}
public synchronized void leave() {
if (self != null) {
self.setLeft();
}
}
public synchronized IbisIdentifier getFirstLiving(
IbisIdentifier[] candidates) {
if (candidates == null || candidates.length == 0) {
return null;
}
for (IbisIdentifier candidate : candidates) {
Member member = getMember(candidate, false);
if (member != null && !member.hasLeft() && !member.isDead()) {
return candidate;
}
}
// no alive canidates found, return first candidate
return candidates[0];
}
public void writeGossipData(DataOutputStream out, int gossipSize) throws IOException {
UUID[] deceased;
UUID[] left;
Member[] randomMembers;
synchronized (this) {
deceased = this.deceased.toArray(new UUID[0]);
left = this.left.toArray(new UUID[0]);
randomMembers = getRandomMembers(gossipSize);
if (self != null) {
// make sure we send out ourselves as "just seen"
self.seen();
}
}
out.writeInt(deceased.length);
for (UUID id : deceased) {
out.writeLong(id.getMostSignificantBits());
out.writeLong(id.getLeastSignificantBits());
}
out.writeInt(left.length);
for (UUID id : left) {
out.writeLong(id.getMostSignificantBits());
out.writeLong(id.getLeastSignificantBits());
}
out.writeInt(randomMembers.length);
for (Member member : randomMembers) {
member.writeTo(out);
}
}
public void readGossipData(DataInputStream in) throws IOException {
int nrOfDeceased = in.readInt();
if (nrOfDeceased < 0) {
throw new IOException("negative deceased list value");
}
ArrayList<UUID> newDeceased = new ArrayList<UUID>();
for (int i = 0; i < nrOfDeceased; i++) {
UUID id = new UUID(in.readLong(), in.readLong());
newDeceased.add(id);
}
int nrOfLeft = in.readInt();
if (nrOfLeft < 0) {
throw new IOException("negative left list value");
}
ArrayList<UUID> newLeft = new ArrayList<UUID>();
for (int i = 0; i < nrOfLeft; i++) {
UUID id = new UUID(in.readLong(), in.readLong());
newLeft.add(id);
}
int nrOfMembers = in.readInt();
if (nrOfMembers < 0) {
throw new IOException("negative member list value");
}
ArrayList<Member> newMembers = new ArrayList<Member>();
for (int i = 0; i < nrOfMembers; i++) {
Member member = new Member(in, properties);
newMembers.add(member);
}
synchronized (this) {
for (Member member : newMembers) {
UUID id = member.getUUID();
if (members.containsKey(id)) {
// merge state of know and received member
members.get(id).merge(member);
} else if (!deceased.contains(id) && !left.contains(id)) {
// add new member
members.put(id, member);
// tell registry about his new member
registry.ibisJoined(member.getIdentifier());
if (statistics != null) {
statistics.newPoolSize(members.size());
}
}
}
for (UUID id : newDeceased) {
if (members.containsKey(id)) {
members.get(id).declareDead();
} else if (!left.contains(id)) {
deceased.add(id);
}
}
for (UUID id : newLeft) {
if (members.containsKey(id)) {
members.get(id).setLeft();
} else {
left.add(id);
}
}
}
}
/**
* Clean up the list of members. Also passes leave and died events to the
* registry.
*/
private synchronized void cleanup(Member member) {
if (deceased.contains(member.getUUID())) {
member.declareDead();
}
if (left.contains(member.getUUID())) {
member.setLeft();
}
// if there are not enough live members in a pool to reach the
// minimum needed to otherwise declare a member dead, do it now
if (member.isSuspect() && member.nrOfWitnesses() >= liveMembers) {
logger.warn("declared " + member + " with "
+ member.nrOfWitnesses()
+ " witnesses dead due to a low number of live members ("
+ liveMembers + ").");
member.declareDead();
}
if (member.hasLeft()) {
left.add(member.getUUID());
members.remove(member.getUUID());
if (statistics != null) {
statistics.newPoolSize(members.size());
}
registry.ibisLeft(member.getIdentifier());
logger.debug("purged " + member + " from list");
} else if (member.isDead()) {
deceased.add(member.getUUID());
members.remove(member.getUUID());
if (statistics != null) {
statistics.newPoolSize(members.size());
}
registry.ibisDied(member.getIdentifier());
logger.debug("purged " + member + " from list");
}
}
/**
* Update number of "alive" members
*/
private synchronized void updateLiveMembers() {
int result = 0;
for (Member member : members.values()) {
if (!member.isDead() && !member.hasLeft() && !member.timedout()) {
result++;
}
}
liveMembers = result;
}
/**
* Clean up the list of members.
*/
private synchronized void cleanup() {
// notice ourselves ;)
if (self != null) {
self.seen();
}
// update live member count
updateLiveMembers();
// iterate over copy of values, so we can remove them if we need to
for (Member member : members.values().toArray(new Member[0])) {
cleanup(member);
}
if (logger.isDebugEnabled()) {
logger.debug(self.getIdentifier() + ": members = " + members.size()
+ ", left = " + left.size() + " deceased = "
+ deceased.size());
}
}
private synchronized Member[] getRandomSuspects(int count) {
ArrayList<Member> suspects = new ArrayList<Member>();
for (Member member : members.values()) {
if (member.isSuspect()) {
suspects.add(member);
}
}
while (suspects.size() > count) {
suspects.remove(random.nextInt(suspects.size()));
}
return suspects.toArray(new Member[0]);
}
private synchronized Member[] getRandomMembers(int count) {
if (count < 0) {
return new Member[0];
}
ArrayList<Member> result = new ArrayList<Member>(members.values());
while (result.size() > count) {
result.remove(random.nextInt(result.size()));
}
return result.toArray(new Member[0]);
}
synchronized void printMembers() {
System.out.println("pool at " + registry.getIbisIdentifier());
System.out.println("dead:");
for (UUID member : deceased) {
System.out.println(member);
}
System.out.println("left:");
for (UUID member : left) {
System.out.println(member);
}
System.out.println("current:");
for (Member member : members.values()) {
System.out.println(member);
}
}
// ping suspect members once a second
public void run() {
Member self;
synchronized (this) {
// add ourselves to the member list
self = new Member(registry.getIbisIdentifier(), properties);
this.self = self;
members.put(self.getUUID(), self);
if (statistics != null) {
statistics.newPoolSize(members.size());
}
registry.ibisJoined(self.getIdentifier());
}
long interval = properties
.getIntProperty(RegistryProperties.PING_INTERVAL) * 1000;
int count = properties.getIntProperty(RegistryProperties.PING_COUNT);
while (!registry.isStopped()) {
cleanup();
Member[] suspects = getRandomSuspects(count);
logger.debug(self.getIdentifier() + ": checking " + suspects.length
+ " suspects");
for (Member suspect : suspects) {
if (suspect.equals(self)) {
logger.error("we are a suspect ourselves");
suspect.seen();
} else {
logger
.debug("suspecting " + suspect
+ " is dead, checking");
try {
registry.getCommHandler().ping(suspect.getIdentifier());
suspect.seen();
} catch (Exception e) {
logger.debug("could not reach " + suspect
+ ", adding ourselves as witness");
suspect.suspectDead(registry.getIbisIdentifier());
}
logger.debug("done checking " + suspect);
}
}
logger.debug(self.getIdentifier() + ": done checking "
+ suspects.length + " suspects");
int timeout = (int) (Math.random() * interval);
synchronized (this) {
if (timeout > 0) {
try {
wait(timeout);
} catch (InterruptedException e) {
// IGNORE
}
}
}
}
logger.debug(self.getIdentifier() + ": registry stopped, exiting");
}
} |
package inpro.incremental.unit;
import inpro.annotation.Label;
import inpro.audio.DDS16kAudioInputStream;
import inpro.synthesis.MaryAdapter;
import inpro.synthesis.MaryAdapter4internal;
import inpro.synthesis.hts.FullPFeatureFrame;
import inpro.synthesis.hts.FullPStream;
import inpro.synthesis.hts.IUBasedFullPStream;
import inpro.synthesis.hts.VocodingAudioStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.sound.sampled.AudioInputStream;
import org.apache.log4j.Logger;
/**
* an installment that supports incremental synthesis
* @author timo
*/
public class SysInstallmentIU extends InstallmentIU {
Logger logger = Logger.getLogger(this.getClass());
public SysInstallmentIU(String tts) {
super(null, tts);
groundedIn = MaryAdapter.getInstance().text2IUs(tts);
}
@SuppressWarnings({ "rawtypes", "unchecked" }) // allow cast from List<WordIU> to List<IU>
public SysInstallmentIU(String tts, List<WordIU> words) {
super(null, tts);
groundedIn = (List) words;
}
@SuppressWarnings({ "rawtypes", "unchecked" }) // allow cast from List<WordIU> to List<IU>
public SysInstallmentIU(List<? extends IU> words) {
super(null, "");
groundedIn = (List) words;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void scaleDeepCopyAndStartAtZero(double scale) {
List<WordIU> newWords = new ArrayList<WordIU>();
WordIU prevWord = null;
double startTime = startTime();
List<WordIU> words = (List<WordIU>) groundedIn();
for (WordIU w : words) {
List<SysSegmentIU> newSegments = new ArrayList<SysSegmentIU>();
for (SegmentIU seg : w.getSegments()) {
// TODO: the following needs to be reworked to restart from a newly generated feature vector
newSegments.add(new SysSegmentIU(new Label(
(seg.l.getStart() - startTime) * scale,
(seg.l.getEnd() - startTime) * scale,
seg.l.getLabel()
), seg instanceof SysSegmentIU ? ((SysSegmentIU) seg).legacyHTSmodel : null,
seg instanceof SysSegmentIU ? ((SysSegmentIU) seg).fv : null,
seg instanceof SysSegmentIU ? ((SysSegmentIU) seg).hmmdata : null,
seg instanceof SysSegmentIU ? ((SysSegmentIU) seg).hmmSynthesisFeatures : Collections.<FullPFeatureFrame>emptyList()));
}
// connect same-level-links
Iterator<SysSegmentIU> it = newSegments.iterator();
SysSegmentIU first = it.next();
while (it.hasNext()) {
SysSegmentIU next = it.next();
next.setSameLevelLink(first);
first = next;
}
WordIU newWord = new WordIU(w.getWord(), prevWord, (List) newSegments);
newWords.add(newWord);
prevWord = newWord;
}
groundedIn = (List) newWords;
}
/**
* return the HMM parameter set for this utterance (based on getWords())
*/
public FullPStream getFullPStream() {
return new IUBasedFullPStream(getInitialWord());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<SysSegmentIU> getSegments() {
List<SysSegmentIU> segments = new ArrayList<SysSegmentIU>();
for (WordIU word : getWords()) {
segments.addAll((List) word.getSegments());
}
return segments;
}
public CharSequence toLabelLines() {
StringBuilder sb = new StringBuilder();
for (SysSegmentIU seg : getSegments()) {
sb.append(seg.toLabelLine());
sb.append("\n");
}
return sb;
}
public AudioInputStream getAudio() {
boolean immediateReturn = true;
VocodingAudioStream vas = new VocodingAudioStream(getFullPStream(), MaryAdapter4internal.getDefaultHMMData(), immediateReturn);
return new DDS16kAudioInputStream(vas);
}
public String toMbrola() {
StringBuilder sb = new StringBuilder();
for (WordIU word : getWords()) {
sb.append(word.toMbrolaLines());
}
sb.append("
return sb.toString();
}
public WordIU getInitialWord() {
return (WordIU) groundedIn.get(0);
}
public WordIU getFinalWord() {
List<WordIU> words = getWords();
return words.get(words.size() - 1);
}
public List<WordIU> getWords() {
List<WordIU> activeWords = new ArrayList<WordIU>();
WordIU word = getInitialWord();
while (word != null) {
activeWords.add(word);
word = (WordIU) word.getNextSameLevelLink();
}
return activeWords;
}
@Override
public String toPayLoad() {
StringBuilder sb = new StringBuilder();
for (WordIU word : getWords()) {
sb.append(word.toPayLoad());
sb.append(" ");
}
return sb.toString();
}
public String toMarkedUpString() {
StringBuilder sb = new StringBuilder();
for (WordIU word : getWords()) {
String payload = word.toPayLoad().replace(">", ">").replace("<", "<");
if (word.isCompleted()) {
sb.append("<strong>");
sb.append(payload);
sb.append("</strong>");
} else if (word.isOngoing()) {
sb.append("<em>");
sb.append(payload);
sb.append("</em>");
} else
sb.append(payload);
sb.append(" ");
}
return sb.toString();
}
} |
import org.junit.Test;
import java.util.ArrayList;
import static org.assertj.core.api.Assertions.assertThat;
class HEntry<T, K> {
private T key;
private K value;
HEntry(T key, K value) {
this.key = key;
this.setValue(value);
}
T getKey() {
return key;
}
K getValue() {
return value;
}
void setValue(K value) {
this.value = value;
}
}
//TODO: resize
class Hashtbl<T, K> {
private ArrayList<ArrayList<HEntry<T, K>>> table;
private int size;
Hashtbl() {
this(20);
}
private Hashtbl(int size) {
this.size = size;
table = new ArrayList<>(this.size);
for (int i = 0; i < this.size; i++) {
table.add(new ArrayList<>());
}
}
private int indexOf(T key) {
return key.hashCode() % this.table.size();
}
void put(T key, K value) throws Exception {
int idx = indexOf(key);
ArrayList<HEntry<T, K>> bucket = table.get(idx);
for (HEntry<T, K> item : bucket) {
if (item.getKey().equals(key)) {
item.setValue(value);
return;
}
}
bucket.add(new HEntry<>(key, value));
}
K get(T key) throws Exception {
int idx = indexOf(key);
ArrayList<HEntry<T, K>> bucket = table.get(idx);
for (HEntry<T, K> item : bucket) {
if (item.getKey().equals(key)) return item.getValue();
}
throw new Exception("key not found!");
}
void remove(T key) throws Exception {
int idx = indexOf(key);
ArrayList<HEntry<T, K>> bucket = table.get(idx);
for (int i = 0; i < bucket.size(); i++) {
if (bucket.get(i).getKey().equals(key)) {
bucket.remove(i);
break;
}
}
throw new Exception("key not found!");
}
}
public class HashtblTest {
@Test
public void bidi_Test() {
Hashtbl<String, Integer> hashtbl = new Hashtbl<>();
try {
hashtbl.put("A", 1);
hashtbl.put("B", 2);
hashtbl.put("C", 3);
System.out.println(hashtbl.get("B"));
hashtbl.remove("B");
System.out.println(hashtbl.get("B"));
} catch (Exception e) {
e.printStackTrace();
}
assertThat(true).isEqualTo(true);
}
} |
package tests;
import engine.DataReader;
import engine.Recommender;
import engine.Graph;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
/**
* Recommender Tester.
*/
public class RecommenderTest {
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
/**
*
* Method: collabFilter(int userID, TreeMap<Double, List<Node>> scores)
*
*/
@Test
public void testCollabFilter() throws Exception {
int userID = 1;
Recommender r = new Recommender(DataReader.readMovieLensData());
List<Integer> recommended = r.collabFilter(userID,
r.getPearsonScores(userID), 10, 5);
System.out.println(recommended);
r.getMovieLensNames(userID, recommended);
}
@Test
public void testCollabFilterUser2() throws Exception {
int userID = 2;
Recommender r = new Recommender(DataReader.readMovieLensData());
List<Integer> recommended = r.collabFilter(userID,
r.getPearsonScores(userID), 10, 5);
System.out.println(recommended);
r.getMovieLensNames(userID, recommended);
}
@Test
public void testCollabFilterTestData() throws Exception {
int userID = 2;
String filename = "data/ml-100k/u1.base";
Recommender r = new Recommender(DataReader.readMovieLensTestData(filename));
List<Integer> recommended = r.collabFilter(userID,
r.getPearsonScores(userID), 10, 5);
System.out.println(recommended);
r.getMovieLensNames(userID, recommended);
}
@Test
public void testCollabFilterAccuracy() throws Exception {
double found = 0.0;
int numRecommendations = 5;
int numSimilarUsers = 75;
double expected = 5 * numRecommendations * 943;
for (int i = 1; i < 6; i++) {
String file1 = "data/ml-100k/u" + i +".base";
String file2 = "data/ml-100k/u" + i + ".test";
System.out.println(i);
Graph g = DataReader.readMovieLensTestData(file2);
Recommender r = new Recommender(DataReader.readMovieLensTestData(file1));
for (int j = 1; j < 944; j++) {
//System.out.println("Finding recommendations for:" + j);
List<Integer> recommended = r.collabFilter(j,
r.getPearsonScores(j), numSimilarUsers, numRecommendations);
for (int k = 0; k < numRecommendations; k++) {
if (recommended.size() > k &&
g.containsEdge(j, recommended.get(k))) {
found++;
}
}
}
}
System.out.println("Percentage of recommendations found is: " + found / expected);
}
/**
*
* Method: getPearsonScores(int userID)
*
*/
@Test
public void testGetPearsonScores() throws Exception {
//TODO: Test goes here...
}
/**
*
* Method: getJaccardScores(int userID)
*
*/
@Test
public void testGetJaccardScores() throws Exception {
//TODO: Test goes here...
}
/**
*
* Method: getNode()
*
*/
@Test
public void testGetNode() throws Exception {
//TODO: Test goes here...
}
/**
*
* Method: getWeight()
*
*/
@Test
public void testGetWeight() throws Exception {
//TODO: Test goes here...
}
/**
*
* Method: setWeight(double weight)
*
*/
@Test
public void testSetWeight() throws Exception {
//TODO: Test goes here...
}
/**
*
* Method: compareTo(Entry other)
*
*/
@Test
public void testCompareTo() throws Exception {
//TODO: Test goes here...
}
/**
*
* Method: getTopMatches(TreeMap<Double, List<Node>> map, int limit)
*
*/
@Test
public void testGetTopMatches() throws Exception {
//TODO: Test goes here...
}
/**
*
* Method: getPearsonCoeff(Node n1, Node n2)
*
*/
@Test
public void testGetPearsonCoeff() throws Exception {
//TODO: Test goes here...
}
/**
*
* Method: getJaccardCoeff(Node n1, Node n2)
*
*/
@Test
public void testGetJaccardCoeff() throws Exception {
//TODO: Test goes here...
}
} |
package threadtest;
/**
*
* @author Ruchira
*/
public class ThreadTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello Thread");
}
} |
package net.tomp2p.holep;
import java.io.IOException;
import java.net.Inet4Address;
import java.util.Scanner;
import net.tomp2p.dht.FutureGet;
import net.tomp2p.dht.FuturePut;
import net.tomp2p.dht.PeerBuilderDHT;
import net.tomp2p.dht.PeerDHT;
import net.tomp2p.futures.FutureBootstrap;
import net.tomp2p.futures.FutureDirect;
import net.tomp2p.futures.FutureShutdown;
import net.tomp2p.nat.FutureRelayNAT;
import net.tomp2p.nat.PeerBuilderNAT;
import net.tomp2p.nat.PeerNAT;
import net.tomp2p.p2p.Peer;
import net.tomp2p.p2p.PeerBuilder;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.rpc.ObjectDataReply;
import net.tomp2p.storage.Data;
public class HolePTestApp {
private static final int port = 4001;
private static final String PEER_1 = "peer1";
private static final String PEER_2 = "peer2";
private Peer peer;
private PeerNAT pNAT;
// private PeerDHT pDHT;
private PeerAddress masterPeerAddress;
private PeerAddress natPeerAddress;
public HolePTestApp() {
}
public void startMasterPeer() throws Exception {
peer = new PeerBuilder(Number160.createHash("master")).ports(port).start();
pNAT = new PeerBuilderNAT(peer).start();
// pDHT = new PeerBuilderDHT(peer).start();
System.err.println("SERVER BOOTSTRAP SUCCESS!");
System.err.println("IP: " + peer.peerAddress().inetAddress());
System.err.println("ID: " + peer.peerID());
}
public void startPeer(String[] args) throws Exception {
peer = new PeerBuilder(Number160.createHash(args[1])).ports(port).start();
PeerAddress bootstrapPeerAddress = new PeerAddress(Number160.createHash("master"), Inet4Address.getByName(args[0]), port, port);
masterPeerAddress = bootstrapPeerAddress;
// Set the isFirewalledUDP and isFirewalledTCP flags
PeerAddress upa = peer.peerBean().serverPeerAddress();
upa = upa.changeFirewalledTCP(true).changeFirewalledUDP(true);
peer.peerBean().serverPeerAddress(upa);
// find neighbors
FutureBootstrap futureBootstrap = peer.bootstrap().peerAddress(bootstrapPeerAddress).start();
futureBootstrap.awaitUninterruptibly();
// setup relay
pNAT = new PeerBuilderNAT(peer).start();
// set up 3 relays
// FutureRelay futureRelay = uNat.startSetupRelay(new FutureRelay());
// futureRelay.awaitUninterruptibly();
FutureRelayNAT frn = pNAT.startRelay(bootstrapPeerAddress);
frn.awaitUninterruptibly();
// find neighbors again
FutureBootstrap fb = peer.bootstrap().peerAddress(bootstrapPeerAddress).start();
fb.awaitUninterruptibly();
if (!fb.isSuccess()) {
System.err.println("ERROR WHILE NAT-BOOTSTRAPPING. THE APPLICATION WILL NOW SHUTDOWN!");
System.exit(1);
} else {
System.err.println("NAT-BOOTSTRAP SUCCESS!");
}
// do maintenance
// uNat.bootstrapBuilder(peer.bootstrap().peerAddress(bootstrapPeerAddress));
// uNat.startRelayMaintenance(futureRelay);
}
public void setObjectDataReply() {
peer.objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
System.out.println("SUCCESS HIT");
System.out.println("Sender: " + sender.toString());
String req = (String) request;
System.err.println("Received Message: " + req);
String reply = "reply";
return (Object) reply;
}
});
}
public void runTextInterface() throws Exception {
System.out.println("Welcome to the textinterface of HolePTestApp!");
Scanner scan = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Choose a valid order. \n"
+ " 0 = Exit process \n"
+ " 1 = getNatPeerAddress() \n"
+ " 2 = putNATPeerAddress() \n"
+ " 3 = sendDirectMessage() \n"
+ " 4 = sendDirectNATMessage() \n"
+ " 5 = sendRelayNATMessage()");
System.out.println();
int order = scan.nextInt();
System.out.println("You've entered the number " + order + ".");
switch (order) {
case 0: //end process
exit = true;
break;
case 1: //get PeerAddress of other peer
getNATPeerAddress();
break;
case 2: //put own PeerAddress of myself into DHT
putNATPeerAddress();
case 3: //send Message to peer not behind a NAT
sendDirectMessage();
break;
case 4: //send Message to peer behind a NAT
sendDirectNATMessage();
break;
case 5: //send Relay message to get to the PeerAddress of one another
sendRelayNATMessage();
default: //start process again
break;
}
}
// if 0 is chosen, the peer should shutdown and the program should end
FutureShutdown fs = (FutureShutdown) peer.shutdown();
fs.awaitUninterruptibly();
System.exit(0);
}
private void sendRelayNATMessage() {
PeerAddress p2 = new PeerAddress(Number160.createHash(PEER_2), peer.peerAddress().peerSocketAddress(), true, true, true, peer.peerAddress().peerSocketAddresses());
p2.changeAddress(masterPeerAddress.peerSocketAddress().inetAddress());
peer.objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request) throws Exception {
System.err.println(sender);
natPeerAddress = sender;
return null;
}
});
FutureDirect fd = peer.sendDirect(p2).object("Hello relay World!").start();
fd.awaitUninterruptibly(10000);
if (fd.isFailed()) {
System.err.println("NO RELAY SENDDIRECT COULD BE MADE!");
} else {
System.err.println("RELAY SENDDIRECT SUCCESS!");
}
}
private void putNATPeerAddress() throws IOException {
// //store id to DHT (important for finding other natPeer
// pDHT = new PeerBuilderDHT(peer).start();
// FuturePut fp = pDHT.put(peer.peerID()).object(new Data(peer.peerAddress())).start();
// fp.awaitUninterruptibly();
// if (!fp.isSuccess()) {
// System.err.println("ERROR WHILE PUTTING THE PEERADDRESS INTO THE DHT!");
// } else {
// System.err.println("DHT PUT SUCCESS!");
}
private void getNATPeerAddress() {
// if (peer.peerAddress().peerId().toString().equals(Number160.createHash(PEER_1))) {
// getOtherNATPeerAddress(PEER_2);
// } else {
// getOtherNATPeerAddress(PEER_1);
}
private void getOtherNATPeerAddress(String peerId) {
// FutureGet fg = pDHT.get(Number160.createHash(peerId)).start();
// fg.awaitUninterruptibly();
// if (!fg.isSuccess()) {
// System.err.println("FUTUREGET FAIL WITH ARG " + peerId + "!");
// } else {
// System.err.println("FUTUREGET SUCCESS WITH ARG " + peerId + "!");
}
private void sendDirectNATMessage() throws IOException {
setObjectDataReply();
FutureDirect fd = peer.sendDirect(natPeerAddress).object("Hello World").start();
fd.awaitUninterruptibly();
if (!fd.isSuccess()) {
System.err.println("SENDDIRECT-NATMESSAGE FAIL!");
} else {
System.err.println("SENDDIRECT-NATMESSAGE SUCCESS!");
}
}
private void sendDirectMessage() throws IOException {
setObjectDataReply();
FutureDirect fd = peer.sendDirect(masterPeerAddress).object("Hello World").start();
fd.awaitUninterruptibly();
if (!fd.isSuccess()) {
System.err.println("SENDDIRECT-MESSAGE FAIL!");
} else {
System.err.println("SENDDIRECT-MESSAGE SUCCESS!");
}
}
} |
package org.ocelotds;
/**
* Constants Class
*
* @author hhfrancois
*/
public interface Constants {
String UTF_8 = "UTF-8";
String JS = ".js";
String MIN = "-min";
String SLASH = "/";
String BACKSLASH_N = "\n";
String LOCALE = "LOCALE";
String OCELOT = "ocelot";
String OCELOT_CORE = OCELOT + "-core";
String OCELOT_MIN = OCELOT + MIN;
String SLASH_OCELOT_JS = SLASH + OCELOT + JS;
String MINIFY_PARAMETER = "minify";
String JSTYPE = "text/javascript;charset=UTF-8";
String FALSE = "false";
String TRUE = "true";
/**
* This string will be replaced by the contextPath in ocelot-core.js
*/
String CTXPATH = "%CTXPATH%";
interface Options {
String STACKTRACE_LENGTH = "ocelot.stacktrace.length";
}
interface Topic {
String SUBSCRIBERS = "subscribers";
String COLON = ":";
String ALL = "ALL";
}
interface Message {
String ID = "id";
String TYPE = "type";
String DATASERVICE = "ds";
String OPERATION = "op";
String ARGUMENTS = "args";
String ARGUMENTNAMES = "argNames";
String DEADLINE = "deadline";
String RESPONSE = "response";
interface Fault {
String MESSAGE = "message";
String CLASSNAME = "classname";
String STACKTRACE = "stacktrace";
}
}
interface Resolver {
String POJO = "pojo";
String CDI = "cdi";
String EJB = "ejb";
String SPRING = "spring";
}
interface Cache {
String CLEANCACHE_TOPIC = "ocelot-cleancache";
String ALL = "ALL";
String USE_ALL_ARGUMENTS = "*";
String ARGS_NOT_CONSIDERATED = "-";
}
} |
package modules.test;
import java.util.Map;
import java.util.TreeMap;
import org.junit.Assert;
import org.junit.Test;
import org.skyve.CORE;
import org.skyve.domain.MapBean;
import org.skyve.domain.types.DateOnly;
import org.skyve.domain.types.DateTime;
import org.skyve.domain.types.TimeOnly;
import org.skyve.domain.types.Timestamp;
import org.skyve.impl.bind.BindUtil;
import org.skyve.metadata.MetaDataException;
import org.skyve.metadata.model.Attribute;
import org.skyve.metadata.view.TextOutput.Sanitisation;
import org.skyve.persistence.DocumentQuery;
import org.skyve.util.Binder;
import org.skyve.util.OWASP;
import org.skyve.util.Time;
import org.skyve.util.Util;
import modules.admin.User.UserExtension;
import modules.admin.domain.Contact;
import modules.admin.domain.Snapshot;
import modules.admin.domain.User;
import modules.admin.domain.UserRole;
import modules.test.domain.AllAttributesPersistent;
public class BindTests extends AbstractSkyveTest {
@Test
@SuppressWarnings("static-method")
public void testSanitizeBinding() throws Exception {
Assert.assertNull(BindUtil.sanitiseBinding(null));
Assert.assertEquals("test", BindUtil.sanitiseBinding("test"));
Assert.assertEquals("test_test", BindUtil.sanitiseBinding("test.test"));
Assert.assertEquals("test_test_test", BindUtil.sanitiseBinding("test.test.test"));
Assert.assertEquals("test1_test2_test3", BindUtil.sanitiseBinding("test1.test2.test3"));
Assert.assertEquals("test_100__test_test", BindUtil.sanitiseBinding("test[100].test.test"));
Assert.assertEquals("test_test_0__test", BindUtil.sanitiseBinding("test.test[0].test"));
Assert.assertEquals("test_100__test_0__test", BindUtil.sanitiseBinding("test[100].test[0].test"));
Assert.assertEquals("test_100__test_0__test_1_", BindUtil.sanitiseBinding("test[100].test[0].test[1]"));
Assert.assertEquals("test1_100__test2_0__test3_1_", BindUtil.sanitiseBinding("test1[100].test2[0].test3[1]"));
}
@Test
@SuppressWarnings("static-method")
public void testUnsanitizeBinding() throws Exception {
Assert.assertNull(BindUtil.unsanitiseBinding(null));
Assert.assertEquals("test", BindUtil.unsanitiseBinding("test"));
Assert.assertEquals("test.test", BindUtil.unsanitiseBinding("test_test"));
Assert.assertEquals("test.test.test", BindUtil.unsanitiseBinding("test_test_test"));
Assert.assertEquals("test1.test2.test3", BindUtil.unsanitiseBinding("test1_test2_test3"));
Assert.assertEquals("test[100].test.test", BindUtil.unsanitiseBinding("test_100__test_test"));
Assert.assertEquals("test.test[0].test", BindUtil.unsanitiseBinding("test_test_0__test"));
Assert.assertEquals("test[100].test[0].test", BindUtil.unsanitiseBinding("test_100__test_0__test"));
Assert.assertEquals("test[100].test[0].test[1]", BindUtil.unsanitiseBinding("test_100__test_0__test_1_"));
Assert.assertEquals("test1[100].test2[0].test3[1]", BindUtil.unsanitiseBinding("test1_100__test2_0__test3_1_"));
}
@Test
@SuppressWarnings("static-method")
public void testGeneratedJavaIdentifier() throws Exception {
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("1"), "one");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("2"), "two");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("3"), "three");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("4"), "four");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("5"), "five");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("6"), "six");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("7"), "seven");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("8"), "eight");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("9"), "nine");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("_1"), "one");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("_2"), "two");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("_3"), "three");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("_4"), "four");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("_5"), "five");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("_6"), "six");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("_7"), "seven");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("_8"), "eight");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("_9"), "nine");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("11"), "one1");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("22"), "two2");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("33"), "three3");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("44"), "four4");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("55"), "five5");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("66"), "six6");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("77"), "seven7");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("88"), "eight8");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("99"), "nine9");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("v1"), "v1");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("v2"), "v2");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("v3"), "v3");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("v4"), "v4");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("v5"), "v5");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("v6"), "v6");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("v7"), "v7");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("v8"), "v8");
Assert.assertEquals(BindUtil.toJavaInstanceIdentifier("v9"), "v9");
}
@Test
public void testCopyProperties() throws Exception {
AllAttributesPersistent from = Util.constructRandomInstance(u, m, aapd, 2);
AllAttributesPersistent to = AllAttributesPersistent.newInstance();
Binder.copy(from, to);
for (Attribute a: aapd.getAttributes()) {
String name = a.getName();
Assert.assertEquals("Property Name " + name, Binder.get(from, name), Binder.get(to, name));
}
}
@Test
@SuppressWarnings("static-method")
public void testCopyPropertiesWithChildCollection() throws Exception {
UserExtension from = User.newInstance();
UserRole role = UserRole.newInstance();
from.getRoles().add(role);
role.setParent(from);
User to = User.newInstance();
Binder.copy(from, to);
Assert.assertEquals(role.getParent(), to);
}
@Test
@SuppressWarnings("static-method")
public void testSimpleMapBeanProperty() {
Map<String, Object> map = new TreeMap<>();
map.put(User.userNamePropertyName, "mike");
MapBean bean = new MapBean(User.MODULE_NAME, User.DOCUMENT_NAME, map);
Assert.assertEquals("mike", Binder.get(bean, User.userNamePropertyName));
}
@Test
@SuppressWarnings("static-method")
public void testCompoundMapBeanProperty() {
String binding = Binder.createCompoundBinding(User.contactPropertyName, Contact.namePropertyName);
Map<String, Object> map = new TreeMap<>();
map.put(binding, "mike");
MapBean bean = new MapBean(User.MODULE_NAME, User.DOCUMENT_NAME, map);
Assert.assertEquals("mike", Binder.get(bean, binding));
}
@Test
public void testSimpleThisProperty() throws Exception {
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
Map<String, Object> map = new TreeMap<>();
map.put(DocumentQuery.THIS_ALIAS, aap);
MapBean bean = new MapBean(m.getName(), aapd.getName(), map);
Assert.assertTrue(Binder.get(bean, AllAttributesPersistent.booleanFlagPropertyName) instanceof Boolean);
}
@Test
public void testCompoundThisProperty() throws Exception {
String binding = Binder.createCompoundBinding(AllAttributesPersistent.aggregatedAssociationPropertyName,
AllAttributesPersistent.booleanFlagPropertyName);
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
Map<String, Object> map = new TreeMap<>();
map.put(DocumentQuery.THIS_ALIAS, aap);
MapBean bean = new MapBean(m.getName(), aapd.getName(), map);
Assert.assertTrue(Binder.get(bean, binding) instanceof Boolean);
}
@Test
public void testSimpleMapPropertyOverThisProperty() throws Exception {
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
Map<String, Object> map = new TreeMap<>();
map.put(DocumentQuery.THIS_ALIAS, aap);
map.put(AllAttributesPersistent.booleanFlagPropertyName, null);
MapBean bean = new MapBean(m.getName(), aapd.getName(), map);
Assert.assertFalse(Binder.get(bean, AllAttributesPersistent.booleanFlagPropertyName) instanceof Boolean);
}
@Test
public void testCompoundMapPropertyOverThisProperty() throws Exception {
String binding = Binder.createCompoundBinding(AllAttributesPersistent.aggregatedAssociationPropertyName,
AllAttributesPersistent.booleanFlagPropertyName);
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
Map<String, Object> map = new TreeMap<>();
map.put(DocumentQuery.THIS_ALIAS, aap);
map.put(binding, null);
MapBean bean = new MapBean(m.getName(), aapd.getName(), map);
Assert.assertFalse(Binder.get(bean, binding) instanceof Boolean);
}
@Test
public void testCompoundPropertyWithoutMappedProperty2Deep() throws Exception {
String binding = Binder.createCompoundBinding(AllAttributesPersistent.aggregatedAssociationPropertyName,
AllAttributesPersistent.booleanFlagPropertyName);
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
Map<String, Object> map = new TreeMap<>();
map.put(AllAttributesPersistent.aggregatedAssociationPropertyName, aap);
MapBean bean = new MapBean(m.getName(), aapd.getName(), map);
Assert.assertTrue(Binder.get(bean, binding) instanceof Boolean);
}
@Test
public void testCompoundPropertyWithoutMappedProperty3Deep() throws Exception {
String binding = Binder.createCompoundBinding(AllAttributesPersistent.aggregatedAssociationPropertyName,
AllAttributesPersistent.aggregatedAssociationPropertyName,
AllAttributesPersistent.booleanFlagPropertyName);
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
Map<String, Object> map = new TreeMap<>();
map.put(AllAttributesPersistent.aggregatedAssociationPropertyName, aap);
MapBean bean = new MapBean(m.getName(), aapd.getName(), map);
Assert.assertTrue(Binder.get(bean, binding) instanceof Boolean);
}
@Test
public void testCompoundPropertyWithoutMappedProperty4Deep() throws Exception {
String binding = Binder.createCompoundBinding(AllAttributesPersistent.aggregatedAssociationPropertyName,
AllAttributesPersistent.aggregatedAssociationPropertyName,
AllAttributesPersistent.aggregatedAssociationPropertyName,
AllAttributesPersistent.booleanFlagPropertyName);
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
Map<String, Object> map = new TreeMap<>();
map.put(Binder.createCompoundBinding(AllAttributesPersistent.aggregatedAssociationPropertyName,
AllAttributesPersistent.aggregatedAssociationPropertyName),
aap);
MapBean bean = new MapBean(m.getName(), aapd.getName(), map);
Assert.assertTrue(Binder.get(bean, binding) instanceof Boolean);
}
@Test
public void testFormatMessage() throws Exception {
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
aap.setText("Test");
Assert.assertEquals("Test", Binder.formatMessage("Test", aap));
Assert.assertEquals("Test", Binder.formatMessage("{text}", aap));
Assert.assertEquals("TestTest", Binder.formatMessage("{text}{text}", aap));
// Test escapes
Assert.assertEquals("{text}Test", Binder.formatMessage("\\{text\\}{text}", aap));
Assert.assertEquals("{textTest", Binder.formatMessage("\\{text{text}", aap));
Assert.assertEquals("text}Test", Binder.formatMessage("text\\}{text}", aap));
Assert.assertEquals("{text", Binder.formatMessage("\\{text", aap));
aap.setText("{text}");
// Test '{' and '}' are left in tact when they are part of the value substituted
Assert.assertEquals("{text}{text}", Binder.formatMessage("{text}{text}", aap));
}
@Test(expected = MetaDataException.class)
public void testDanglingMessageFormat() throws Exception {
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
Assert.assertEquals("{text", Binder.formatMessage("{text", aap));
}
@Test
public void testExpressions() throws Exception {
AllAttributesPersistent bean = Util.constructRandomInstance(u, m, aapd, 2);
bean.setText("Test");
CORE.getStash().put("text", "Stash");
CORE.getUser().getAttributes().put("text", "Attribute");
final String currentDate = CORE.getCustomer().getDefaultDateConverter().toDisplayValue(new DateOnly());
final String tomorrowsDate = CORE.getCustomer().getDefaultDateConverter()
.toDisplayValue(Time.addDaysToNew(new DateOnly(), 1));
final String currentTime = CORE.getCustomer().getDefaultTimeConverter().toDisplayValue(new TimeOnly());
final String currentDateTime = CORE.getCustomer().getDefaultDateTimeConverter().toDisplayValue(new DateTime());
final String currentTimestamp = CORE.getCustomer().getDefaultTimestampConverter().toDisplayValue(new Timestamp());
Assert.assertEquals("TestUser", Binder.formatMessage("{USER}", bean));
Assert.assertEquals("TestUser", Binder.formatMessage("{USERID}", bean));
Assert.assertEquals("", Binder.formatMessage("{USERNAME}", bean));
Assert.assertEquals("", Binder.formatMessage("{DATAGROUPID}", bean));
Assert.assertNotEquals("", Binder.formatMessage("{CONTACTID}", bean));
Assert.assertEquals("bizhub", Binder.formatMessage("{CUSTOMER}", bean));
Assert.assertEquals(currentDate, Binder.formatMessage("{DATE}", bean));
Assert.assertEquals(currentTime, Binder.formatMessage("{TIME}", bean));
Assert.assertEquals(currentDateTime, Binder.formatMessage("{DATETIME}", bean));
Assert.assertEquals(currentTimestamp, Binder.formatMessage("{TIMESTAMP}", bean));
Assert.assertEquals(Util.getDocumentUrl(bean), Binder.formatMessage("{URL}", bean));
Assert.assertEquals("Test", Binder.formatMessage("{text}", bean));
Assert.assertEquals("Test", Binder.formatMessage("{ text }", bean));
Assert.assertEquals("Test", Binder.formatMessage("{bean:text}", bean));
Assert.assertEquals("Test", Binder.formatMessage("{bean: text }", bean));
Assert.assertEquals("Test", Binder.formatMessage("{bean : text }", bean));
Assert.assertEquals("Text", Binder.formatMessage("{disp:text}", bean));
Assert.assertEquals("", Binder.formatMessage("{desc:text}", bean));
Assert.assertEquals("Test", Binder.formatMessage("{el:bean.text}", bean));
Assert.assertEquals("Stash", Binder.formatMessage("{el:stash['text']}", bean));
Assert.assertEquals("Attribute", Binder.formatMessage("{el:user.attributes['text']}", bean));
Assert.assertEquals("", Binder.formatMessage("{el:stash['nothing']}", bean));
Assert.assertEquals("", Binder.formatMessage("{el:user.attributes['nothing']}", bean));
Assert.assertEquals(currentDate, Binder.formatMessage("{el:DATE}", bean));
Assert.assertEquals(tomorrowsDate, Binder.formatMessage("{el:DATE.setLocalDate(DATE.toLocalDate().plusDays(1))}", bean));
Assert.assertEquals(currentTime, Binder.formatMessage("{el:TIME}", bean));
Assert.assertEquals(currentDateTime, Binder.formatMessage("{el:DATETIME}", bean));
Assert.assertEquals(currentTimestamp, Binder.formatMessage("{el:TIMESTAMP}", bean));
Assert.assertEquals("some.non-existent.key", Binder.formatMessage("{i18n:some.non-existent.key}", bean));
Assert.assertEquals("Yes", Binder.formatMessage("{role:admin.BasicUser}", bean));
Assert.assertEquals("Stash", Binder.formatMessage("{stash:text}", bean));
Assert.assertEquals("", Binder.formatMessage("{stash:nothing}", bean));
Assert.assertEquals("Attribute", Binder.formatMessage("{user:text}", bean));
Assert.assertEquals("", Binder.formatMessage("{user:nothing}", bean));
}
@Test
public void testExpressionValidation() throws Exception {
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{USER}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{USERID}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{USERNAME}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{DATAGROUPID}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{CONTACTID}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{CUSTOMER}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{DATE}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{TIME}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{DATETIME}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{TIMESTAMP}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{URL}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{text}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{ text }"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{bean:text}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{bean: text }"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{bean : text }"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{disp:text}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{desc:text}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:bean.text}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:stash['text']}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:user.attributes['text']}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:stash['nothing']}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:user.attributes['nothing']}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:DATE}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:DATE.set(DATE.toLocalDate().plusDays(1))}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:TIME}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:DATETIME}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{el:TIMESTAMP}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{i18n:some.non-existent.key}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{role:admin.BasicUser}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{stash:text}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{stash:nothing}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{user:text}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "{user:nothing}"));
Assert.assertFalse(BindUtil.messageExpressionsAreValid(c, m, aapd, "{"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "}"));
Assert.assertFalse(BindUtil.messageExpressionsAreValid(c, m, aapd, "{}"));
Assert.assertFalse(BindUtil.messageExpressionsAreValid(c, m, aapd, "{text\\}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "\\{text}"));
Assert.assertTrue(BindUtil.messageExpressionsAreValid(c, m, aapd, "\\{{text}"));
}
/**
* Test that a MapBean with a display binding with a dynamic domain defined by no THIS_ALIAS returns code.
*/
@Test
public void testMapBeanWithNoThisReturnsDynamicDomainCode() {
Map<String, Object> properties = new TreeMap<>();
properties.put(Snapshot.queryNamePropertyName, "dynamicDomainValue");
MapBean bean = new MapBean(Snapshot.MODULE_NAME, Snapshot.DOCUMENT_NAME, properties);
Assert.assertEquals("Dynamic domain code value with no THIS_ALIAS should return the code value for a MapBean",
"dynamicDomainValue",
BindUtil.getDisplay(c, bean, Snapshot.queryNamePropertyName));
}
@Test
public void testSanitiseAsFunction() throws Exception {
AllAttributesPersistent aap = Util.constructRandomInstance(u, m, aapd, 2);
aap.setText("Test<script>alert(1)</script>Me");
Assert.assertEquals("Format Message with sanitise function should remove script tag",
"<h1>TestMe</h1>",
BindUtil.formatMessage("<h1>{text}</h1>", displayName -> OWASP.sanitise(Sanitisation.relaxed, displayName), aap));
}
} |
// This file is part of OpenTSDB.
// This program is free software: you can redistribute it and/or modify it
// option) any later version. This program is distributed in the hope that it
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
package net.opentsdb.tsd;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import net.opentsdb.stats.StatsCollector;
/**
* Keeps track of all existing connections.
*/
final class ConnectionManager extends SimpleChannelHandler {
private static final Logger LOG = LoggerFactory.getLogger(ConnectionManager.class);
private static final AtomicLong connections_established = new AtomicLong();
private static final AtomicLong exceptions_caught = new AtomicLong();
private static final DefaultChannelGroup channels =
new DefaultChannelGroup("all-channels");
static void closeAllConnections() {
channels.close().awaitUninterruptibly();
}
/** Constructor. */
public ConnectionManager() {
}
/**
* Collects the stats and metrics tracked by this instance.
* @param collector The collector to use.
*/
public static void collectStats(final StatsCollector collector) {
collector.record("connectionmgr.connections", connections_established);
collector.record("connectionmgr.exceptions", exceptions_caught);
}
@Override
public void channelOpen(final ChannelHandlerContext ctx,
final ChannelStateEvent e) {
channels.add(e.getChannel());
connections_established.incrementAndGet();
}
@Override
public void handleUpstream(final ChannelHandlerContext ctx,
final ChannelEvent e) throws Exception {
if (e instanceof ChannelStateEvent) {
LOG.info(e.toString());
}
super.handleUpstream(ctx, e);
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx,
final ExceptionEvent e) {
final Throwable cause = e.getCause();
final Channel chan = ctx.getChannel();
exceptions_caught.incrementAndGet();
if (cause instanceof ClosedChannelException) {
LOG.warn("Attempt to write to closed channel " + chan);
return;
}
if (cause instanceof IOException) {
final String message = cause.getMessage();
if ("Connection reset by peer".equals(message)
|| "Connection timed out".equals(message)) {
// Do nothing. A client disconnecting isn't really our problem. Oh,
// and I'm not kidding you, there's no better way to detect ECONNRESET
// in Java. Like, people have been bitching about errno for years,
// and Java managed to do something *far* worse. That's quite a feat.
return;
}
}
LOG.error("Unexpected exception from downstream for " + chan, cause);
e.getChannel().close();
}
} |
package ublu.util;
import ublu.Ublu;
import java.util.logging.Level;
import java.util.logging.Logger;
import ublu.command.CommandInterface;
import ublu.command.CommandInterface.COMMANDRESULT;
import ublu.command.CommandMap;
import ublu.util.Generics.UbluProgram;
import ublu.util.Generics.FunctorMap;
import ublu.util.Generics.InterpreterFrameStack;
import ublu.util.Generics.TupleNameList;
import ublu.util.Generics.TupleStack;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.file.Path;
import java.util.Set;
import ublu.util.Generics.ConstMap;
/**
* command interface object
*
* @author jwoehr
*/
public class Interpreter {
private Ublu myUblu;
private DBug myDBug;
private History history;
private String historyFileName;
private ConstMap constMap;
private TupleMap tupleMap;
private CommandMap cmdMap;
private FunctorMap functorMap;
private boolean good_bye;
private int global_ret_val;
private InterpreterFrame interpreterFrame;
private InterpreterFrameStack interpreterFrameStack;
private TupleStack tupleStack;
private boolean break_issued;
private Props props;
private long paramSubIndex = 0;
private int instanceDepth = 0;
/**
* Get the const map
*
* @return the const map
*/
public ConstMap getConstMap() {
return constMap;
}
/**
* Get constant value from the map. Return null if not found.
*
* @param name name of const
* @return the value of const
*/
public String getConst(String name) {
String result = null;
Const theConst = constMap.get(name);
if (theConst != null) {
result = theConst.getValue();
}
return result;
}
/**
* Set constant value in the map. Won't set a Const with a null value. Does
* not prevent a Const in the map from being overwritten, CmdConst checks
* first to make sure no Const of that name exists.
*
* @param name name of const
* @param value value of const
* @return true if const was created and stored to the ConstMap, false if a
* null value was passed in and no Const was created nor stored to the
* ConstMap.
* @see ublu.util.Const
* @see ublu.command.CmdConst
*/
public boolean setConst(String name, String value) {
boolean result = false;
if (Const.isConstName(name) && value != null) {
constMap.put(name, new Const(name, value));
result = true;
}
return result;
}
/**
* Get nested interpreter depth
*
* @return nested interpreter depth
*/
public int getInstanceDepth() {
return instanceDepth;
}
/**
* Get properties
*
* @return properties
*/
public Props getProps() {
return props;
}
/**
* Set properties
*
* @param props properties
*/
protected final void setProps(Props props) {
this.props = props;
}
/**
* Test for a property's being set to string <code>true</code>
*
* @param key
* @return true if set to string <code>true</code>
*/
public boolean isBooleanProperty(String key) {
return getProperty(key, "false").equalsIgnoreCase("true");
}
/**
* Test for a debug subkey's being set to string <code>true</code>. The
* string <code>dbug.</code> is prepended to the subkey.
*
* @param subkey
* @return true if set to string <code>true</code>
*/
public boolean isDBugBooleanProperty(String subkey) {
return isBooleanProperty("dbug." + subkey);
}
/**
* Return autoincrementing parameter substitute naming deus ex machina
*
* @return the value before postincrementation
*/
protected long getParamSubIndex() {
return paramSubIndex++;
}
/**
* BREAK command just popped a frame
*
* @return true if BREAK command just popped a frame
*/
public boolean isBreakIssued() {
return break_issued;
}
/**
* Indicate BREAK command just popped a frame
*
* @param break_issued true if BREAK command just popped a frame
*/
public final void setBreakIssued(boolean break_issued) {
this.break_issued = break_issued;
}
/**
* Return the application instance
*
* @return the application instance
*/
public final Ublu getMyUblu() {
return myUblu;
}
/**
* Set the application instance
*
* @param myUblu the application instance
*/
public final void setMyUblu(Ublu myUblu) {
this.myUblu = myUblu;
}
/**
* Return the logger for this interpreter
*
* @return the logger for this interpreter
*/
public final Logger getLogger() {
return getMyUblu().getLogger();
}
/**
* Get the current input stream to the interpret
*
* @return my input stream
*/
public final InputStream getInputStream() {
return interpreterFrame.getInputStream();
}
/**
* Set the current input stream to the interpret
*
* @param inputStream my input stream
*/
public final void setInputStream(InputStream inputStream) {
interpreterFrame.setInputStream(inputStream);
}
/**
* Get output stream for the interpret
*
* @return output stream for the interpret
*/
public PrintStream getOutputStream() {
return interpreterFrame.getOutputStream();
}
/**
* Set output stream for the interpret
*
* @param outputStream output stream for the interpret
*/
public final void setOutputStream(PrintStream outputStream) {
interpreterFrame.setOutputStream(outputStream);
}
/**
* Get error stream for the interpret
*
* @return error stream for the interpret
*/
public final PrintStream getErroutStream() {
return interpreterFrame.getErroutStream();
}
/**
* Set error stream for the interpret
*
* @param erroutStream error stream for the interpret
*/
public final void setErroutStream(PrintStream erroutStream) {
interpreterFrame.setErroutStream(erroutStream);
}
/**
* Are we currently parsing a quoted string?
*
* @return true if currently parsing a "${" quoted string "}$"
*/
public boolean isParsingString() {
return interpreterFrame.isParsingString();
}
/**
* True if we are currently parsing a quoted string.
*
* @param parsingString set true if currently parsing a "${" quoted string
* "}$"
*/
public final void setParsingString(boolean parsingString) {
interpreterFrame.setParsingString(parsingString);
}
/**
* Are we currently parsing an execution block?
*
* @return true if currently parsing an "$[" execution block "]$"
*/
public boolean isParsingBlock() {
return interpreterFrame.isParsingBlock();
}
/**
* Return parsing block depth
*
* @return parsing block depth
*/
public int getParsingBlockDepth() {
return interpreterFrame.getParsingBlockDepth();
}
/**
* True if we are currently parsing an execution block.
*
* @param parsingBlock set true if currently parsing an "$[" execution block
* "]$"
*/
public void setParsingBlock(boolean parsingBlock) {
interpreterFrame.setParsingBlock(parsingBlock);
}
/**
* Are we currently including a file of commands?
*
* @return true if currently including a file of commands
*/
public boolean isIncluding() {
return interpreterFrame.isIncluding();
}
/**
* Echo lines of include file?
*
* @return true if we should be echoing include lines
*/
public boolean isEchoInclude() {
return getProperty("includes.echo", "true").equalsIgnoreCase("true");
}
/**
* Echo lines of include file?
*
* @param tf
*/
public void setEchoInclude(Boolean tf) {
setProperty("includes.echo", tf.toString());
}
/**
* Should we be prompting?
*
* @return true if we should be prompting
*/
public boolean isPrompting() {
return getProperty("prompting", "true").equalsIgnoreCase("true");
}
/**
* Should we be prompting?
*
* @param tf
*/
public void setPrompting(Boolean tf) {
setProperty("prompting", tf.toString());
}
/**
* Set the status of whether we are currently including a file of commands.
*
* @param including true if currently including a file of commands
*/
public final void setIncluding(boolean including) {
interpreterFrame.setIncluding(including);
}
/**
* Get the basepath of the include file which is including
*
* @return basepath of the include file which is including
*/
public Path getIncludePath() {
return interpreterFrame.getIncludePath();
}
/**
* Set the basepath of the include file which is including
*
* @param includePath basepath of the include file which is including
*/
public void setIncludePath(Path includePath) {
interpreterFrame.setIncludePath(includePath);
}
/**
* Is the current block a FOR block or not?
*
* @return true iff the current block a FOR block
*/
public final boolean isForBlock() {
return interpreterFrame.isForBlock();
}
/**
* Set the current block a FOR block or not.
*
* @param forBlock true if a FOR block
* @return this
*/
public final Interpreter setForBlock(boolean forBlock) {
interpreterFrame.setForBlock(forBlock);
return this;
}
/**
* Get the buffered reader we are using to include a file of commands.
*
* @return the buffered reader we are using to include a file of commands
*/
public BufferedReader getIncludeFileBufferedReader() {
return interpreterFrame.getIncludeFileBufferedReader();
}
/**
* Set the buffered reader we are using to include a file of commands.
*
* @param includeFileBufferedReader the buffered reader we are using to
* include a file of commands
*/
public final void setIncludeFileBufferedReader(BufferedReader includeFileBufferedReader) {
interpreterFrame.setIncludeFileBufferedReader(includeFileBufferedReader);
}
/**
* Get the buffered reader for the input stream when we don't have console
*
* @return the buffered reader for the input stream when we don't have
* console
*/
public BufferedReader getInputStreamBufferedReader() {
return interpreterFrame.getInputStreamBufferedReader();
}
/**
* Set the buffered reader for the input stream when we don't have console
*
* @param inputStreamBufferedReader the buffered reader for the input stream
* when we don't have console
*/
public final void setInputStreamBufferedReader(BufferedReader inputStreamBufferedReader) {
interpreterFrame.setInputStreamBufferedReader(inputStreamBufferedReader);
}
/**
* Get the history file name that will be used next time the history manager
* is instanced.
*
* @return history file name
*/
public final String getHistoryFileName() {
return historyFileName;
}
/**
* Set the history file name that will be used next time the history manager
* is instanced without instancing history file
*
* @param historyFileName history file name
*/
public final void setHistoryFileName(String historyFileName) {
this.historyFileName = historyFileName;
}
/**
* Get the history manager
*
* @return the history manager
*/
public History getHistory() {
return history;
}
/**
* Set the history manager
*
* @param history the history manager
*/
public final void setHistory(History history) {
this.history = history;
}
/**
* Close the history file.
*/
public final void closeHistory() {
try {
if (getHistory() != null) {
getHistory().close();
setHistory(null);
}
} catch (IOException ex) {
getLogger().log(Level.WARNING, "Error closing history file", ex);
}
}
/**
* Close any old history file and open a new one with the name we have set
* via {@link #setHistoryFileName(String)}.
*
*/
public final void instanceHistory() {
closeHistory();
try {
setHistory(new History(this, getHistoryFileName()));
} catch (IOException ex) {
getLogger().log(Level.WARNING, "Could not open history file", ex);
}
}
/**
* A return value for the interpret, not currently used.
*
* @return the global return value
*/
public int getGlobal_ret_val() {
return global_ret_val;
}
/**
* A return value for the interpret, not currently used.
*
* @param global_ret_val the global return value
*/
public final void setGlobal_ret_val(int global_ret_val) {
this.global_ret_val = global_ret_val;
}
/**
* Signals the interpret to exit
*
* @return true is we're done
*/
public boolean isGoodBye() {
return good_bye;
}
/**
* Signals the interpret to exit
*
* @param good_bye true if we're done
*/
public final void setGoodBye(boolean good_bye) {
this.good_bye = good_bye;
}
/**
* The argument array of lexes from input
*
* @return my arg array
*/
public final ArgArray getArgArray() {
return interpreterFrame.getArgArray();
}
/**
* The argument array of lexes from input
*
* @param argArray my arg array
*/
public final void setArgArray(ArgArray argArray) {
interpreterFrame.setArgArray(argArray);
}
/**
* The map of key-value pairs used as tuple variables in Ublu
*
* @return The map of key-value pairs
*/
public final TupleMap getTupleMap() {
return tupleMap;
}
/**
* The map of key-value pairs used as tuple variables in Ublu
*
* @param tupleMap The map of key-value pairs
*/
protected final void setTupleMap(TupleMap tupleMap) {
this.tupleMap = tupleMap;
}
/**
* Get the tuple var assigned to a key
*
* @param key
* @return the tuple var assigned to a key
*/
public Tuple getTuple(String key) {
return tupleMap.getTuple(key);
}
/**
* Get the tuple var assigned to a key but don't check local map
*
* @param key
* @return the tuple var assigned to a key
*/
public Tuple getTupleNoLocal(String key) {
return tupleMap.getTupleNoLocal(key);
}
/**
* Put a tuple to the most local map
*
* @param t the tuple
* @return the tuple
*/
public Tuple putTupleMostLocal(Tuple t) {
return tupleMap.putTupleMostLocal(t);
}
/**
* Set a tuple var from a key and a value
*
* @param key tuple key
* @param value tuple object value
* @return the tuple which was created or set
*/
public Tuple setTuple(String key, Object value) {
return tupleMap.setTuple(key, value);
}
/**
* Set a tuple var from a key and a value but only in global map
*
* @param key tuple key
* @param value tuple object value
* @return the tuple which was created or set
*/
public Tuple setTupleNoLocal(String key, Object value) {
return tupleMap.setTupleNoLocal(key, value);
}
/**
* Delete a tuple from the map
*
* @param key the string key identifying the tuple
* @return the object value of the deleted tuple
*/
public Object deleteTuple(String key) {
return tupleMap.deleteTuple(key);
}
/**
* Remove a tuple from the tuple map
*
* @param t the tuple to remove
* @return the tuple's object value
*/
public Object deleteTuple(Tuple t) {
tupleMap.deleteTuple(t);
return t.getValue();
}
/**
* Get the map of commands
*
* @return the map of commands
*/
public final CommandMap getCmdMap() {
return cmdMap;
}
/**
* Set the map of commands
*
* @param cmdMap the map of commands
*/
protected final void setCmdMap(CommandMap cmdMap) {
this.cmdMap = cmdMap;
}
/**
* Get the command object matching the name
*
* @param i
* @param cmdName name of command
* @return the command object corresponding to the name
*/
public CommandInterface getCmd(Interpreter i, String cmdName) {
return getCmdMap().getCmd(i, cmdName);
}
/**
* Local function dictionary
*
* @return Local function dictionary
*/
public FunctorMap getFunctorMap() {
return functorMap;
}
/**
* Local function dictionary
*
* @param functorMap Local function dictionary
*/
public final void setFunctorMap(FunctorMap functorMap) {
this.functorMap = functorMap;
}
/**
* Add named function to dictionary
*
* @param name name of function
* @param f functor
*/
public void addFunctor(String name, Functor f) {
getFunctorMap().put(name, f);
}
/**
* Get named functor from dictionary
*
* @param name name of function
* @return the functor
*/
public Functor getFunctor(String name) {
return getFunctorMap().get(name);
}
/**
* True if name is in dictionary
*
* @param name name of function
* @return true iff name is in dictionary
*/
public boolean hasFunctor(String name) {
return getFunctorMap().containsKey(name);
}
/**
* Get the tuple stack
*
* @return the tuple stack
*/
public TupleStack getTupleStack() {
return tupleStack;
}
/**
* Set the tuple stack
*
* @param tupleStack the tuple stack
*/
public final void setTupleStack(TupleStack tupleStack) {
this.tupleStack = tupleStack;
}
/**
* Do we have a console (or are we reading from a stream)?
*
* @return true if console active
*/
public boolean isConsole() {
return System.console() != null && getInputStream() == System.in;
}
/**
* Instance with args ready for the {@link #interpret} to start its first
* {@link #loop}.
*
* @param args arguments at invocation, effectively just another command
* line
* @param ublu the associated instance
*/
public Interpreter(String[] args, Ublu ublu) {
this(ublu);
setArgArray(new ArgArray(this, args));
}
/**
* Instance with the application controller and passed-in args (commands)
* set.
*
* @param args passed-in args (commands)
* @param ublu the application controller
*/
public Interpreter(String args, Ublu ublu) {
this(ublu);
setArgArray(new Parser(this, args).parseAnArgArray());
}
/**
* Instance with only the application controller set
*
* @param ublu the application controller
*/
public Interpreter(Ublu ublu) {
this();
setMyUblu(ublu);
}
/**
* Copy ctor creates Interpreter with same maps i/o.
*
* @param i interpreter to be copied
*/
public Interpreter(Interpreter i) {
this();
instanceDepth = i.instanceDepth + 1;
setInputStream(i.getInputStream());
setInputStreamBufferedReader(i.getInputStreamBufferedReader());
setErroutStream(i.getErroutStream());
setOutputStream(i.getOutputStream());
setTupleMap(i.getTupleMap());
setCmdMap(i.getCmdMap());
setFunctorMap(i.getFunctorMap());
setHistoryFileName(i.getHistoryFileName());
setMyUblu(i.getMyUblu());
setProps(i.getProps());
constMap = new ConstMap(i.constMap);
}
/**
* Copy ctor New instance spawned from another instance with args passed in
*
* @param i Instance to spawn from
* @param args the args
*/
public Interpreter(Interpreter i, String args) {
this(i);
setArgArray(new Parser(this, args).parseAnArgArray());
}
/**
* Initialize internals such as tuple map to store variables.
*/
protected Interpreter() {
interpreterFrame = new InterpreterFrame();
interpreterFrameStack = new InterpreterFrameStack();
setTupleStack(new TupleStack());
setInputStream(System.in);
setInputStreamBufferedReader(new BufferedReader(new InputStreamReader(getInputStream())));
setErroutStream(System.err);
setOutputStream(System.out);
setTupleMap(new TupleMap());
setCmdMap(new CommandMap());
setFunctorMap(new FunctorMap());
setParsingString(false);
setForBlock(false);
setBreakIssued(false);
setIncluding(false);
setIncludeFileBufferedReader(null);
setHistoryFileName(History.DEFAULT_HISTORY_FILENAME);
setGlobal_ret_val(0);
setGoodBye(false);
props = new Props();
myDBug = new DBug(this);
constMap = new ConstMap();
}
/**
* Get dbug instance
*
* @return the DBug instance
*/
public DBug dbug() {
return myDBug;
}
/**
*
* @param filepath
* @throws FileNotFoundException
* @throws IOException
*/
public void readProps(String filepath) throws FileNotFoundException, IOException {
props.readIn(filepath);
}
/**
*
* @param filepath
* @param comment
* @throws FileNotFoundException
* @throws IOException
*/
public void writeProps(String filepath, String comment) throws FileNotFoundException, IOException {
props.writeOut(filepath, comment);
}
/**
* get a property
*
* @param key
* @return the property
*/
public String getProperty(String key) {
return props.get(key);
}
/**
* get Property return a default value if non
*
* @param key sought
* @param defaultValue default
* @return value
*/
public final String getProperty(String key, String defaultValue) {
return props.get(key, defaultValue);
}
/**
* Set key to value
*
* @param key key
* @param value value
*/
public void setProperty(String key, String value) {
props.set(key, value);
}
/**
* Get set of keys
*
* @return set of keys
*/
public Set propertyKeys() {
return props.keySet();
}
/**
* Push a new local tuple map
*/
public void pushLocal() {
getTupleMap().pushLocal();
}
/**
* Pop the local tuple map
*/
public void popLocal() {
getTupleMap().popLocal();
}
/**
* Push an interpreter frame
*
* @return this
*/
public Interpreter pushFrame() {
InterpreterFrame newFrame = new InterpreterFrame(interpreterFrame);
interpreterFrameStack.push(interpreterFrame);
getTupleMap().pushLocal();
interpreterFrame = newFrame;
return this;
}
/**
* Pop interpreter frame
*
* @return this
*/
public Interpreter popFrame() {
interpreterFrame = interpreterFrameStack.pop();
getTupleMap().popLocal();
// if (getTupleMap().getLocalMap() != null) {
// getTupleMap().setLocalMap(null);
return this;
}
/**
* How many frames have been pushed?
*
* @return How many frames have been pushed
*/
public int frameDepth() {
return interpreterFrameStack.size();
}
/**
* Print a string to out
*
* @param s to print
*/
public void output(String s) {
getOutputStream().print(s);
}
/**
* Print a string and a newline to out
*
* @param s to print
*/
public void outputln(String s) {
getOutputStream().println(s);
}
/**
* Print a string to err
*
* @param s to print
*/
public void outputerr(String s) {
getErroutStream().print(s);
}
/**
* Print a string and a newline to err
*
* @param s to print
*/
public void outputerrln(String s) {
getErroutStream().println(s);
}
/**
* Execute a block
*
* @param block the block to execute
* @return command result
*/
public COMMANDRESULT executeBlock(String block) {
COMMANDRESULT rc;
pushFrame();
Parser p = new Parser(this, block);
setArgArray(p.parseAnArgArray());
rc = loop();
popFrame();
return rc;
}
/**
* Create a tuple name list from the param array to a function
*
* @return tuple name list from the param array to a function
*/
public TupleNameList parseTupleNameList() {
TupleNameList tnl = null;
if (!getArgArray().peekNext().equals("(")) {
getLogger().log(Level.SEVERE, "Missing ( parameter list ) function call.");
} else {
getArgArray().next(); // discard "("
tnl = new TupleNameList();
while (!getArgArray().peekNext().equals(")")) {
tnl.add(getArgArray().next());
}
getArgArray().next(); // discard ")"
}
return tnl;
}
/**
* Execute a functor
*
* @param f the functor
* @param tupleNames list of names to sub for params
* @return command result
*/
public COMMANDRESULT executeFunctor(Functor f, TupleNameList tupleNames) {
COMMANDRESULT rc;
if (tupleNames.size() != f.numParams()) {
getLogger().log(Level.SEVERE, "Unable to execute functor {0}\n which needs {1} params but received {2}", new Object[]{f, f.numParams(), tupleNames.toString()});
rc = COMMANDRESULT.FAILURE;
} else {
// rc = executeBlock(f.bind(tupleNames.delifoize(this)));
// getTupleMap().pushLocal();
pushFrame();
String block = f.bindWithSubstitutes(this, tupleNames/*.delifoize(this)*/);
rc = executeBlock(block);
// getTupleMap().popLocal();
popFrame();
}
return rc;
}
/**
* Show one function in a code re-usable form
*
* @param funcName function to show
* @return the function in a code re-usable form
*/
public String showFunction(String funcName) {
return getFunctorMap().showFunction(funcName);
}
/**
* List all named functions
*
* @return String describing all known functions
*/
public String listFunctions() {
return getFunctorMap().listFunctions();
}
/**
* Remove a function from the dictionary
*
* @param name function name
* @return boolean if was found (and removed)
*/
public boolean deleteFunction(String name) {
return getFunctorMap().deleteFunction(name);
}
/**
* The processing loop, processes all the input for a line until exhausted
* or until a command returns a command result indicating failure.
*
* @return the last command result indicating success or failure.
*/
public COMMANDRESULT loop() {
COMMANDRESULT lastCommandResult = COMMANDRESULT.SUCCESS;
String initialCommandLine = getArgArray().toHistoryLine();
while (!getArgArray().isEmpty() && !good_bye && !isBreakIssued()) {
String commandName = getArgArray().next().trim();
if (commandName.equals("")) {
continue; // cr or some sort of whitespace got parsed, skip to next
}
if (getCmdMap().containsKey(commandName)) {
CommandInterface command = getCmd(this, commandName);
try {
setArgArray(command.cmd(getArgArray()));
lastCommandResult = command.getResult();
if (lastCommandResult == COMMANDRESULT.FAILURE) {
break; // we exit the loop on error
}
} catch (IllegalArgumentException ex) {
getLogger().log(Level.SEVERE, "Command \"" + commandName + "\" threw exception", ex);
lastCommandResult = COMMANDRESULT.FAILURE;
break;
} catch (java.lang.RuntimeException ex) {
/* java.net.UnknownHostException lands here, as well as */
getLogger().log(Level.SEVERE, "Command \"" + commandName + "\" threw exception", ex);
lastCommandResult = COMMANDRESULT.FAILURE;
break;
}
} else if (getFunctorMap().containsKey(commandName)) {
try {
TupleNameList tnl = parseTupleNameList();
if (tnl != null) {
lastCommandResult = executeFunctor(getFunctor(commandName), tnl);
if (lastCommandResult == COMMANDRESULT.FAILURE) {
break;
}
} else {
getLogger().log(Level.SEVERE, "Found function {0} but could not execute it", commandName);
lastCommandResult = COMMANDRESULT.FAILURE;
break;
}
} catch (java.lang.RuntimeException ex) {
getLogger().log(Level.SEVERE, "Function \"" + commandName + "\" threw exception", ex);
lastCommandResult = COMMANDRESULT.FAILURE;
break;
}
} else {
getLogger().log(Level.SEVERE, "Command \"{0}\" not found.", commandName);
lastCommandResult = COMMANDRESULT.FAILURE;
break;
}
}
if (!isIncluding() && !initialCommandLine.isEmpty()) {
if (getHistory() != null) {
try {
getHistory().writeLine(initialCommandLine);
} catch (IOException ex) {
getLogger().log(Level.WARNING, "Couldn't write to history file " + getHistory().getHistoryFileName(), ex);
}
}
}
setGlobal_ret_val(lastCommandResult.ordinal());
return lastCommandResult;
}
/**
* Include a program already parsed into lines
*
* @param api400prog an instance of a an array of lines to be treated as a
* program
* @return the command result
*/
public COMMANDRESULT include(UbluProgram api400prog) {
setIncluding(true);
COMMANDRESULT commandResult = COMMANDRESULT.SUCCESS;
for (String line : api400prog) {
if (isEchoInclude()) {
getErroutStream().println(":: " + line);
}
if (!line.isEmpty()) {
ArgArray aa = new Parser(this, line).parseAnArgArray();
setArgArray(aa);
commandResult = loop();
if (commandResult == COMMANDRESULT.FAILURE) {
break;
}
}
}
setIncluding(false);
return commandResult;
}
/**
* Read in a text file and execute as commands
*
* @param filepath Path to the file of commands
* @return last command result
* @throws FileNotFoundException
* @throws IOException
*/
public COMMANDRESULT include(Path filepath) throws FileNotFoundException, IOException {
pushFrame();
Path currentIncludePath = getIncludePath();
if (currentIncludePath != null) {
filepath = currentIncludePath.resolve(filepath.normalize());
}
setIncludePath(filepath.getParent());
setIncluding(true);
COMMANDRESULT commandResult = COMMANDRESULT.SUCCESS;
File file = filepath.normalize().toFile();
try (FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader)) {
setIncludeFileBufferedReader(bufferedReader);
while (getIncludeFileBufferedReader().ready()) {
String input = getIncludeFileBufferedReader().readLine();
if (isEchoInclude()) {
getErroutStream().println(":: " + input);
}
if (!input.isEmpty()) {
ArgArray aa = new Parser(this, input).parseAnArgArray();
setArgArray(aa);
commandResult = loop();
if (commandResult == COMMANDRESULT.FAILURE) {
break;
}
}
}
}
setIncludeFileBufferedReader(null);
setIncluding(false);
popFrame();
return commandResult;
}
/**
* Read a line, parse its whitespace-separated lexes into an
* {@link ublu.util.ArgArray}.
*
* @return the {@link ublu.util.ArgArray} thus parsed
*/
public ArgArray readAndParse() {
String input = null;
ArgArray aa = new ArgArray(this);
if (isIncluding()) {
try {
if (getIncludeFileBufferedReader() != null) {
if (getIncludeFileBufferedReader().ready()) {
input = getIncludeFileBufferedReader().readLine();
if (isParsingString() || isParsingBlock()) {
if (isPrompting()) {
outputerrln(input);
}
}
}
} else {
setIncluding(false);
input = ""; // so we won't exit on file failure because input == null;
}
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "IO error reading included file", ex);
}
} else if (isConsole()) {
input = System.console().readLine();
} else { // we're reading from the input stream
try {
input = getInputStreamBufferedReader().readLine();
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Error reading interpreter input from input stream", ex);
}
}
if (input != null) {
input = input.trim();
aa = new Parser(this, input).parseAnArgArray();
} else {
setGoodBye(true);
}
setArgArray(aa);
return getArgArray();
}
/**
* interactive loop until bye
*
* @return a global return value from the interpret loop
*/
public int interpret() {
while (!isGoodBye()) {
prompt();
readAndParse();
loop();
if (isGoodBye() && isConsole() && instanceDepth == 0) {
outputerrln("Goodbye!");
}
}
return getGlobal_ret_val();
}
/**
* Prompt the user for input. Usually just a <tt>></tt> sign, but when
* parsing a multiline <tt>${ quoted string }$</tt> an intermediate
* continuation prompt of <tt>${</tt>
*/
public void prompt() {
if (isPrompting()) {
StringBuilder sb = new StringBuilder(instanceDepth == 0 ? "" : Integer.toString(instanceDepth)).append("> ");
String thePrompt = sb.toString();
if (isParsingString()) {
thePrompt = "(${) ";
}
if (isParsingBlock()) {
sb = new StringBuilder().append('(');
for (int i = 0; i < getParsingBlockDepth(); i++) {
sb.append("$[");
}
sb.append(") ");
thePrompt = sb.toString();
}
if (isConsole()) {
outputerr(thePrompt);
}
}
}
} |
package udo.testdriver;
import static org.loadui.testfx.Assertions.verifyThat;
import static org.loadui.testfx.controls.Commons.hasText;
import java.io.IOException;
import java.io.RandomAccessFile;
import javafx.scene.Parent;
import javafx.scene.input.KeyCode;
import org.junit.runners.MethodSorters;
import org.junit.FixMethodOrder;
import org.junit.BeforeClass;
import org.junit.Test;
import org.loadui.testfx.GuiTest;
import org.loadui.testfx.utils.FXTestUtils;
import udo.gui.Gui;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestFx {
private static GuiTest controller;
private static Gui ju;
@BeforeClass
public static void setUpClass() {
removeExistingTasks();
FXTestUtils.launchApp(Gui.class);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// here is that closure I talked about above, you instantiate the
// getRootNode abstract method
// which requires you to return a 'parent' object, luckily for us,
// getRoot() gives a parent!
// getRoot() is available from ALL Node objects, which makes it easy.
controller = new GuiTest() {
@Override
protected Parent getRootNode() {
return ju.getPrimaryStage().getScene().getRoot();
}
};
}
private static void removeExistingTasks() {
try {
(new RandomAccessFile("tasks.json", "rws")).setLength(0);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void test1() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
controller.type("New task");
controller.push(KeyCode.ENTER);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
verifyThat("#_status",
hasText("Task: New task added successfully"));
}
@Test
public void test2() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
controller.type("Delete 2");
controller.push(KeyCode.ENTER);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
verifyThat("#_status",
hasText("Error: specified task's index is not valid"));
}
@Test
public void test3() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
controller.push(KeyCode.DOWN);
controller.type("Delete 1");
controller.push(KeyCode.ENTER);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
verifyThat("#_status",
hasText("Task: New task deleted successfully"));
}
@Test
public void test4() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
controller.type("Undo");
controller.push(KeyCode.ENTER);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
verifyThat("#_status",
hasText("Undo completed"));
}
@Test
public void test5() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
controller.type("Undo");
controller.push(KeyCode.ENTER);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
verifyThat("#_status",
hasText("Error: no more operation to undo"));
}
@Test
public void test6() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
controller.push(KeyCode.DOWN);
controller.type("Mod");
controller.push(KeyCode.TAB);
controller.type(" 1 Date with Emma Watson /dl 5pm");
controller.push(KeyCode.ENTER);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
verifyThat("#_status",
hasText("Task: Date with Emma Watson modified successfully"));
}
@Test
public void test7() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
controller.push(KeyCode.UP);
for(int i=0; i<7; i++) {
controller.push(KeyCode.BACK_SPACE);
}
controller.type("and talk with Bill Gates /s 5pm /e 9pm");
controller.push(KeyCode.ENTER);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
verifyThat("#_status",
hasText("Task: Date with Emma Watson and talk with Bill... modified successfully"));
}
@Test
public void test8() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
controller.push(KeyCode.DOWN);
controller.type("sea");
controller.push(KeyCode.TAB);
controller.type(" /fr");
controller.push(KeyCode.TAB);
controller.push(KeyCode.ENTER);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
verifyThat("#_status",
hasText("Search results for free slots"));
}
} |
package com.openxc.sinks;
import java.util.HashSet;
import java.util.Set;
import android.util.Log;
import com.google.common.base.Objects;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.openxc.NoValueException;
import com.openxc.measurements.BaseMeasurement;
import com.openxc.measurements.Measurement;
import com.openxc.measurements.UnrecognizedMeasurementTypeException;
import com.openxc.messages.KeyMatcher;
import com.openxc.messages.KeyedMessage;
import com.openxc.messages.SimpleVehicleMessage;
import com.openxc.messages.VehicleMessage;
/**
* A data sink that sends new measurements of specific types to listeners.
*
* Applications requesting asynchronous updates for specific signals get their
* values through this sink.
*/
public class MessageListenerSink extends AbstractQueuedCallbackSink {
private final static String TAG = "MessageListenerSink";
private Multimap<KeyMatcher, VehicleMessage.Listener>
mPersistentMessageListeners = HashMultimap.create();
// The non-persistent listeners will be removed after they receive their
// first message.
private Multimap<KeyMatcher, VehicleMessage.Listener>
mMessageListeners = HashMultimap.create();
private Multimap<Class<? extends Measurement>, Measurement.Listener>
mMeasurementTypeListeners = HashMultimap.create();
private Multimap<Class<? extends VehicleMessage>, VehicleMessage.Listener>
mMessageTypeListeners = HashMultimap.create();
public MessageListenerSink() {
super();
}
public synchronized void register(KeyMatcher matcher,
VehicleMessage.Listener listener, boolean persist) {
if(persist) {
mPersistentMessageListeners.put(matcher, listener);
} else {
mMessageListeners.put(matcher, listener);
}
}
public synchronized void register(KeyMatcher matcher,
VehicleMessage.Listener listener) {
register(matcher, listener, true);
}
public synchronized void register(
Class<? extends VehicleMessage> messageType,
VehicleMessage.Listener listener) {
mMessageTypeListeners.put(messageType, listener);
}
public void register(Class<? extends Measurement> measurementType,
Measurement.Listener listener) {
try {
// A bit of a hack to cache this measurement's ID field so we
// can deserialize incoming measurements of this type. Why don't we
// have a getId() in the Measurement interface? Ah, because it would
// have to be static and you can't have static methods in an
// interface. It would work if we were passed an instance of the
// measurement in this function, but we don't really have that when
// adding a listener.
BaseMeasurement.getKeyForMeasurement(measurementType);
} catch(UnrecognizedMeasurementTypeException e) { }
mMeasurementTypeListeners.put(measurementType, listener);
}
public synchronized void unregister(
Class<? extends Measurement> measurementType,
Measurement.Listener listener) {
mMeasurementTypeListeners.remove(measurementType, listener);
}
public synchronized void unregister(
Class<? extends VehicleMessage> messageType,
VehicleMessage.Listener listener) {
mMessageTypeListeners.remove(messageType, listener);
}
public synchronized void unregister(KeyMatcher matcher,
VehicleMessage.Listener listener) {
mPersistentMessageListeners.remove(matcher, listener);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("numMessageListeners", mMessageListeners.size())
.add("numMessageTypeListeners", mMessageTypeListeners.size())
.add("numPersistentMessageListeners",
mPersistentMessageListeners.size())
.add("numMeasurementTypeListeners", mMeasurementTypeListeners.size())
.toString();
}
@Override
protected synchronized void propagateMessage(VehicleMessage message) {
if(message instanceof KeyedMessage) {
for (KeyMatcher matcher : mPersistentMessageListeners.keys()) {
if (matcher.matches(message.asKeyedMessage())) {
for (VehicleMessage.Listener listener :
mPersistentMessageListeners.get(matcher)) {
listener.receive(message);
}
}
}
Set<KeyMatcher> matchedKeys = new HashSet<>();
for (KeyMatcher matcher : mMessageListeners.keys()) {
if (matcher.matches(message.asKeyedMessage())) {
for (VehicleMessage.Listener listener :
mMessageListeners.get(matcher)) {
listener.receive(message);
}
matchedKeys.add(matcher);
}
}
for(KeyMatcher matcher : matchedKeys) {
mMessageListeners.removeAll(matcher);
}
if (message instanceof SimpleVehicleMessage) {
propagateMeasurementFromMessage(message.asSimpleMessage());
}
}
if(mMessageTypeListeners.containsKey(message.getClass())) {
for(VehicleMessage.Listener listener :
mMessageTypeListeners.get(message.getClass())) {
listener.receive(message);
}
}
}
private synchronized void propagateMeasurementFromMessage(
SimpleVehicleMessage message) {
try {
Measurement measurement =
BaseMeasurement.getMeasurementFromMessage(message);
if(mMeasurementTypeListeners.containsKey(measurement.getClass())) {
for(Measurement.Listener listener :
mMeasurementTypeListeners.get(measurement.getClass())) {
listener.receive(measurement);
}
}
} catch(UnrecognizedMeasurementTypeException e) {
// The message is not a recognized Measurement, we don't propagate
// it as a Measurement (only as a Message, which is handled
// earlier).
} catch(NoValueException e) {
Log.w(TAG, "Received notification for a blank measurement", e);
}
}
} |
package view;
import controller.CellSocietyController;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
public class SimulationScreen {
private CellSocietyController myController;
private int myWidth;
private int myHeight;
private HBox myTop;
private GridPane myGridPane;
/**
* This function begins setting up the general simulation scene. This includes things like adding the four buttons
* at the top that load, step through, speed up, and stop/start the simulation. Note: all strings used to create
* buttons must be retrieved from a .properties file. Right now I have them hard coded into the program.
* @returns a scene
*/
public Scene initSimScreen(int width, int height){
BorderPane root = new BorderPane();
myWidth = width;
myHeight = height;
myGridPane = new GridPane();
//myController = new CellSocietyController(width, height);
root.setTop(addButtons());
root.setCenter(myGridPane);
return new Scene(root, width, height, Color.WHITE);
}
private HBox addButtons() {
myTop = new HBox();
myTop.getChildren().addAll(addLoadButton(), addStepButton(), addSpeedUpButton(), addStopStartButton());
double length = myTop.getChildren().size();
double buttonWidth = myTop.getChildren().get(0).getLayoutBounds().getWidth();
myTop.setSpacing((myWidth - length * buttonWidth) / (length + 1));
return myTop;
}
/**
* This function adds the load button to the scene and creates the eventListener.
* @return Button that loads new file
*/
private Button addLoadButton(){
Button loadButton = new Button("Load");
loadButton.setOnAction(e -> {
//myController.transitionToFileLoaderScreen();
});
return loadButton;
}
/**
* This function adds the step button to the scene and creates the eventListener.
*/
private Button addStepButton(){
Button stepButton = new Button ("Step");
stepButton.setOnAction(e-> {
//myController.stepThroughSimulation();
});
return stepButton;
}
/**
* Adds speed up button
*/
private Button addSpeedUpButton(){
Button speedUpButton = new Button("Speed Up");
speedUpButton.setOnAction(e -> {
//myController.speedUpSimulation();
});
return speedUpButton;
}
/**
* adds stop.start button
* @return
*/
private Button addStopStartButton(){
Button stopStartButton = new Button("Stop/Start");
stopStartButton.setOnAction(e -> {
//myController.stopOrStart();
});
return stopStartButton;
}
/**
* must be passed a grid of some type so that it can determine the colors of each square
* It will then go through each square and set its appropriate color
* @param colorGrid
*/
public void updateScreen(Color[][] colorGrid){
for(int j = 0; j < colorGrid.length; j++){
for(int i = 0; i < colorGrid[0].length; i++){
//get color and update square with that color
getChild(j, i).setFill(colorGrid[j][i]);
}
}
}
/**
* goes through myGridPane and creates a new rectangle object at each spot in the grid
* @param gridHeight
* @param gridWidth
*/
public void initSimView(int gridHeight, int gridWidth){
System.out.println("here");
for(int j = 0; j < gridHeight; j++){
for(int i = 0; i < gridWidth; i++){
Rectangle rect = new Rectangle(myWidth/gridWidth,
(myHeight - myTop.getLayoutBounds().getHeight())/gridHeight);
rect.setFill(Color.BLACK);
rect.setStroke(Color.BLACK);
myGridPane.add(rect, i, j);
}
}
}
private Shape getChild(int row, int column){
for(Node child: myGridPane.getChildren()){
if(GridPane.getRowIndex(child) == row && GridPane.getColumnIndex(child) == column){
//trust me, it will be a rectangle...
return (Shape) child;
}
}
System.out.println("error, getChild() method not working");
return null;
}
} |
package com.jbooktrader.platform.web;
import com.jbooktrader.platform.model.*;
import com.jbooktrader.platform.performance.*;
import com.jbooktrader.platform.position.*;
import com.jbooktrader.platform.startup.*;
import com.jbooktrader.platform.strategy.*;
import com.jbooktrader.platform.util.*;
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.text.*;
public class WebHandler implements HttpHandler {
private static final String WEBROOT = "resources/web";
public void handle(HttpExchange httpExchange) throws IOException {
String requestURI = httpExchange.getRequestURI().toString().trim();
String userAgent = httpExchange.getRequestHeaders().getFirst("User-Agent");
Boolean iPhone = userAgent.contains("iPhone");
StringBuilder sb = new StringBuilder();
// The page...
if (requestURI.equalsIgnoreCase("/") || requestURI.equalsIgnoreCase("/index.html")) {
// We'll respond to any unknown request with the main page
sb.append("<!DOCTYPE HTML PUBLIC \"-
sb.append("<html>\n");
sb.append("<head>\n");
sb.append("<title>JBookTrader Web Console</title>\n");
if (iPhone) {
sb.append("<link rel=\"apple-touch-icon\" href=\"apple-touch-icon.png\" />\n");
sb.append("<meta name=\"viewport\" content=\"width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\" />\n");
sb.append("<link media=\"screen\" rel=\"stylesheet\" type=\"text/css\" href=\"iPhone.css\" />\n");
sb.append("<script type=\"application/x-javascript\" src=\"iPhone.js\"></script> \n");
}
else {
sb.append("<link media=\"screen\" rel=\"stylesheet\" type=\"text/css\" href=\"stylesheet.css\" />\n");
}
String modeString = "";
if (Dispatcher.getMode().toString() == "Trade") { modeString = "Trading"; }
else if (Dispatcher.getMode().toString() == "Optimization") { modeString = "Optimizing"; }
else modeString = Dispatcher.getMode() + "ing";
sb.append("</head>\n");
sb.append("<body>\n");
sb.append("<h1>\n");
sb.append(JBookTrader.APP_NAME).append(" : ").append(modeString);
sb.append("</h1>\n");
sb.append("<table>");
sb.append("<tr><th>Strategy</th><th>Position</th><th>Trades</th><th>Max DD</th><th>Net Profit</th></tr>");
DecimalFormat df = NumberFormatterFactory.getNumberFormatter(0);
double totalPNL = 0.0;
for (Strategy strategy : Dispatcher.getTrader().getAssistant().getAllStrategies()) {
PositionManager positionManager = strategy.getPositionManager();
PerformanceManager performanceManager = strategy.getPerformanceManager();
totalPNL += performanceManager.getNetProfit();
sb.append("<tr>\n");
sb.append("<td>").append(strategy.getName()).append("</td>");
sb.append("<td align=\"right\">").append(positionManager.getPosition()).append("</td>");
sb.append("<td align=\"right\">").append(performanceManager.getTrades()).append("</td>");
sb.append("<td align=\"right\">").append(df.format(performanceManager.getMaxDrawdown())).append("</td>");
sb.append("<td align=\"right\">").append(df.format(performanceManager.getNetProfit())).append("</td>\n");
sb.append("</tr>\n");
}
sb.append("<tr><td class=\"summary\" colspan=\"4\">Summary</td>");
sb.append("<td class=\"summary\" style=\"text-align: right\">").append(df.format(totalPNL)).append("</td>\n");
sb.append("</table>\n");
sb.append("<p class=\"version\">JBookTrader version ").append(JBookTrader.VERSION).append("</p>\n");
sb.append("</body>\n");
sb.append("</html>\n");
}
// This handles static files...
else if (
requestURI.toLowerCase().contains(".png") ||
requestURI.toLowerCase().contains(".jpg") ||
requestURI.toLowerCase().contains(".gif") ||
requestURI.toLowerCase().contains(".ico") ||
requestURI.toLowerCase().contains(".css") ||
requestURI.toLowerCase().contains(".js")) {
try {
handleFile(httpExchange, requestURI);
}
catch (Exception e) {
e.printStackTrace();
}
return;
}
// Huh?
else {
sb.append("File not found");
String response = sb.toString();
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
return;
}
String response = sb.toString();
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
/**
* Handles HTTP requests for files (images, css, js, etc.)
* The files must reside in resources/web/
*
* @param httpExchange
* @param requestURI
* @throws IOException
*/
private void handleFile(HttpExchange httpExchange, String requestURI) throws IOException {
StringBuilder resource = new StringBuilder(WEBROOT).append(requestURI);
if (requestURI.toLowerCase().contains(".png")) {
httpExchange.getResponseHeaders().set("Content-Type", "image/png;charset=utf-8");
}
else if (requestURI.toLowerCase().contains(".ico")) {
httpExchange.getResponseHeaders().set("Content-Type", "image/x-ico;charset=utf-8");
}
else if (requestURI.toLowerCase().contains(".jpg")) {
httpExchange.getResponseHeaders().set("Content-Type", "image/jpeg;charset=utf-8");
}
else if (requestURI.toLowerCase().contains(".gif")) {
httpExchange.getResponseHeaders().set("Content-Type", "image/gif;charset=utf-8");
}
else if (requestURI.toLowerCase().contains(".css")) {
httpExchange.getResponseHeaders().set("Content-Type", "text/css;charset=utf-8");
}
else if (requestURI.toLowerCase().contains(".js")) {
httpExchange.getResponseHeaders().set("Content-Type", "text/javascript;charset=utf-8");
}
else {
httpExchange.getResponseHeaders().set("Content-Type", "application/octet-stream;charset=utf-8");
}
long fileLength = 0;
try {
File temp = new File(resource.toString());
fileLength = temp.length();
}
catch(Exception e) {
System.out.println(e);
}
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, fileLength);
OutputStream responseBody = httpExchange.getResponseBody();
try {
FileInputStream file = new FileInputStream(resource.toString());
BufferedInputStream bis = new BufferedInputStream(file);
byte buffer[] = new byte[8192];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1)
responseBody.write(buffer, 0, bytesRead);
bis.close();
}
catch (Exception e) {
System.out.println(e);
}
finally {
responseBody.flush();
responseBody.close();
}
return;
}
} |
package org.jfree.data.general;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jfree.data.DomainInfo;
import org.jfree.data.KeyToGroupMap;
import org.jfree.data.KeyedValues;
import org.jfree.data.Range;
import org.jfree.data.RangeInfo;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.function.Function2D;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.util.ArrayUtilities;
/**
* A collection of useful static methods relating to datasets.
*/
public final class DatasetUtilities {
/**
* Private constructor for non-instanceability.
*/
private DatasetUtilities() {
// now try to instantiate this ;-)
}
/**
* Calculates the total of all the values in a {@link PieDataset}. If
* the dataset contains negative or <code>null</code> values, they are
* ignored.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The total.
*/
public static double calculatePieDatasetTotal(PieDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
List keys = dataset.getKeys();
double totalValue = 0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable current = (Comparable) iterator.next();
if (current != null) {
Number value = dataset.getValue(current);
double v = 0.0;
if (value != null) {
v = value.doubleValue();
}
if (v > 0) {
totalValue = totalValue + v;
}
}
}
return totalValue;
}
/**
* Creates a pie dataset from a table dataset by taking all the values
* for a single row.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param rowKey the row key.
*
* @return A pie dataset.
*/
public static PieDataset createPieDatasetForRow(CategoryDataset dataset,
Comparable rowKey) {
int row = dataset.getRowIndex(rowKey);
return createPieDatasetForRow(dataset, row);
}
/**
* Creates a pie dataset from a table dataset by taking all the values
* for a single row.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param row the row (zero-based index).
*
* @return A pie dataset.
*/
public static PieDataset createPieDatasetForRow(CategoryDataset dataset,
int row) {
DefaultPieDataset result = new DefaultPieDataset();
int columnCount = dataset.getColumnCount();
for (int current = 0; current < columnCount; current++) {
Comparable columnKey = dataset.getColumnKey(current);
result.setValue(columnKey, dataset.getValue(row, current));
}
return result;
}
/**
* Creates a pie dataset from a table dataset by taking all the values
* for a single column.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param columnKey the column key.
*
* @return A pie dataset.
*/
public static PieDataset createPieDatasetForColumn(CategoryDataset dataset,
Comparable columnKey) {
int column = dataset.getColumnIndex(columnKey);
return createPieDatasetForColumn(dataset, column);
}
/**
* Creates a pie dataset from a {@link CategoryDataset} by taking all the
* values for a single column.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param column the column (zero-based index).
*
* @return A pie dataset.
*/
public static PieDataset createPieDatasetForColumn(CategoryDataset dataset,
int column) {
DefaultPieDataset result = new DefaultPieDataset();
int rowCount = dataset.getRowCount();
for (int i = 0; i < rowCount; i++) {
Comparable rowKey = dataset.getRowKey(i);
result.setValue(rowKey, dataset.getValue(i, column));
}
return result;
}
/**
* Creates a new pie dataset based on the supplied dataset, but modified
* by aggregating all the low value items (those whose value is lower
* than the <code>percentThreshold</code>) into a single item with the
* key "Other".
*
* @param source the source dataset (<code>null</code> not permitted).
* @param key a new key for the aggregated items (<code>null</code> not
* permitted).
* @param minimumPercent the percent threshold.
*
* @return The pie dataset with (possibly) aggregated items.
*/
public static PieDataset createConsolidatedPieDataset(PieDataset source,
Comparable key, double minimumPercent) {
return DatasetUtilities.createConsolidatedPieDataset(source, key,
minimumPercent, 2);
}
/**
* Creates a new pie dataset based on the supplied dataset, but modified
* by aggregating all the low value items (those whose value is lower
* than the <code>percentThreshold</code>) into a single item. The
* aggregated items are assigned the specified key. Aggregation only
* occurs if there are at least <code>minItems</code> items to aggregate.
*
* @param source the source dataset (<code>null</code> not permitted).
* @param key the key to represent the aggregated items.
* @param minimumPercent the percent threshold (ten percent is 0.10).
* @param minItems only aggregate low values if there are at least this
* many.
*
* @return The pie dataset with (possibly) aggregated items.
*/
public static PieDataset createConsolidatedPieDataset(PieDataset source,
Comparable key, double minimumPercent, int minItems) {
DefaultPieDataset result = new DefaultPieDataset();
double total = DatasetUtilities.calculatePieDatasetTotal(source);
// Iterate and find all keys below threshold percentThreshold
List keys = source.getKeys();
ArrayList otherKeys = new ArrayList();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable currentKey = (Comparable) iterator.next();
Number dataValue = source.getValue(currentKey);
if (dataValue != null) {
double value = dataValue.doubleValue();
if (value / total < minimumPercent) {
otherKeys.add(currentKey);
}
}
}
// Create new dataset with keys above threshold percentThreshold
iterator = keys.iterator();
double otherValue = 0;
while (iterator.hasNext()) {
Comparable currentKey = (Comparable) iterator.next();
Number dataValue = source.getValue(currentKey);
if (dataValue != null) {
if (otherKeys.contains(currentKey)
&& otherKeys.size() >= minItems) {
// Do not add key to dataset
otherValue += dataValue.doubleValue();
}
else {
// Add key to dataset
result.setValue(currentKey, dataValue);
}
}
}
// Add other category if applicable
if (otherKeys.size() >= minItems) {
result.setValue(key, otherValue);
}
return result;
}
public static CategoryDataset createCategoryDataset(String rowKeyPrefix,
String columnKeyPrefix, double[][] data) {
DefaultCategoryDataset result = new DefaultCategoryDataset();
for (int r = 0; r < data.length; r++) {
String rowKey = rowKeyPrefix + (r + 1);
for (int c = 0; c < data[r].length; c++) {
String columnKey = columnKeyPrefix + (c + 1);
result.addValue(new Double(data[r][c]), rowKey, columnKey);
}
}
return result;
}
public static CategoryDataset createCategoryDataset(String rowKeyPrefix,
String columnKeyPrefix, Number[][] data) {
DefaultCategoryDataset result = new DefaultCategoryDataset();
for (int r = 0; r < data.length; r++) {
String rowKey = rowKeyPrefix + (r + 1);
for (int c = 0; c < data[r].length; c++) {
String columnKey = columnKeyPrefix + (c + 1);
result.addValue(data[r][c], rowKey, columnKey);
}
}
return result;
}
/**
* Creates a {@link CategoryDataset} that contains a copy of the data in
* an array (instances of <code>Double</code> are created to represent the
* data items).
* <p>
* Row and column keys are taken from the supplied arrays.
*
* @param rowKeys the row keys (<code>null</code> not permitted).
* @param columnKeys the column keys (<code>null</code> not permitted).
* @param data the data.
*
* @return The dataset.
*/
public static CategoryDataset createCategoryDataset(Comparable[] rowKeys,
Comparable[] columnKeys, double[][] data) {
// check arguments...
if (rowKeys == null) {
throw new IllegalArgumentException("Null 'rowKeys' argument.");
}
if (columnKeys == null) {
throw new IllegalArgumentException("Null 'columnKeys' argument.");
}
if (ArrayUtilities.hasDuplicateItems(rowKeys)) {
throw new IllegalArgumentException("Duplicate items in 'rowKeys'.");
}
if (ArrayUtilities.hasDuplicateItems(columnKeys)) {
throw new IllegalArgumentException(
"Duplicate items in 'columnKeys'.");
}
if (rowKeys.length != data.length) {
throw new IllegalArgumentException(
"The number of row keys does not match the number of rows in "
+ "the data array.");
}
int columnCount = 0;
for (int r = 0; r < data.length; r++) {
columnCount = Math.max(columnCount, data[r].length);
}
if (columnKeys.length != columnCount) {
throw new IllegalArgumentException(
"The number of column keys does not match the number of "
+ "columns in the data array.");
}
// now do the work...
DefaultCategoryDataset result = new DefaultCategoryDataset();
for (int r = 0; r < data.length; r++) {
Comparable rowKey = rowKeys[r];
for (int c = 0; c < data[r].length; c++) {
Comparable columnKey = columnKeys[c];
result.addValue(new Double(data[r][c]), rowKey, columnKey);
}
}
return result;
}
/**
* Creates a {@link CategoryDataset} by copying the data from the supplied
* {@link KeyedValues} instance.
*
* @param rowKey the row key (<code>null</code> not permitted).
* @param rowData the row data (<code>null</code> not permitted).
*
* @return A dataset.
*/
public static CategoryDataset createCategoryDataset(Comparable rowKey,
KeyedValues rowData) {
if (rowKey == null) {
throw new IllegalArgumentException("Null 'rowKey' argument.");
}
if (rowData == null) {
throw new IllegalArgumentException("Null 'rowData' argument.");
}
DefaultCategoryDataset result = new DefaultCategoryDataset();
for (int i = 0; i < rowData.getItemCount(); i++) {
result.addValue(rowData.getValue(i), rowKey, rowData.getKey(i));
}
return result;
}
/**
* Creates an {@link XYDataset} by sampling the specified function over a
* fixed range.
*
* @param f the function (<code>null</code> not permitted).
* @param start the start value for the range.
* @param end the end value for the range.
* @param samples the number of sample points (must be > 1).
* @param seriesKey the key to give the resulting series
* (<code>null</code> not permitted).
*
* @return A dataset.
*/
public static XYDataset sampleFunction2D(Function2D f, double start,
double end, int samples, Comparable seriesKey) {
if (f == null) {
throw new IllegalArgumentException("Null 'f' argument.");
}
if (seriesKey == null) {
throw new IllegalArgumentException("Null 'seriesKey' argument.");
}
if (start >= end) {
throw new IllegalArgumentException("Requires 'start' < 'end'.");
}
if (samples < 2) {
throw new IllegalArgumentException("Requires 'samples' > 1");
}
XYSeries series = new XYSeries(seriesKey);
double step = (end - start) / (samples - 1);
for (int i = 0; i < samples; i++) {
double x = start + (step * i);
series.add(x, f.getValue(x));
}
XYSeriesCollection collection = new XYSeriesCollection(series);
return collection;
}
/**
* Returns <code>true</code> if the dataset is empty (or <code>null</code>),
* and <code>false</code> otherwise.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean isEmptyOrNull(PieDataset dataset) {
if (dataset == null) {
return true;
}
int itemCount = dataset.getItemCount();
if (itemCount == 0) {
return true;
}
for (int item = 0; item < itemCount; item++) {
Number y = dataset.getValue(item);
if (y != null) {
double yy = y.doubleValue();
if (yy > 0.0) {
return false;
}
}
}
return true;
}
/**
* Returns <code>true</code> if the dataset is empty (or <code>null</code>),
* and <code>false</code> otherwise.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean isEmptyOrNull(CategoryDataset dataset) {
if (dataset == null) {
return true;
}
int rowCount = dataset.getRowCount();
int columnCount = dataset.getColumnCount();
if (rowCount == 0 || columnCount == 0) {
return true;
}
for (int r = 0; r < rowCount; r++) {
for (int c = 0; c < columnCount; c++) {
if (dataset.getValue(r, c) != null) {
return false;
}
}
}
return true;
}
/**
* Returns <code>true</code> if the dataset is empty (or <code>null</code>),
* and <code>false</code> otherwise.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean isEmptyOrNull(XYDataset dataset) {
if (dataset != null) {
for (int s = 0; s < dataset.getSeriesCount(); s++) {
if (dataset.getItemCount(s) > 0) {
return false;
}
}
}
return true;
}
/**
* Returns the range of values in the domain (x-values) of a dataset.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range of values (possibly <code>null</code>).
*/
public static Range findDomainBounds(XYDataset dataset) {
return findDomainBounds(dataset, true);
}
/**
* Returns the range of values in the domain (x-values) of a dataset.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval determines whether or not the x-interval is taken
* into account (only applies if the dataset is an
* {@link IntervalXYDataset}).
*
* @return The range of values (possibly <code>null</code>).
*/
public static Range findDomainBounds(XYDataset dataset,
boolean includeInterval) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
Range result = null;
// if the dataset implements DomainInfo, life is easier
if (dataset instanceof DomainInfo) {
DomainInfo info = (DomainInfo) dataset;
result = info.getDomainBounds(includeInterval);
}
else {
result = iterateDomainBounds(dataset, includeInterval);
}
return result;
}
/**
* Iterates over the items in an {@link XYDataset} to find
* the range of x-values. If the dataset is an instance of
* {@link IntervalXYDataset}, the starting and ending x-values
* will be used for the bounds calculation.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*/
public static Range iterateDomainBounds(XYDataset dataset) {
return iterateDomainBounds(dataset, true);
}
/**
* Iterates over the items in an {@link XYDataset} to find
* the range of x-values.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines, for an
* {@link IntervalXYDataset}, whether the x-interval or just the
* x-value is used to determine the overall range.
*
* @return The range (possibly <code>null</code>).
*/
public static Range iterateDomainBounds(XYDataset dataset,
boolean includeInterval) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
double lvalue;
double uvalue;
if (includeInterval && dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset;
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
lvalue = intervalXYData.getStartXValue(series, item);
uvalue = intervalXYData.getEndXValue(series, item);
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
}
if (!Double.isNaN(uvalue)) {
maximum = Math.max(maximum, uvalue);
}
}
}
}
else {
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
lvalue = dataset.getXValue(series, item);
uvalue = lvalue;
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
maximum = Math.max(maximum, uvalue);
}
}
}
}
if (minimum > maximum) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Returns the range of values in the range for the dataset.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*/
public static Range findRangeBounds(CategoryDataset dataset) {
return findRangeBounds(dataset, true);
}
/**
* Returns the range of values in the range for the dataset.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range (possibly <code>null</code>).
*/
public static Range findRangeBounds(CategoryDataset dataset,
boolean includeInterval) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
Range result = null;
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
result = info.getRangeBounds(includeInterval);
}
else {
result = iterateRangeBounds(dataset, includeInterval);
}
return result;
}
/**
* Returns the range of values in the range for the dataset. This method
* is the partner for the {@link #findDomainBounds(XYDataset)} method.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*/
public static Range findRangeBounds(XYDataset dataset) {
return findRangeBounds(dataset, true);
}
/**
* Returns the range of values in the range for the dataset. This method
* is the partner for the {@link #findDomainBounds(XYDataset, boolean)}
* method.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range (possibly <code>null</code>).
*/
public static Range findRangeBounds(XYDataset dataset,
boolean includeInterval) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
Range result = null;
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
result = info.getRangeBounds(includeInterval);
}
else {
result = iterateRangeBounds(dataset, includeInterval);
}
return result;
}
/**
* Iterates over the data item of the category dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range (possibly <code>null</code>).
*
* @deprecated As of 1.0.10, use
* {@link #iterateRangeBounds(CategoryDataset, boolean)}.
*/
public static Range iterateCategoryRangeBounds(CategoryDataset dataset,
boolean includeInterval) {
return iterateRangeBounds(dataset, includeInterval);
}
/**
* Iterates over the data item of the category dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*
* @since 1.0.10
*/
public static Range iterateRangeBounds(CategoryDataset dataset) {
return iterateRangeBounds(dataset, true);
}
/**
* Iterates over the data item of the category dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range (possibly <code>null</code>).
*
* @since 1.0.10
*/
public static Range iterateRangeBounds(CategoryDataset dataset,
boolean includeInterval) {
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int rowCount = dataset.getRowCount();
int columnCount = dataset.getColumnCount();
if (includeInterval && dataset instanceof IntervalCategoryDataset) {
// handle the special case where the dataset has y-intervals that
// we want to measure
IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset;
Number lvalue, uvalue;
for (int row = 0; row < rowCount; row++) {
for (int column = 0; column < columnCount; column++) {
lvalue = icd.getStartValue(row, column);
uvalue = icd.getEndValue(row, column);
if (lvalue != null && !Double.isNaN(lvalue.doubleValue())) {
minimum = Math.min(minimum, lvalue.doubleValue());
}
if (uvalue != null && !Double.isNaN(uvalue.doubleValue())) {
maximum = Math.max(maximum, uvalue.doubleValue());
}
}
}
}
else {
// handle the standard case (plain CategoryDataset)
for (int row = 0; row < rowCount; row++) {
for (int column = 0; column < columnCount; column++) {
Number value = dataset.getValue(row, column);
if (value != null) {
double v = value.doubleValue();
if (!Double.isNaN(v)) {
minimum = Math.min(minimum, v);
maximum = Math.max(maximum, v);
}
}
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Iterates over the data item of the xy dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*
* @deprecated As of 1.0.10, use {@link #iterateRangeBounds(XYDataset)}.
*/
public static Range iterateXYRangeBounds(XYDataset dataset) {
return iterateRangeBounds(dataset);
}
/**
* Iterates over the data item of the xy dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*
* @since 1.0.10
*/
public static Range iterateRangeBounds(XYDataset dataset) {
return iterateRangeBounds(dataset, true);
}
/**
* Iterates over the data items of the xy dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines, for an
* {@link IntervalXYDataset}, whether the y-interval or just the
* y-value is used to determine the overall range.
*
* @return The range (possibly <code>null</code>).
*
* @since 1.0.10
*/
public static Range iterateRangeBounds(XYDataset dataset,
boolean includeInterval) {
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
// handle three cases by dataset type
if (includeInterval && dataset instanceof IntervalXYDataset) {
// handle special case of IntervalXYDataset
IntervalXYDataset ixyd = (IntervalXYDataset) dataset;
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double lvalue = ixyd.getStartYValue(series, item);
double uvalue = ixyd.getEndYValue(series, item);
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
}
if (!Double.isNaN(uvalue)) {
maximum = Math.max(maximum, uvalue);
}
}
}
}
else if (includeInterval && dataset instanceof OHLCDataset) {
// handle special case of OHLCDataset
OHLCDataset ohlc = (OHLCDataset) dataset;
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double lvalue = ohlc.getLowValue(series, item);
double uvalue = ohlc.getHighValue(series, item);
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
}
if (!Double.isNaN(uvalue)) {
maximum = Math.max(maximum, uvalue);
}
}
}
}
else {
// standard case - plain XYDataset
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value = dataset.getYValue(series, item);
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
maximum = Math.max(maximum, value);
}
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Finds the minimum domain (or X) value for the specified dataset. This
* is easy if the dataset implements the {@link DomainInfo} interface (a
* good idea if there is an efficient way to determine the minimum value).
* Otherwise, it involves iterating over the entire data-set.
* <p>
* Returns <code>null</code> if all the data values in the dataset are
* <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The minimum value (possibly <code>null</code>).
*/
public static Number findMinimumDomainValue(XYDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
Number result = null;
// if the dataset implements DomainInfo, life is easy
if (dataset instanceof DomainInfo) {
DomainInfo info = (DomainInfo) dataset;
return new Double(info.getDomainLowerBound(true));
}
else {
double minimum = Double.POSITIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value;
if (dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData
= (IntervalXYDataset) dataset;
value = intervalXYData.getStartXValue(series, item);
}
else {
value = dataset.getXValue(series, item);
}
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
result = null;
}
else {
result = new Double(minimum);
}
}
return result;
}
/**
* Returns the maximum domain value for the specified dataset. This is
* easy if the dataset implements the {@link DomainInfo} interface (a good
* idea if there is an efficient way to determine the maximum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values in the dataset are
* <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The maximum value (possibly <code>null</code>).
*/
public static Number findMaximumDomainValue(XYDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
Number result = null;
// if the dataset implements DomainInfo, life is easy
if (dataset instanceof DomainInfo) {
DomainInfo info = (DomainInfo) dataset;
return new Double(info.getDomainUpperBound(true));
}
// hasn't implemented DomainInfo, so iterate...
else {
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value;
if (dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData
= (IntervalXYDataset) dataset;
value = intervalXYData.getEndXValue(series, item);
}
else {
value = dataset.getXValue(series, item);
}
if (!Double.isNaN(value)) {
maximum = Math.max(maximum, value);
}
}
}
if (maximum == Double.NEGATIVE_INFINITY) {
result = null;
}
else {
result = new Double(maximum);
}
}
return result;
}
/**
* Returns the minimum range value for the specified dataset. This is
* easy if the dataset implements the {@link RangeInfo} interface (a good
* idea if there is an efficient way to determine the minimum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values in the dataset are
* <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The minimum value (possibly <code>null</code>).
*/
public static Number findMinimumRangeValue(CategoryDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
return new Double(info.getRangeLowerBound(true));
}
// hasn't implemented RangeInfo, so we'll have to iterate...
else {
double minimum = Double.POSITIVE_INFINITY;
int seriesCount = dataset.getRowCount();
int itemCount = dataset.getColumnCount();
for (int series = 0; series < seriesCount; series++) {
for (int item = 0; item < itemCount; item++) {
Number value;
if (dataset instanceof IntervalCategoryDataset) {
IntervalCategoryDataset icd
= (IntervalCategoryDataset) dataset;
value = icd.getStartValue(series, item);
}
else {
value = dataset.getValue(series, item);
}
if (value != null) {
minimum = Math.min(minimum, value.doubleValue());
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Double(minimum);
}
}
}
/**
* Returns the minimum range value for the specified dataset. This is
* easy if the dataset implements the {@link RangeInfo} interface (a good
* idea if there is an efficient way to determine the minimum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values in the dataset are
* <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The minimum value (possibly <code>null</code>).
*/
public static Number findMinimumRangeValue(XYDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
// work out the minimum value...
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
return new Double(info.getRangeLowerBound(true));
}
// hasn't implemented RangeInfo, so we'll have to iterate...
else {
double minimum = Double.POSITIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value;
if (dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData
= (IntervalXYDataset) dataset;
value = intervalXYData.getStartYValue(series, item);
}
else if (dataset instanceof OHLCDataset) {
OHLCDataset highLowData = (OHLCDataset) dataset;
value = highLowData.getLowValue(series, item);
}
else {
value = dataset.getYValue(series, item);
}
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Double(minimum);
}
}
}
/**
* Returns the maximum range value for the specified dataset. This is easy
* if the dataset implements the {@link RangeInfo} interface (a good idea
* if there is an efficient way to determine the maximum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values are <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The maximum value (possibly <code>null</code>).
*/
public static Number findMaximumRangeValue(CategoryDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
// work out the minimum value...
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
return new Double(info.getRangeUpperBound(true));
}
// hasn't implemented RangeInfo, so we'll have to iterate...
else {
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getRowCount();
int itemCount = dataset.getColumnCount();
for (int series = 0; series < seriesCount; series++) {
for (int item = 0; item < itemCount; item++) {
Number value;
if (dataset instanceof IntervalCategoryDataset) {
IntervalCategoryDataset icd
= (IntervalCategoryDataset) dataset;
value = icd.getEndValue(series, item);
}
else {
value = dataset.getValue(series, item);
}
if (value != null) {
maximum = Math.max(maximum, value.doubleValue());
}
}
}
if (maximum == Double.NEGATIVE_INFINITY) {
return null;
}
else {
return new Double(maximum);
}
}
}
/**
* Returns the maximum range value for the specified dataset. This is
* easy if the dataset implements the {@link RangeInfo} interface (a good
* idea if there is an efficient way to determine the maximum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values are <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The maximum value (possibly <code>null</code>).
*/
public static Number findMaximumRangeValue(XYDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
// work out the minimum value...
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
return new Double(info.getRangeUpperBound(true));
}
// hasn't implemented RangeInfo, so we'll have to iterate...
else {
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value;
if (dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData
= (IntervalXYDataset) dataset;
value = intervalXYData.getEndYValue(series, item);
}
else if (dataset instanceof OHLCDataset) {
OHLCDataset highLowData = (OHLCDataset) dataset;
value = highLowData.getHighValue(series, item);
}
else {
value = dataset.getYValue(series, item);
}
if (!Double.isNaN(value)) {
maximum = Math.max(maximum, value);
}
}
}
if (maximum == Double.NEGATIVE_INFINITY) {
return null;
}
else {
return new Double(maximum);
}
}
}
/**
* Returns the minimum and maximum values for the dataset's range
* (y-values), assuming that the series in one category are stacked.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (<code>null</code> if the dataset contains no values).
*/
public static Range findStackedRangeBounds(CategoryDataset dataset) {
return findStackedRangeBounds(dataset, 0.0);
}
/**
* Returns the minimum and maximum values for the dataset's range
* (y-values), assuming that the series in one category are stacked.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param base the base value for the bars.
*
* @return The range (<code>null</code> if the dataset contains no values).
*/
public static Range findStackedRangeBounds(CategoryDataset dataset,
double base) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
Range result = null;
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int categoryCount = dataset.getColumnCount();
for (int item = 0; item < categoryCount; item++) {
double positive = base;
double negative = base;
int seriesCount = dataset.getRowCount();
for (int series = 0; series < seriesCount; series++) {
Number number = dataset.getValue(series, item);
if (number != null) {
double value = number.doubleValue();
if (value > 0.0) {
positive = positive + value;
}
if (value < 0.0) {
negative = negative + value;
// '+', remember value is negative
}
}
}
minimum = Math.min(minimum, negative);
maximum = Math.max(maximum, positive);
}
if (minimum <= maximum) {
result = new Range(minimum, maximum);
}
return result;
}
/**
* Returns the minimum and maximum values for the dataset's range
* (y-values), assuming that the series in one category are stacked.
*
* @param dataset the dataset.
* @param map a structure that maps series to groups.
*
* @return The value range (<code>null</code> if the dataset contains no
* values).
*/
public static Range findStackedRangeBounds(CategoryDataset dataset,
KeyToGroupMap map) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
boolean hasValidData = false;
Range result = null;
// create an array holding the group indices for each series...
int[] groupIndex = new int[dataset.getRowCount()];
for (int i = 0; i < dataset.getRowCount(); i++) {
groupIndex[i] = map.getGroupIndex(map.getGroup(
dataset.getRowKey(i)));
}
// minimum and maximum for each group...
int groupCount = map.getGroupCount();
double[] minimum = new double[groupCount];
double[] maximum = new double[groupCount];
int categoryCount = dataset.getColumnCount();
for (int item = 0; item < categoryCount; item++) {
double[] positive = new double[groupCount];
double[] negative = new double[groupCount];
int seriesCount = dataset.getRowCount();
for (int series = 0; series < seriesCount; series++) {
Number number = dataset.getValue(series, item);
if (number != null) {
hasValidData = true;
double value = number.doubleValue();
if (value > 0.0) {
positive[groupIndex[series]]
= positive[groupIndex[series]] + value;
}
if (value < 0.0) {
negative[groupIndex[series]]
= negative[groupIndex[series]] + value;
// '+', remember value is negative
}
}
}
for (int g = 0; g < groupCount; g++) {
minimum[g] = Math.min(minimum[g], negative[g]);
maximum[g] = Math.max(maximum[g], positive[g]);
}
}
if (hasValidData) {
for (int j = 0; j < groupCount; j++) {
result = Range.combine(result, new Range(minimum[j],
maximum[j]));
}
}
return result;
}
/**
* Returns the minimum value in the dataset range, assuming that values in
* each category are "stacked".
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The minimum value.
*
* @see #findMaximumStackedRangeValue(CategoryDataset)
*/
public static Number findMinimumStackedRangeValue(CategoryDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
Number result = null;
boolean hasValidData = false;
double minimum = 0.0;
int categoryCount = dataset.getColumnCount();
for (int item = 0; item < categoryCount; item++) {
double total = 0.0;
int seriesCount = dataset.getRowCount();
for (int series = 0; series < seriesCount; series++) {
Number number = dataset.getValue(series, item);
if (number != null) {
hasValidData = true;
double value = number.doubleValue();
if (value < 0.0) {
total = total + value;
// '+', remember value is negative
}
}
}
minimum = Math.min(minimum, total);
}
if (hasValidData) {
result = new Double(minimum);
}
return result;
}
/**
* Returns the maximum value in the dataset range, assuming that values in
* each category are "stacked".
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The maximum value (possibly <code>null</code>).
*
* @see #findMinimumStackedRangeValue(CategoryDataset)
*/
public static Number findMaximumStackedRangeValue(CategoryDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
Number result = null;
boolean hasValidData = false;
double maximum = 0.0;
int categoryCount = dataset.getColumnCount();
for (int item = 0; item < categoryCount; item++) {
double total = 0.0;
int seriesCount = dataset.getRowCount();
for (int series = 0; series < seriesCount; series++) {
Number number = dataset.getValue(series, item);
if (number != null) {
hasValidData = true;
double value = number.doubleValue();
if (value > 0.0) {
total = total + value;
}
}
}
maximum = Math.max(maximum, total);
}
if (hasValidData) {
result = new Double(maximum);
}
return result;
}
/**
* Returns the minimum and maximum values for the dataset's range,
* assuming that the series are stacked.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range ([0.0, 0.0] if the dataset contains no values).
*/
public static Range findStackedRangeBounds(TableXYDataset dataset) {
return findStackedRangeBounds(dataset, 0.0);
}
/**
* Returns the minimum and maximum values for the dataset's range,
* assuming that the series are stacked, using the specified base value.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param base the base value.
*
* @return The range (<code>null</code> if the dataset contains no values).
*/
public static Range findStackedRangeBounds(TableXYDataset dataset,
double base) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
double minimum = base;
double maximum = base;
for (int itemNo = 0; itemNo < dataset.getItemCount(); itemNo++) {
double positive = base;
double negative = base;
int seriesCount = dataset.getSeriesCount();
for (int seriesNo = 0; seriesNo < seriesCount; seriesNo++) {
double y = dataset.getYValue(seriesNo, itemNo);
if (!Double.isNaN(y)) {
if (y > 0.0) {
positive += y;
}
else {
negative += y;
}
}
}
if (positive > maximum) {
maximum = positive;
}
if (negative < minimum) {
minimum = negative;
}
}
if (minimum <= maximum) {
return new Range(minimum, maximum);
}
else {
return null;
}
}
/**
* Calculates the total for the y-values in all series for a given item
* index.
*
* @param dataset the dataset.
* @param item the item index.
*
* @return The total.
*
* @since 1.0.5
*/
public static double calculateStackTotal(TableXYDataset dataset, int item) {
double total = 0.0;
int seriesCount = dataset.getSeriesCount();
for (int s = 0; s < seriesCount; s++) {
double value = dataset.getYValue(s, item);
if (!Double.isNaN(value)) {
total = total + value;
}
}
return total;
}
/**
* Calculates the range of values for a dataset where each item is the
* running total of the items for the current series.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range.
*
* @see #findRangeBounds(CategoryDataset)
*/
public static Range findCumulativeRangeBounds(CategoryDataset dataset) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
boolean allItemsNull = true; // we'll set this to false if there is at
// least one non-null data item...
double minimum = 0.0;
double maximum = 0.0;
for (int row = 0; row < dataset.getRowCount(); row++) {
double runningTotal = 0.0;
for (int column = 0; column <= dataset.getColumnCount() - 1;
column++) {
Number n = dataset.getValue(row, column);
if (n != null) {
allItemsNull = false;
double value = n.doubleValue();
if (!Double.isNaN(value)) {
runningTotal = runningTotal + value;
minimum = Math.min(minimum, runningTotal);
maximum = Math.max(maximum, runningTotal);
}
}
}
}
if (!allItemsNull) {
return new Range(minimum, maximum);
}
else {
return null;
}
}
} |
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import uk.co.uwcs.choob.modules.Modules;
import uk.co.uwcs.choob.support.ChoobBadSyntaxError;
import uk.co.uwcs.choob.support.IRCInterface;
import uk.co.uwcs.choob.support.events.*;
/**
* Fun (live) stats for all the family.
*
* @author Faux
*/
class EntityStat
{
public int id;
public String statName;
public String entityName;
//String chan; // ???
public double value; // WMA; over 100 lines for people, 1000 lines for channels
}
class StatSortByValue implements Comparator<EntityStat>
{
public int compare(EntityStat o1, EntityStat o2) {
if (o1.value > o2.value) {
return -1;
}
if (o1.value < o2.value) {
return 1;
}
return 0;
}
@Override
public boolean equals(Object obj) {
return false;
}
}
public class Stats
{
final int HISTORY = 1000;
final double NICK_LENGTH = 100; // "Significant" lines in WMA calculations.
final double CHAN_LENGTH = 1000;
final double THRESHOLD = 0.005; // val * THRESHOLD is considered too small to be a part of WMA.
final double NICK_ALPHA = Math.exp(Math.log(THRESHOLD) / NICK_LENGTH);
final double CHAN_ALPHA = Math.exp(Math.log(THRESHOLD) / CHAN_LENGTH);
public String[] info()
{
return new String[] {
"Plugin for analysing speech.",
"The Choob Team",
"choob@uwcs.co.uk",
"$Rev$$Date$"
};
}
private Modules mods;
private IRCInterface irc;
public Stats(Modules mods, IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
}
/*
public void commandSpammers( Message mes )
{
List<Message> history = mods.history.getLastMessages( mes, HISTORY );
Map<String, Integer> scores = new HashMap<String, Integer>();
for (Message m : history)
{
final String nick = mods.nick.getBestPrimaryNick(m.getNick());
Integer i = scores.get(nick);
if (i == null)
{
// frikkin' immutable integers
}
}
*/
private void update( String thing, Message mes, double thisVal )
{
if ( mes instanceof ChannelEvent )
updateObj( thing, mes.getContext(), thisVal, CHAN_ALPHA );
updateObj( thing, mods.nick.getBestPrimaryNick( mes.getNick() ), thisVal, NICK_ALPHA );
}
private void updateObj ( String thing, String name, double thisVal, double alpha )
{
// I assume thing is safe. ^.^
List<EntityStat> ret = mods.odb.retrieve( EntityStat.class, "WHERE entityName = \"" + mods.odb.escapeString(name) + "\" && statName = \"" + thing + "\"");
EntityStat obj;
if (ret.size() == 0) {
obj = new EntityStat();
obj.statName = thing;
obj.entityName = name;
obj.value = thisVal;
mods.odb.save(obj);
} else {
obj = ret.get(0);
obj.value = alpha * obj.value + (1 - alpha) * thisVal;
mods.odb.update(obj);
}
}
public void onMessage( Message mes )
{
if (Pattern.compile(irc.getTriggerRegex()).matcher(mes.getMessage()).find()) {
// Ignore commands.
return;
}
String content = mes.getMessage().replaceAll("^[a-zA-Z0-9`_|]+:\\s+", "");
boolean referred = !content.equals(mes.getMessage());
if (mes instanceof ActionEvent) {
content = "*" + mes.getNick() + " " + content; // bizarrely, this is proper captuation grammar.
}
if (Pattern.compile("^<\\S+>").matcher(content).find()) {
// Ignore quotes, too.
return;
}
try {
update( "captuation", mes, apiCaptuation( content ) );
int wc = apiWordCount( content );
update( "wordcount", mes, wc );
update( "characters", mes, apiLength( content ) );
if (wc > 0)
update( "wordlength", mes, apiWordLength( content ) );
update( "referred", mes, referred ? 1.0 : 0.0 );
} catch (Exception e) {
// FAIL!
}
}
public String[] helpCommandGet = {
"Get stat(s) about some person or channel.",
"<Entity> [ <Stat> ]",
"<Entity> is the name of the channel or person to get stats for",
"<Stat> is the optional name of a specific statistic to get (omit it to get all of them)"
};
public void commandGet( Message mes )
{
String[] params = mods.util.getParamArray(mes);
if (params.length == 3) {
String nick = mods.nick.getBestPrimaryNick( params[1] );
String thing = params[2].toLowerCase();
List<EntityStat> ret = mods.odb.retrieve( EntityStat.class, "WHERE entityName = \"" + mods.odb.escapeString(nick) + "\" && statName = \"" + mods.odb.escapeString(thing) + "\"");
EntityStat obj;
if (ret.size() == 0) {
irc.sendContextReply( mes, "Sorry, cannae find datta one." );
} else {
obj = ret.get(0);
irc.sendContextReply( mes, "They be 'avin a score of " + Math.round(obj.value * 100) / 100.0 );
}
} else if (params.length == 2) {
String nick = mods.nick.getBestPrimaryNick( params[1] );
List<EntityStat> ret = mods.odb.retrieve( EntityStat.class, "WHERE entityName = \"" + mods.odb.escapeString(nick) + "\"");
if (ret.size() == 0) {
irc.sendContextReply( mes, "Sorry, cannae find datta one." );
} else {
StringBuilder results = new StringBuilder( "Stats:" );
for (EntityStat obj: ret) {
results.append( " " + obj.statName + " = " + Math.round(obj.value * 100) / 100.0 + ";" );
}
irc.sendContextReply( mes, results.toString() );
}
} else {
throw new ChoobBadSyntaxError();
}
}
public String[] helpCommandList = {
"Gets statistics about an entire channel.",
"<Channel> <Stat>",
"<Channel> is the name of the channel get statistics for",
"<Stat> is the optional name of a specific statistic to get (omit it to get all of them)"
};
public void commandList(Message mes)
{
String[] params = mods.util.getParamArray(mes);
if ((params.length < 3) || (params.length > 3)) {
throw new ChoobBadSyntaxError();
}
String channel = params[1];
String stat = params[2].toLowerCase();
List<String> channelMembers = irc.getUsersList(channel);
List<EntityStat> stats = new ArrayList<EntityStat>();
for (int i = 0; i < channelMembers.size(); i++) {
List<EntityStat> datas = mods.odb.retrieve(EntityStat.class, "WHERE entityName = \"" + mods.odb.escapeString(channelMembers.get(i)) + "\" && statName = \"" + mods.odb.escapeString(stat) + "\"");
if (datas.size() == 0) continue;
stats.add(datas.get(0));
}
if (stats.size() == 0) {
irc.sendContextReply(mes, "No data found for \"" + stat + "\" in \"" + channel + "\".");
return;
}
Collections.sort(stats, new StatSortByValue());
final int space = 400;
StringBuffer text1 = new StringBuffer();
StringBuffer text2 = new StringBuffer();
boolean addToStart = true;
text1.append("\"");
text1.append(stat);
text1.append("\" in \"");
text1.append(channel);
text1.append("\": ");
while (stats.size() > 0) {
EntityStat data = (addToStart ? stats.get(0) : stats.get(stats.size() - 1));
stats.remove(data);
StringBuffer text = new StringBuffer();
text.append(data.entityName);
text.append(" (");
text.append(Math.round(data.value * 100) / 100.0);
text.append(")");
if (text1.length() + text2.length() + text.length() > space) {
text1.append("...");
break;
}
if (addToStart) {
text1.append(text);
if (stats.size() > 0) text1.append(", ");
} else {
text2.insert(0, text);
if (stats.size() > 0) text2.insert(0, ", ");
}
addToStart = !addToStart;
}
text1.append(text2);
text1.append(".");
irc.sendContextReply(mes, text1.toString());
}
public int apiCaptuation( String str )
{
int score = 0;
// remove smilies and trailing whitespace.
str = str.replaceAll("(?:^|\\s+)[:pP)/;\\\\o()^. -]{2,4}(\\s+|$)", "$1");
// remove URLs
str = str.replaceAll("[a-z0-9]+:/\\S+", "");
// Nothing left?
if (str.length() == 0)
return 0;
// No thingie on the end? PENALTY.
// Must end with ., !, ? with or without optional terminating ) or ".
if (!Pattern.compile("[\\.\\?\\!][\\)\"]?$").matcher(str).find())
score += 1;
// Now remove quoted stuff; it'll only give extra points where not needed.
str = str.replaceAll("\".*?\"", "");
// Small letter at start of new sentance/line? PENALTY.
Matcher ma = Pattern.compile("(?:^|(?<!\\.)\\.\\s+)\\p{Ll}").matcher(str);
while (ma.find())
score += 1;
// Penalty non-words.
// Exceptions: id, Id, ill, cant, wont, hand,
// Punish:
// Lowercase "I" in special cases.
// Missing apostrophes in special cases.
// Certain American spellings.
// Internetisms, like "zomg."
// Certain known abbreviations that aren't capitalised.
// Mixed case, like "tHis". "CoW" is fine, however.
// Leetspeak. Unfortunately, C0FF33 is still valid, as it's also hex.
// Also, words with trailing numbers are fine, since some nicknames
// etc. are like this.
ma = Pattern.compile("\\b(?:im|Im|i'm|i'd|i|i'll|b|u2?|(?i:s?hes|they(?:ve|re|ll)|there(?:s|re|ll)|(?:has|was|sha|have)nt|(?:could|would)(?:ve|nt)|k?thz|pl[xz]|zomg|\\w+xor|sidewalk|color)|(?=[A-Z]*[a-z][A-Za-z]*\\b)(?i:bbq|lol|rofl|i?irc|afaik|hth|imh?o|fy|https?|ft[lw])|[a-z]+[A-Z][a-zA-Z]*|(?!(?:[il]1[08]n))(?:\\w*[g-zG-Z]\\w*[0-9]\\w*[a-zA-Z]|\\w*[0-9]\\w*[g-zG-Z]\\w*[a-zA-Z])|american|british|english|european)\\b").matcher(str);
while (ma.find())
score += 1;
return score;
}
// http://schmidt.devlib.org/java/word-count.html#source
public int apiWordCount(String str)
{
int numWords = 0;
int index = 0;
boolean prevWhitespace = true;
while (index < str.length())
{
char c = str.charAt(index++);
boolean currWhitespace = Character.isWhitespace(c);
if (prevWhitespace && !currWhitespace)
numWords++;
prevWhitespace = currWhitespace;
}
return numWords;
}
public int apiLength(String str)
{
return str.replaceAll("\\s+", "").length();
}
public double apiWordLength(String str)
{
return (double)apiLength(str) / (double)apiWordCount(str);
}
/*
public void commandText( Message mes ) throws ChoobException
{
final String workingText = getText(mes);
irc.sendContextReply(mes, (String)mods.plugin.callAPI("Http", "StoreString", workingText));
}
*/
} |
package core;
import java.util.Locale;
import java.util.ResourceBundle;
/**
*
* @author Jonas
*/
public class Translator {
Locale[] locales = {new Locale("de", "DE"), new Locale("en", "GB"), new Locale("it", "IT"),
new Locale("el", "GR"), new Locale("es", "ES"), new Locale("fi", "FI"), new Locale("fr", "FR"),
new Locale("ru", "RU"), new Locale("sv", "SV")};
static Translator t = new Translator();
int currentLang;
int lastLang;
private Translator() {currentLang = 0; lastLang = 0;}
public static Translator getInstance() {return t;}
public String getString(String k) {
ResourceBundle rb = ResourceBundle.getBundle("text/local/Bundle", locales[currentLang]);
return rb.getString(k);
}
public void setCurrentLang(int i) {lastLang = currentLang; currentLang = i;}
public String getcurrentLang() {return locales[currentLang].getLanguage();}
public int getcurrentLangIndex() {return currentLang;}
public int getlastLangIndex() {return lastLang;}
} |
package fini.main;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import fini.main.model.Command;
import fini.main.model.Command.CommandType;
import fini.main.model.FiniParser;
import fini.main.model.StatusSaver;
import fini.main.model.Storage;
import fini.main.model.Task;
import fini.main.util.ModsLoader;
import fini.main.util.Sorter;
import fini.main.view.DisplayController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
* This Brain class is the main logic component of FINI.
* It handles all logic process regarding the manipulation of tasks and different display modes.
* Brain class is the only class that has the access to parser and storage classes.
*
* @@author A0127483B
*/
public class Brain {
private static final String DEFAULT_PROJECT = "Inbox";
private static final String EMPTY_STRING = "";
private static final String SEARCHING_STRING = "Searching...";
private static final String INVALID_FEEDBACK = "Invalid command. Please type help for assistance.";
private static final String ADD_EMPTY_PARAMETER = "Add CommandParameters is empty";
private static final String UPDATE_EMPTY_PARAMETER = "Update CommandParameters is empty";
private static final String START_EXCEEDS_END = "Start date and time should be earlier than end date time";
private static final String EXCEEDS_PROJECT_LIMIT = "Maximum of 5 projects at the same time!";
private static final String TASK_NOT_FOUND = "Task not found";
private static final String ADD_MESSAGE = "Added: %1$s";
private static final String UPDATE_MESSAGE = "Update: %1$s %2$s";
private static final String DELETE_MESSAGE = "Delete: %1$s %2$s";
private static final String CLEAR_MESSAGE = "All tasks have been cleared";
private static final String UNDO_LIMIT = "Unable to undo. You've not done any changes yet.";
private static final String UNDO_MESSAGE = "Your action has been undone.";
private static final String REDO_LIMIT = "Unable to redo. There is nothing for me to redo.";
private static final String REDO_MESSAGE = "Your action has been redone.";
private static final String DISPLAY_MESSAGE = "display project: %1$s";
private static final String UNKNOWN_DISPLAY = "Unknown displayTask method";
private static final String DISPLAY_COMPLETED_MESSAGE = "display completed";
private static final String DISPLAY_MAIN_MESSAGE = "display main";
private static final String DISPLAY_ALL_MESSAGE = "display all";
private static final String COMPLETE_MESSAGE = "Complete: %1$s %2$s";
private static final String UNCOMPLETE_MESSAGE = "Uncomplete: %1$s %2$s";
private static final String NO_MODS_FILE = "No nusmods file";
private static final String MODS_LOADED = "NUSMODS loaded";
private static final String HELP_MESSAGE = "Check help panel for more info";
private static final int START_INDEX = 0;
private static final int END_INDEX = 1;
private static final int MAXIMUM_NUM_OF_PROJECTS = 5;
private static final String USER_INPUT_DISPLAY_ALL = "all";
private static final String USER_INPUT_DISPLAY_MAIN = "main";
private static final String USER_INPUT_DISPLAY_COMPLETED = "completed";
// Singleton
private static Brain brain;
private DisplayController displayController;
private Storage taskOrganiser;
private FiniParser finiParser;
private Sorter sorter;
private StatusSaver statusSaver;
private ArrayList<Task> taskMasterList;
private ObservableList<String> projectNameList = FXCollections.observableArrayList();
private ObservableList<Task> taskObservableList = FXCollections.observableArrayList();
private ObservableList<Task> taskAuxiliaryList = FXCollections.observableArrayList();
private boolean searchDisplayTrigger = false;
private boolean projectDisplayTrigger = false;
private boolean completeDisplayTrigger = false;
private boolean allDisplayTrigger = false;
private Brain() {
finiParser = FiniParser.getInstance();
taskOrganiser = Storage.getInstance();
statusSaver = StatusSaver.getInstance();
taskMasterList = taskOrganiser.readFile();
sortTaskMasterList();
taskObservableList.setAll(getIncompleteTasks());
taskAuxiliaryList.setAll(taskObservableList);
for (Task task : taskAuxiliaryList) {
if (!task.getProjectName().equals(DEFAULT_PROJECT) && !projectNameList.contains(task.getProjectName())) {
projectNameList.add(task.getProjectName());
}
}
statusSaver.saveStatus(taskMasterList, taskObservableList);
}
/*
* This method is the getInstance method for the singleton pattern of
* Brain. It initialises a new Brain if Brain is null, else returns the
* current instance of the Brain.
*/
public static Brain getInstance() {
if (brain == null) {
brain = new Brain();
}
return brain;
}
/*
* This method initialises the first display when FINI is launched
* This method is executed from the MainApp
*/
public void initDisplay() {
displayController.setFocusToCommandBox();
displayController.updateMainDisplay(taskAuxiliaryList);
displayController.updateProjectsOverviewPanel(projectNameList);
displayController.updateTasksOverviewPanel(taskAuxiliaryList);
displayController.updateFiniPoints(getCompletedTasks());
}
public void executeCommand(String userInput) {
Command newCommand = new Command(userInput);
CommandType commandType = newCommand.getCommandType();
int objectIndex = newCommand.getObjectIndex();
String commandParameters = newCommand.getCommandParameters();
MainApp.finiLogger.info("User's input: " + userInput);
MainApp.finiLogger.info("Command type: " + commandType.toString());
MainApp.finiLogger.info("Object index: " + objectIndex);
MainApp.finiLogger.info("Parameters: " + commandParameters);
String display = EMPTY_STRING;
switch (commandType) {
case ADD:
display = addTask(commandParameters);
saveThisStatus();
break;
case UPDATE:
display = updateTask(objectIndex, commandParameters);
saveThisStatus();
break;
case DELETE:
display = deleteTask(objectIndex);
saveThisStatus();
break;
case CLEAR:
display = clearAllTasks();
saveThisStatus();
break;
case UNDO:
display = undo();
break;
case REDO:
display = redo();
break;
case SET:
display = setUserPrefDirectory(commandParameters);
break;
case DISPLAY:
display = displayTask(commandParameters);
break;
case SEARCH:
display = SEARCHING_STRING;
searchTask(commandParameters);
break;
case EXIT:
System.exit(0);
case COMPLETE:
display = completeTask(objectIndex);
saveThisStatus();
break;
case UNCOMPLETE:
display = uncompleteTask(objectIndex);
saveThisStatus();
break;
case MODS:
display = loadNUSMods(commandParameters);
saveThisStatus();
break;
case HELP:
display = displayHelpPanel();
break;
case INVALID:
display = INVALID_FEEDBACK;
break;
default:
break;
}
displayControl();
sortTaskMasterList();
taskAuxiliaryList.setAll(getIncompleteTasks());
projectNameList = FXCollections.observableArrayList();
for (Task task : taskAuxiliaryList) {
if (!task.getProjectName().equals(DEFAULT_PROJECT) && !projectNameList.contains(task.getProjectName())) {
projectNameList.add(task.getProjectName());
}
}
displayController.updateProjectsOverviewPanel(projectNameList);
displayController.updateTasksOverviewPanel(taskAuxiliaryList);
displayController.updateDisplayToUser(display);
displayController.updateFiniPoints(getCompletedTasks());
}
private List<Task> getCompletedTasks() {
return taskMasterList.stream().filter(task -> task.isCompleted()).collect(Collectors.toList());
}
private String addTask(String commandParameters) {
if (commandParameters.isEmpty()) {
return ADD_EMPTY_PARAMETER;
}
finiParser.parse(commandParameters);
if (finiParser.getDatetimes() != null && finiParser.getDatetimes().size() == 2 &&
!finiParser.getDatetimes().get(START_INDEX).isBefore(finiParser.getDatetimes().get(END_INDEX))) {
return START_EXCEEDS_END;
}
if (!finiParser.getProjectName().equals(DEFAULT_PROJECT) &&
!projectNameList.contains(finiParser.getProjectName()) &&
projectNameList.size() == MAXIMUM_NUM_OF_PROJECTS) {
return EXCEEDS_PROJECT_LIMIT;
}
Task newTask = new Task.TaskBuilder(finiParser.getNotParsed(), finiParser.getIsRecurring())
.setDatetimes(finiParser.getDatetimes())
.setPriority(finiParser.getPriority())
.setProjectName(finiParser.getProjectName())
.setInterval(finiParser.getInterval())
.setRecursUntil(finiParser.getRecursUntil()).build();
taskMasterList.add(newTask);
taskOrganiser.updateFile(taskMasterList);
return String.format(ADD_MESSAGE, finiParser.getNotParsed());
}
private String updateTask(int objectIndex, String commandParameters) {
Task taskToUpdate;
if (commandParameters.isEmpty()) {
return UPDATE_EMPTY_PARAMETER;
}
try {
taskToUpdate = taskObservableList.get(objectIndex - 1);
} catch (IndexOutOfBoundsException e) {
return TASK_NOT_FOUND;
}
// delete first
taskObservableList.remove(taskToUpdate);
taskMasterList.remove(taskToUpdate);
taskOrganiser.updateFile(taskMasterList);
// add then
finiParser.parse(commandParameters);
if (finiParser.getDatetimes() != null && finiParser.getDatetimes().size() == 2 &&
!finiParser.getDatetimes().get(START_INDEX).isBefore(finiParser.getDatetimes().get(END_INDEX))) {
return START_EXCEEDS_END;
}
if (!finiParser.getProjectName().equals(DEFAULT_PROJECT) &&
!projectNameList.contains(finiParser.getProjectName()) &&
projectNameList.size() == MAXIMUM_NUM_OF_PROJECTS) {
return EXCEEDS_PROJECT_LIMIT;
}
Task newTask = new Task.TaskBuilder(finiParser.getNotParsed(), finiParser.getIsRecurring())
.setDatetimes(finiParser.getDatetimes())
.setPriority(finiParser.getPriority())
.setProjectName(finiParser.getProjectName())
.setInterval(finiParser.getInterval())
.setRecursUntil(finiParser.getRecursUntil()).build();
taskMasterList.add(newTask);
taskOrganiser.updateFile(taskMasterList);
return String.format(UPDATE_MESSAGE, objectIndex, taskToUpdate.getTitle());
}
private String deleteTask(int objectIndex) {
Task taskToDelete;
try {
taskToDelete = taskObservableList.get(objectIndex - 1);
} catch (IndexOutOfBoundsException e) {
return TASK_NOT_FOUND;
}
taskObservableList.remove(taskToDelete);
taskMasterList.remove(taskToDelete);
taskOrganiser.updateFile(taskMasterList);
return String.format(DELETE_MESSAGE, objectIndex, taskToDelete.getTitle());
}
// @@author A0121828H
private String clearAllTasks() {
taskMasterList.clear();
taskOrganiser.updateFile(taskMasterList);
return CLEAR_MESSAGE;
}
private String undo() {
assert statusSaver != null;
if (statusSaver.isUndoMasterStackEmpty()) {
return UNDO_LIMIT;
}
statusSaver.retrieveLastStatus();
taskMasterList = statusSaver.getLastTaskMasterList();
taskObservableList = statusSaver.getLastTaskObservableList();
taskOrganiser.updateFile(taskMasterList);
return UNDO_MESSAGE;
}
private String redo() {
if (statusSaver.isRedoMasterStackEmpty()) {
return REDO_LIMIT;
}
statusSaver.retrieveRedoStatus();
taskMasterList = statusSaver.getLastTaskMasterList();
taskObservableList = statusSaver.getLastTaskObservableList();
taskOrganiser.updateFile(taskMasterList);
return REDO_MESSAGE;
}
private String setUserPrefDirectory(String commandParameters) {
return taskOrganiser.setUserPrefDirectory(commandParameters);
}
private String displayTask(String commandParameters) {
if (commandParameters.equals(USER_INPUT_DISPLAY_COMPLETED)) {
completeDisplayTrigger = true;
projectDisplayTrigger = false;
searchDisplayTrigger = false;
allDisplayTrigger = false;
return DISPLAY_COMPLETED_MESSAGE;
} else if(commandParameters.equals(EMPTY_STRING) || commandParameters.equals(USER_INPUT_DISPLAY_MAIN)) {
completeDisplayTrigger = false;
projectDisplayTrigger = false;
searchDisplayTrigger = false;
allDisplayTrigger = false;
return DISPLAY_MAIN_MESSAGE;
} else if(commandParameters.equals(USER_INPUT_DISPLAY_ALL)) {
completeDisplayTrigger = false;
searchDisplayTrigger = false;
projectDisplayTrigger = false;
allDisplayTrigger = true;
sortTaskMasterListWithIncomplete();
taskObservableList.setAll(taskMasterList);
return DISPLAY_ALL_MESSAGE;
} else if (projectNameList.contains(commandParameters)) {
projectDisplayTrigger = true;
completeDisplayTrigger = false;
searchDisplayTrigger = false;
allDisplayTrigger = false;
ObservableList<Task> projectTasks = FXCollections.observableArrayList();
for (Task task : taskObservableList) {
if (task.getProjectName().equals(commandParameters)) {
projectTasks.add(task);
}
}
taskObservableList.setAll(projectTasks);
return String.format(DISPLAY_MESSAGE, commandParameters);
} else {
return UNKNOWN_DISPLAY;
}
}
private void searchTask(String commandParameters) {
searchDisplayTrigger = true;
ObservableList<Task> tempObservableList = FXCollections.observableArrayList();
finiParser.parse(commandParameters);
for (Task task : taskMasterList) {
if (task.getTitle().contains(commandParameters)) {
tempObservableList.add(task);
}
}
taskObservableList.setAll(tempObservableList);
}
private String completeTask(int objectIndex) {
Task taskToComplete;
try {
taskToComplete = taskObservableList.get(objectIndex - 1);
} catch (IndexOutOfBoundsException e) {
return TASK_NOT_FOUND;
}
if (taskToComplete.isRecurring() && taskToComplete.hasNext()) {
Task copyTask = taskToComplete.makeCopy();
copyTask.setIsComplete();
copyTask.updateObjectID();
for (Iterator<Task> iterator = taskMasterList.iterator(); iterator.hasNext(); ) {
Task taskToRemove = iterator.next();
if (!taskToRemove.getObjectID().equals(taskToComplete.getObjectID()) &&
taskToRemove.hasRecurUniqueID() &&
taskToRemove.getRecurUniqueID().equals(copyTask.getRecurUniqueID())) {
iterator.remove();
}
}
taskMasterList.add(copyTask);
taskToComplete.toNext();
} else {
taskToComplete.setIsComplete();
}
taskOrganiser.updateFile(taskMasterList);
return String.format(COMPLETE_MESSAGE, objectIndex, taskToComplete.getTitle());
}
private String uncompleteTask(int objectIndex) {
Task taskToUncomplete;
try {
taskToUncomplete = taskObservableList.get(objectIndex - 1);
} catch (IndexOutOfBoundsException e) {
return TASK_NOT_FOUND;
}
taskToUncomplete.setIncomplete();
if (taskToUncomplete.isRecurring()) {
for (Iterator<Task> iterator = taskMasterList.iterator(); iterator.hasNext(); ) {
Task taskToRemove = iterator.next();
if (!taskToRemove.getObjectID().equals(taskToUncomplete.getObjectID()) &&
taskToRemove.hasRecurUniqueID() &&
taskToRemove.getRecurUniqueID().equals(taskToUncomplete.getRecurUniqueID())) {
iterator.remove();
}
}
}
taskOrganiser.updateFile(taskMasterList);
return String.format(UNCOMPLETE_MESSAGE, objectIndex, taskToUncomplete.getTitle());
}
private String loadNUSMods(String commandParameters) {
File modsFile = new File(commandParameters);
if (modsFile.exists()) {
ModsLoader loader = new ModsLoader(modsFile);
taskMasterList.addAll(loader.getLessonTasks());
} else {
return NO_MODS_FILE;
}
taskOrganiser.updateFile(taskMasterList);
return MODS_LOADED;
}
private String displayHelpPanel() {
displayController.displayHelpPanel();
return HELP_MESSAGE;
}
private void saveThisStatus() {
assert taskMasterList != null;
assert taskObservableList != null;
statusSaver.saveStatus(taskMasterList, taskObservableList);
}
private void displayControl() {
if (completeDisplayTrigger) {
taskObservableList.setAll(getCompletedTasks());
displayController.updateCompletedDisplay(taskObservableList);
} else if (searchDisplayTrigger) {
displayController.updateSearchDisplay(taskObservableList);
} else if (allDisplayTrigger) {
displayController.updateAllDisplay(taskObservableList);
} else if (projectDisplayTrigger) {
displayController.updateProjectDisplay(taskObservableList);
} else {
sortTaskMasterList();
taskObservableList.setAll(getIncompleteTasks());
displayController.updateMainDisplay(taskObservableList);
}
}
private List<Task> getIncompleteTasks() {
return taskMasterList.stream().filter(task -> !task.isCompleted()).collect(Collectors.toList());
}
private void sortTaskMasterList() {
assert taskMasterList != null;
sorter = new Sorter(taskMasterList);
sorter.sort();
taskMasterList = sorter.getSortedList();
}
private void sortTaskMasterListWithIncomplete() {
assert taskMasterList != null;
sorter = new Sorter(taskMasterList);
sorter.addSortByIncomplete();
sorter.sort();
taskMasterList = sorter.getSortedList();
}
public ObservableList<Task> getTaskObservableList() {
return taskObservableList;
}
public void setRootController(DisplayController displayController) {
this.displayController = displayController;
}
public DisplayController getRootController() {
return displayController;
}
} |
package foam.dao;
import foam.core.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.util.List;
import java.util.Iterator;
public class XMLDAO
extends MapDAO
{
protected String fileName;
public void setFileName(String filename) {
if ( filename.contains(".xml") ) {
fileName = System.getProperty("user.dir") + filename;
} else {
fileName = System.getProperty("user.dir") + filename.concat(".xml");
}
}
public String getFileName() { return fileName; }
// Read file and read data in the DAO
public void init() throws IOException {
X x = new ProxyX();
this.setX(x);
List<FObject> objList;
try {
objList = XMLSupport.fromXML(x, fileName);
Iterator i = objList.iterator();
while ( i.hasNext() ) {
FObject currentObj = (FObject)i.next();
ClassInfo clsInfo = currentObj.getClassInfo();
this.setOf(clsInfo);
this.putOnly(currentObj);
}
} catch ( FileNotFoundException ex) {
}
}
// Rewrites file when new object is put into DAO
public FObject put(FObject obj) {
this.setOf(obj.getClassInfo());
FObject s = super.put(obj);
daoToXML();
return s;
}
// Used for xml to FObject conversion where re-write is not required
public FObject putOnly(FObject obj) {
this.setOf(obj.getClassInfo());
return super.put(obj);
}
public FObject remove(FObject obj) {
FObject s = super.remove(obj);
daoToXML();
return s;
}
public void removeAll() {
super.removeAll();
daoToXML();
}
public void daoToXML () {
X x = new ProxyX();
this.setX(x);
ListSink ls = new ListSink();
this.select(ls);
List objList = ls.getData();
try {
XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xmlStreamWriter = xMLOutputFactory.createXMLStreamWriter(new FileWriter(fileName));
XMLSupport.toXML(objList, xmlStreamWriter);
xmlStreamWriter.flush();
xmlStreamWriter.close();
} catch (IOException | XMLStreamException ex) {
}
}
} |
package frontend;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.Action;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javafx.embed.swing.SwingNode;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import text_handler.FontManager;
public class Editor {
private SwingNode swingNode;
private JTextPane textPane;
private JScrollPane scrollPane;
private JPanel panel;
private Customizer customizer;
private boolean updateMatcher = true;
private Matcher matcher;
private boolean contentChanged = false;
private HashMap<Object, Action> editorKitActions;
protected final class Customizer {
private Customizer(){
//default settings
setBorder(new EmptyBorder(10, 15, 10, 15));
setMarginBackground(Color.WHITE);
}
public Border getBorder(Border border){
return panel.getBorder();
}
public void setBorder(Border border){
panel.setBorder(border);
}
public Insets getMargin(){
return panel.getInsets();
}
public void setMarginBackground(Color color){
panel.setBackground(color);
}
public Color getMarginBackground(Color color){
return panel.getBackground();
}
public void setOpaque(boolean isOpaque){
textPane.setOpaque(isOpaque);
}
public int getHorizontalUnitIncrement(){
return scrollPane.getHorizontalScrollBar().getUnitIncrement();
}
public int getHorizontalBlockIncrement(){
return scrollPane.getHorizontalScrollBar().getBlockIncrement();
}
public int getVerticalUnitIncrement(){
return scrollPane.getVerticalScrollBar().getUnitIncrement();
}
public int getVerticalBlockIncrement(){
return scrollPane.getVerticalScrollBar().getBlockIncrement();
}
public void setHorizontalUnitIncrement(int value){
scrollPane.getHorizontalScrollBar().setUnitIncrement(value);
}
public void setHorizontalBlockIncrement(int value){
scrollPane.getHorizontalScrollBar().setBlockIncrement(value);
}
public void setVerticalUnitIncrement(int value){
scrollPane.getVerticalScrollBar().setUnitIncrement(value);
}
public void setVerticalBlockIncrement(int value){
scrollPane.getVerticalScrollBar().setBlockIncrement(value);
}
}
public Editor(SwingNode swingNode) {
this.swingNode = swingNode;
createSwingContent();
}
public Customizer getCustomizer(){
return customizer;
}
public final void updateMatcher(){
updateMatcher = true;
}
protected void createSwingContent() {
panel = new JPanel(new BorderLayout());
SwingUtilities.invokeLater(() -> {
textPane = new JTextPane();
scrollPane = new JScrollPane(panel);
panel.add(textPane);
swingNode.setContent(scrollPane);
initialize();
customizer = new Customizer();
});
}
protected void initialize(){
// Add document listener
textPane.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void changedUpdate(DocumentEvent arg0) {
//TODO test only for style or for text also
contentChanged = true;
}
@Override
public void insertUpdate(DocumentEvent arg0) {
contentChanged = true;
}
@Override
public void removeUpdate(DocumentEvent arg0) {
contentChanged = true;
}
});
// Set default Font
setFont(FontManager.FONT_DEFAULT, FontWeight.NORMAL);
// save all actions in one place
editorKitActions = new HashMap<Object, Action>(textPane.getEditorKit().getActions().length);
for(Action action: textPane.getEditorKit().getActions())
editorKitActions.put(action.getValue(Action.NAME), action);
}
public boolean contentChanged(){
return contentChanged;
}
public void deleteSelected(){
int start = textPane.getSelectionStart();
int end = textPane.getSelectionEnd();
if(end != 0){
try {
textPane.getDocument().remove(start, end - start);
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
public void cut(){
Action cut = editorKitActions.get(DefaultEditorKit.cutAction);
cut.actionPerformed(new ActionEvent(textPane, ActionEvent.ACTION_PERFORMED, "Cut"));
}
public void copy(){
Action copy = editorKitActions.get(DefaultEditorKit.copyAction);
copy.actionPerformed(new ActionEvent(textPane, ActionEvent.ACTION_PERFORMED,"Copy"));
}
public void paste(){
Action paste = editorKitActions.get(DefaultEditorKit.pasteAction);
paste.actionPerformed(new ActionEvent(textPane, ActionEvent.ACTION_PERFORMED, "Paste"));
}
public void setEditable(boolean editable) {
textPane.setEditable(editable);
}
public void setSize(int width, int height){
textPane.setSize(width, height);
}
public boolean getEditable() {
return textPane.isEditable();
}
public void setFont(Font font, FontWeight weight) {
textPane.setFont(FontManager.getAWTFont(font, weight));
}
public Font getFont() {
return FontManager.getFxFont(textPane.getFont());
}
public void writeToFile(File file)throws IOException {
textPane.write(new BufferedWriter(new FileWriter(file)));
contentChanged = false;
}
public void readFromFile(File file)throws IOException {
textPane.read(new BufferedReader(new FileReader(file)), file);
}
public void clear(){
textPane.setText(null);
}
/** Creates a new matcher object for a specific regex **/
protected Matcher createMatcher(String regex, boolean matchCase, boolean wholeWord){
String newRegex = (wholeWord)?"\\b"+regex+"\\b" : regex;
Pattern pattern = (matchCase) ? Pattern.compile(newRegex) : Pattern.compile(newRegex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(textPane.getText());
return matcher;
}
/**
* Selects the next word . Creates the new matcher if required**/
protected boolean find(String findWhat, boolean matchCase, boolean wholeWord){
if(updateMatcher){
matcher = createMatcher(findWhat, matchCase, wholeWord);
updateMatcher = false;
}
boolean found = matcher.find();
if(found){
textPane.setSelectionStart(matcher.start());
textPane.setSelectionEnd(matcher.end());
}
return found;
}
//Replace the selected text with given text
public void replaceSelected(String replaceWith){
textPane.replaceSelection(replaceWith);
}
/** Replace all occurrence of given string with specified string **/
public void replaceAll(String findWhat, String replaceWith, boolean matchCase){
matcher = createMatcher(findWhat, matchCase, false);
textPane.setText(matcher.replaceAll(replaceWith));
}
} |
package luajava;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* LuaJava console
* @author Thiago Ponte
*/
public class Console
{
/**
* Creates a console for user interaction
* @param args - names of the lua files to be executed
*/
public static void main(String[] args)
{
try
{
LuaState L = LuaStateFactory.newLuaState();
L.openBasicLibraries();
L.openDebug();
L.openLoadLib();
if (args.length > 0)
{
for (int i = 0; i < args.length; i++)
{
int res = L.doFile(args[i]);
if (res != 0)
{
String str;
if (res == LuaState.LUA_ERRRUN.intValue())
{
str = "Runtime error. ";
}
else if (res == LuaState.LUA_ERRMEM.intValue())
{
str = "Memory allocation error. ";
}
else if (res == LuaState.LUA_ERRERR.intValue())
{
str = "Error while running the error handler function. ";
}
else
{
str = "Lua Error code " + res + ". ";
}
throw new LuaException(str + "Error on file " + args[i]);
}
}
return;
}
System.out.println("API Lua Java - console mode.");
BufferedReader inp =
new BufferedReader(new InputStreamReader(System.in));
String line;
System.out.print("> ");
while ((line = inp.readLine()) != null && !line.equals("exit"))
{
int ret = L.doString(line);
if (ret != 0)
System.out.println("Invalid Input : " + line);
System.out.print("> ");
}
L.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
} |
package org.glob3.mobile.generated;
public class Mark
{
/**
* The text the mark displays.
* Useless if the mark does not have label.
*/
private final String _label;
/**
* Flag to know if the label will be located under the icon (if TRUE) or on its right (if FALSE).
* Useless if the mark does not have label or icon.
* Default value: TRUE
*/
private final boolean _labelBottom;
/**
* The font size of the text.
* Useless if the mark does not have label.
* Default value: 20
*/
private final float _labelFontSize;
/**
* The color of the text.
* Useless if the mark does not have label.
* Default value: white
*/
private final Color _labelFontColor;
/**
* The color of the text shadow.
* Useless if the mark does not have label.
* Default value: black
*/
private final Color _labelShadowColor;
/**
* The number of pixels between the icon and the text.
* Useless if the mark does not have label or icon.
* Default value: 2
*/
private final int _labelGapSize;
/**
* The URL to get the image file.
* Useless if the mark does not have icon.
*/
private URL _iconURL = new URL();
/**
* The point where the mark will be geo-located.
*/
private final Geodetic3D _position ;
/**
* The minimun distance (in meters) to show the mark. If the camera is further than this, the mark will not be displayed.
* Default value: 4.5e+06
*/
private double _minDistanceToCamera;
/**
* The extra data to be stored by the mark.
* Usefull to store data such us name, URL...
*/
private MarkUserData _userData;
/**
* Flag to know if the mark is the owner of _userData and thus it must delete it on destruction.
* Default value: TRUE
*/
private final boolean _autoDeleteUserData;
/**
* Interface for listening to the touch event.
*/
private MarkTouchListener _listener;
/**
* Flag to know if the mark is the owner of _listener and thus it must delete it on destruction.
* Default value: FALSE
*/
private final boolean _autoDeleteListener;
private IGLTextureId _textureId;
private Vector3D _cartesianPosition;
private IFloatBuffer _vertices;
private IFloatBuffer getVertices(Planet planet)
{
if (_vertices == null)
{
final Vector3D pos = getCartesianPosition(planet);
FloatBufferBuilderFromCartesian3D vertex = new FloatBufferBuilderFromCartesian3D(CenterStrategy.noCenter(), Vector3D.zero());
vertex.add(pos);
vertex.add(pos);
vertex.add(pos);
vertex.add(pos);
_vertices = vertex.create();
}
return _vertices;
}
private boolean _textureSolved;
private IImage _textureImage;
private int _textureWidth;
private int _textureHeight;
private final String _imageID;
private boolean _renderedMark;
private static IFloatBuffer _billboardTexCoord = null;
private Planet _planet; // REMOVED FINAL WORD BY CONVERSOR RULE
private int _viewportWidth;
private int _viewportHeight;
private GLState _glState = new GLState();
private void createGLState()
{
GLGlobalState globalState = _glState.getGLGlobalState();
globalState.disableDepthTest();
globalState.enableBlend();
globalState.setBlendFactors(GLBlendFactor.srcAlpha(), GLBlendFactor.oneMinusSrcAlpha());
globalState.bindTexture(_textureId);
GPUProgramState progState = _glState.getGPUProgramState();
if (_planet == null)
{
ILogger.instance().logError("Planet NULL");
}
else
{
//Test matrix multiplication
// progState->setUniformMatrixValue("Modelview", MutableMatrix44D::createTranslationMatrix(Vector3D(1e7, 0, 0)), true);
progState.setAttributeEnabled("Position", true);
progState.setAttributeEnabled("TextureCoord", true);
if (_billboardTexCoord == null)
{
FloatBufferBuilderFromCartesian2D texCoor = new FloatBufferBuilderFromCartesian2D();
texCoor.add(1,1);
texCoor.add(1,0);
texCoor.add(0,1);
texCoor.add(0,0);
_billboardTexCoord = texCoor.create();
}
progState.setAttributeValue("TextureCoord", _billboardTexCoord, 2, 2, 0, false, 0);
final Vector3D pos = new Vector3D(_planet.toCartesian(_position));
FloatBufferBuilderFromCartesian3D vertex = new FloatBufferBuilderFromCartesian3D(CenterStrategy.noCenter(), Vector3D.zero());
vertex.add(pos);
vertex.add(pos);
vertex.add(pos);
vertex.add(pos);
IFloatBuffer vertices = vertex.create();
progState.setAttributeValue("Position", vertices, 4, 3, 0, false, 0); //Stride 0 - Not normalized - Index 0 - Our buffer contains elements of 3 - The attribute is a float vector of 4 elements
progState.setUniformValue("TextureExtent", new Vector2D(_textureWidth, _textureHeight));
progState.setUniformValue("ViewPortExtent", new Vector2D((double)_viewportWidth, (double)_viewportHeight));
progState.setAttributeDisabled("Color");
}
}
/**
* Creates a marker with icon and label
*/
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera, boolean labelBottom, float labelFontSize, Color labelFontColor, Color labelShadowColor, int labelGapSize, MarkUserData userData, boolean autoDeleteUserData, MarkTouchListener listener)
{
this(label, iconURL, position, minDistanceToCamera, labelBottom, labelFontSize, labelFontColor, labelShadowColor, labelGapSize, userData, autoDeleteUserData, listener, false);
}
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera, boolean labelBottom, float labelFontSize, Color labelFontColor, Color labelShadowColor, int labelGapSize, MarkUserData userData, boolean autoDeleteUserData)
{
this(label, iconURL, position, minDistanceToCamera, labelBottom, labelFontSize, labelFontColor, labelShadowColor, labelGapSize, userData, autoDeleteUserData, null, false);
}
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera, boolean labelBottom, float labelFontSize, Color labelFontColor, Color labelShadowColor, int labelGapSize, MarkUserData userData)
{
this(label, iconURL, position, minDistanceToCamera, labelBottom, labelFontSize, labelFontColor, labelShadowColor, labelGapSize, userData, true, null, false);
}
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera, boolean labelBottom, float labelFontSize, Color labelFontColor, Color labelShadowColor, int labelGapSize)
{
this(label, iconURL, position, minDistanceToCamera, labelBottom, labelFontSize, labelFontColor, labelShadowColor, labelGapSize, null, true, null, false);
}
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera, boolean labelBottom, float labelFontSize, Color labelFontColor, Color labelShadowColor)
{
this(label, iconURL, position, minDistanceToCamera, labelBottom, labelFontSize, labelFontColor, labelShadowColor, 2, null, true, null, false);
}
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera, boolean labelBottom, float labelFontSize, Color labelFontColor)
{
this(label, iconURL, position, minDistanceToCamera, labelBottom, labelFontSize, labelFontColor, Color.newFromRGBA(0, 0, 0, 1), 2, null, true, null, false);
}
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera, boolean labelBottom, float labelFontSize)
{
this(label, iconURL, position, minDistanceToCamera, labelBottom, labelFontSize, Color.newFromRGBA(1, 1, 1, 1), Color.newFromRGBA(0, 0, 0, 1), 2, null, true, null, false);
}
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera, boolean labelBottom)
{
this(label, iconURL, position, minDistanceToCamera, labelBottom, 20, Color.newFromRGBA(1, 1, 1, 1), Color.newFromRGBA(0, 0, 0, 1), 2, null, true, null, false);
}
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera)
{
this(label, iconURL, position, minDistanceToCamera, true, 20, Color.newFromRGBA(1, 1, 1, 1), Color.newFromRGBA(0, 0, 0, 1), 2, null, true, null, false);
}
public Mark(String label, URL iconURL, Geodetic3D position)
{
this(label, iconURL, position, 4.5e+06, true, 20, Color.newFromRGBA(1, 1, 1, 1), Color.newFromRGBA(0, 0, 0, 1), 2, null, true, null, false);
}
public Mark(String label, URL iconURL, Geodetic3D position, double minDistanceToCamera, boolean labelBottom, float labelFontSize, Color labelFontColor, Color labelShadowColor, int labelGapSize, MarkUserData userData, boolean autoDeleteUserData, MarkTouchListener listener, boolean autoDeleteListener)
{
_label = label;
_iconURL = new URL(iconURL);
_position = new Geodetic3D(position);
_labelBottom = labelBottom;
_labelFontSize = labelFontSize;
_labelFontColor = labelFontColor;
_labelShadowColor = labelShadowColor;
_labelGapSize = labelGapSize;
_textureId = null;
_cartesianPosition = null;
_vertices = null;
_textureSolved = false;
_textureImage = null;
_renderedMark = false;
_textureWidth = 0;
_textureHeight = 0;
_userData = userData;
_autoDeleteUserData = autoDeleteUserData;
_minDistanceToCamera = minDistanceToCamera;
_listener = listener;
_autoDeleteListener = autoDeleteListener;
_imageID = iconURL.getPath() + "_" + label;
_planet = null;
}
/**
* Creates a marker just with label, without icon
*/
public Mark(String label, Geodetic3D position, double minDistanceToCamera, float labelFontSize, Color labelFontColor, Color labelShadowColor, MarkUserData userData, boolean autoDeleteUserData, MarkTouchListener listener)
{
this(label, position, minDistanceToCamera, labelFontSize, labelFontColor, labelShadowColor, userData, autoDeleteUserData, listener, false);
}
public Mark(String label, Geodetic3D position, double minDistanceToCamera, float labelFontSize, Color labelFontColor, Color labelShadowColor, MarkUserData userData, boolean autoDeleteUserData)
{
this(label, position, minDistanceToCamera, labelFontSize, labelFontColor, labelShadowColor, userData, autoDeleteUserData, null, false);
}
public Mark(String label, Geodetic3D position, double minDistanceToCamera, float labelFontSize, Color labelFontColor, Color labelShadowColor, MarkUserData userData)
{
this(label, position, minDistanceToCamera, labelFontSize, labelFontColor, labelShadowColor, userData, true, null, false);
}
public Mark(String label, Geodetic3D position, double minDistanceToCamera, float labelFontSize, Color labelFontColor, Color labelShadowColor)
{
this(label, position, minDistanceToCamera, labelFontSize, labelFontColor, labelShadowColor, null, true, null, false);
}
public Mark(String label, Geodetic3D position, double minDistanceToCamera, float labelFontSize, Color labelFontColor)
{
this(label, position, minDistanceToCamera, labelFontSize, labelFontColor, Color.newFromRGBA(0, 0, 0, 1), null, true, null, false);
}
public Mark(String label, Geodetic3D position, double minDistanceToCamera, float labelFontSize)
{
this(label, position, minDistanceToCamera, labelFontSize, Color.newFromRGBA(1, 1, 1, 1), Color.newFromRGBA(0, 0, 0, 1), null, true, null, false);
}
public Mark(String label, Geodetic3D position, double minDistanceToCamera)
{
this(label, position, minDistanceToCamera, 20, Color.newFromRGBA(1, 1, 1, 1), Color.newFromRGBA(0, 0, 0, 1), null, true, null, false);
}
public Mark(String label, Geodetic3D position)
{
this(label, position, 4.5e+06, 20, Color.newFromRGBA(1, 1, 1, 1), Color.newFromRGBA(0, 0, 0, 1), null, true, null, false);
}
public Mark(String label, Geodetic3D position, double minDistanceToCamera, float labelFontSize, Color labelFontColor, Color labelShadowColor, MarkUserData userData, boolean autoDeleteUserData, MarkTouchListener listener, boolean autoDeleteListener)
{
_label = label;
_labelBottom = true;
_iconURL = new URL("", false);
_position = new Geodetic3D(position);
_labelFontSize = labelFontSize;
_labelFontColor = labelFontColor;
_labelShadowColor = labelShadowColor;
_labelGapSize = 2;
_textureId = null;
_cartesianPosition = null;
_vertices = null;
_textureSolved = false;
_textureImage = null;
_renderedMark = false;
_textureWidth = 0;
_textureHeight = 0;
_userData = userData;
_autoDeleteUserData = autoDeleteUserData;
_minDistanceToCamera = minDistanceToCamera;
_listener = listener;
_autoDeleteListener = autoDeleteListener;
_imageID = "_" + label;
_planet = null;
}
/**
* Creates a marker just with icon, without label
*/
public Mark(URL iconURL, Geodetic3D position, double minDistanceToCamera, MarkUserData userData, boolean autoDeleteUserData, MarkTouchListener listener)
{
this(iconURL, position, minDistanceToCamera, userData, autoDeleteUserData, listener, false);
}
public Mark(URL iconURL, Geodetic3D position, double minDistanceToCamera, MarkUserData userData, boolean autoDeleteUserData)
{
this(iconURL, position, minDistanceToCamera, userData, autoDeleteUserData, null, false);
}
public Mark(URL iconURL, Geodetic3D position, double minDistanceToCamera, MarkUserData userData)
{
this(iconURL, position, minDistanceToCamera, userData, true, null, false);
}
public Mark(URL iconURL, Geodetic3D position, double minDistanceToCamera)
{
this(iconURL, position, minDistanceToCamera, null, true, null, false);
}
public Mark(URL iconURL, Geodetic3D position)
{
this(iconURL, position, 4.5e+06, null, true, null, false);
}
public Mark(URL iconURL, Geodetic3D position, double minDistanceToCamera, MarkUserData userData, boolean autoDeleteUserData, MarkTouchListener listener, boolean autoDeleteListener)
{
_label = "";
_labelBottom = true;
_iconURL = new URL(iconURL);
_position = new Geodetic3D(position);
_labelFontSize = 20F;
_labelFontColor = Color.newFromRGBA(1, 1, 1, 1);
_labelShadowColor = Color.newFromRGBA(0, 0, 0, 1);
_labelGapSize = 2;
_textureId = null;
_cartesianPosition = null;
_vertices = null;
_textureSolved = false;
_textureImage = null;
_renderedMark = false;
_textureWidth = 0;
_textureHeight = 0;
_userData = userData;
_autoDeleteUserData = autoDeleteUserData;
_minDistanceToCamera = minDistanceToCamera;
_listener = listener;
_autoDeleteListener = autoDeleteListener;
_imageID = iconURL.getPath() + "_";
_planet = null;
}
/**
* Creates a marker whith a given pre-renderer IImage
*/
public Mark(IImage image, String imageID, Geodetic3D position, double minDistanceToCamera, MarkUserData userData, boolean autoDeleteUserData, MarkTouchListener listener)
{
this(image, imageID, position, minDistanceToCamera, userData, autoDeleteUserData, listener, false);
}
public Mark(IImage image, String imageID, Geodetic3D position, double minDistanceToCamera, MarkUserData userData, boolean autoDeleteUserData)
{
this(image, imageID, position, minDistanceToCamera, userData, autoDeleteUserData, null, false);
}
public Mark(IImage image, String imageID, Geodetic3D position, double minDistanceToCamera, MarkUserData userData)
{
this(image, imageID, position, minDistanceToCamera, userData, true, null, false);
}
public Mark(IImage image, String imageID, Geodetic3D position, double minDistanceToCamera)
{
this(image, imageID, position, minDistanceToCamera, null, true, null, false);
}
public Mark(IImage image, String imageID, Geodetic3D position)
{
this(image, imageID, position, 4.5e+06, null, true, null, false);
}
public Mark(IImage image, String imageID, Geodetic3D position, double minDistanceToCamera, MarkUserData userData, boolean autoDeleteUserData, MarkTouchListener listener, boolean autoDeleteListener)
{
_label = "";
_labelBottom = true;
_iconURL = new URL(new URL("", false));
_position = new Geodetic3D(position);
_labelFontSize = 20F;
_labelFontColor = null;
_labelShadowColor = null;
_labelGapSize = 2;
_textureId = null;
_cartesianPosition = null;
_vertices = null;
_textureSolved = true;
_textureImage = image;
_renderedMark = false;
_textureWidth = image.getWidth();
_textureHeight = image.getHeight();
_userData = userData;
_autoDeleteUserData = autoDeleteUserData;
_minDistanceToCamera = minDistanceToCamera;
_listener = listener;
_autoDeleteListener = autoDeleteListener;
_imageID = imageID;
_planet = null;
}
public void dispose()
{
if (_cartesianPosition != null)
_cartesianPosition.dispose();
if (_vertices != null)
_vertices.dispose();
if (_autoDeleteListener)
{
if (_listener != null)
_listener.dispose();
}
if (_autoDeleteUserData)
{
if (_userData != null)
_userData.dispose();
}
if (_textureImage != null)
{
IFactory.instance().deleteImage(_textureImage);
}
}
public final String getLabel()
{
return _label;
}
public final Geodetic3D getPosition()
{
return _position;
}
public final void initialize(G3MContext context, long downloadPriority)
{
_planet = context.getPlanet();
if (!_textureSolved)
{
final boolean hasLabel = (_label.length() != 0);
final boolean hasIconURL = (_iconURL.getPath().length() != 0);
if (hasIconURL)
{
IDownloader downloader = context.getDownloader();
downloader.requestImage(_iconURL, downloadPriority, TimeInterval.fromDays(30), true, new IconDownloadListener(this, _label, _labelBottom, _labelFontSize, _labelFontColor, _labelShadowColor, _labelGapSize), true);
}
else
{
if (hasLabel)
{
ITextUtils.instance().createLabelImage(_label, _labelFontSize, _labelFontColor, _labelShadowColor, new MarkLabelImageListener(null, this), true);
}
else
{
ILogger.instance().logWarning("Marker created without label nor icon");
}
}
}
}
//C++ TO JAVA CONVERTER TODO TASK: The implementation of the following method could not be found:
// void render(G3MRenderContext rc, Vector3D cameraPosition);
public final boolean isReady()
{
return _textureSolved;
}
public final boolean isRendered()
{
return _renderedMark;
}
public final void onTextureDownloadError()
{
_textureSolved = true;
if (_labelFontColor != null)
_labelFontColor.dispose();
if (_labelShadowColor != null)
_labelShadowColor.dispose();
ILogger.instance().logError("Can't create texture for Mark (iconURL=\"%s\", label=\"%s\")", _iconURL.getPath(), _label);
}
public final void onTextureDownload(IImage image)
{
_textureSolved = true;
if (_labelFontColor != null)
_labelFontColor.dispose();
if (_labelShadowColor != null)
_labelShadowColor.dispose();
// _textureImage = image->shallowCopy();
_textureImage = image;
_textureWidth = _textureImage.getWidth();
_textureHeight = _textureImage.getHeight();
// IFactory::instance()->deleteImage(image);
}
public final int getTextureWidth()
{
return _textureWidth;
}
public final int getTextureHeight()
{
return _textureHeight;
}
public final Vector2I getTextureExtent()
{
return new Vector2I(_textureWidth, _textureHeight);
}
public final MarkUserData getUserData()
{
return _userData;
}
public final void setUserData(MarkUserData userData)
{
if (_autoDeleteUserData)
{
if (_userData != null)
_userData.dispose();
}
_userData = userData;
}
public final boolean touched()
{
return (_listener == null) ? false : _listener.touchedMark(this);
// if (_listener == NULL) {
// return false;
// return _listener->touchedMark(this);
}
public final Vector3D getCartesianPosition(Planet planet)
{
if (_cartesianPosition == null)
{
_cartesianPosition = new Vector3D(planet.toCartesian(_position));
}
return _cartesianPosition;
}
public final void setMinDistanceToCamera(double minDistanceToCamera)
{
_minDistanceToCamera = minDistanceToCamera;
}
public final double getMinDistanceToCamera()
{
return _minDistanceToCamera;
}
public final void render(G3MRenderContext rc, Vector3D cameraPosition, GLState parentGLState)
{
final Planet planet = rc.getPlanet();
final Vector3D markPosition = getCartesianPosition(planet);
final Vector3D markCameraVector = markPosition.sub(cameraPosition);
// mark will be renderered only if is renderable by distance and placed on a visible globe area
boolean renderableByDistance;
if (_minDistanceToCamera == 0)
{
renderableByDistance = true;
}
else
{
final double squaredDistanceToCamera = markCameraVector.squaredLength();
renderableByDistance = (squaredDistanceToCamera <= (_minDistanceToCamera * _minDistanceToCamera));
}
_renderedMark = false;
if (renderableByDistance)
{
final Vector3D normalAtMarkPosition = planet.geodeticSurfaceNormal(markPosition);
if (normalAtMarkPosition.angleBetween(markCameraVector)._radians > IMathUtils.instance().halfPi())
{
if (_textureId == null)
{
if (_textureImage != null)
{
_textureId = rc.getTexturesHandler().getGLTextureId(_textureImage, GLFormat.rgba(), _imageID, false);
rc.getFactory().deleteImage(_textureImage);
_textureImage = null;
_viewportWidth = rc.getCurrentCamera().getWidth();
_viewportHeight = rc.getCurrentCamera().getHeight();
createGLState();
}
}
else
{
if (rc.getCurrentCamera().getWidth() != _viewportWidth || rc.getCurrentCamera().getHeight() != _viewportHeight)
{
_viewportWidth = rc.getCurrentCamera().getWidth();
_viewportHeight = rc.getCurrentCamera().getHeight();
createGLState(); //Ready for rendering
}
}
if (_textureId != null)
{
GL gl = rc.getGL();
GPUProgramManager progManager = rc.getGPUProgramManager();
_glState.setParent(parentGLState); //Linking with parent
gl.drawArrays(GLPrimitive.triangleStrip(), 0, 4, _glState, progManager);
_renderedMark = true;
}
}
}
}
} |
package org.mtransit.parser.ca_moncton_codiac_transpo_bus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MDirectionType;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
public class MonctonCodiacTranspoBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-moncton-codiac-transpo-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new MonctonCodiacTranspoBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating Codiac Transpo bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("\nGenerating Codiac Transpo bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public boolean excludeRoute(GRoute gRoute) {
return super.excludeRoute(gRoute);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
private static final long RID_ENDS_WITH_B = 20_000L;
private static final long RID_ENDS_WITH_C = 30_000L;
private static final long RID_ENDS_WITH_P = 160_000L;
private static final long RID_ENDS_WITH_S = 190_000L;
private static final long RID_ENDS_WITH_C1 = 27L * 10_000L;
private static final long RID_ENDS_WITH_C2 = 28L * 10_000L;
private static final long RID_ENDS_WITH_LT = 29L * 10_000L;
private static final long RID_ENDS_WITH_LTS = 30L * 10_000L;
private static final String B = "b";
private static final String C = "c";
private static final String P = "p";
private static final String S = "s";
private static final String C1 = "c1";
private static final String C2 = "c2";
private static final String LT = "lt";
private static final String LTS = "lts";
private static final long RID_MM = 99_000L;
private static final String MM_RID = "MM";
@Override
public long getRouteId(GRoute gRoute) {
String rsn = gRoute.getRouteId().toLowerCase(Locale.ENGLISH);
if (Utils.isDigitsOnly(rsn)) {
return Long.parseLong(rsn); // use route short name as route ID
}
if (MM_RID.equalsIgnoreCase(rsn)) {
return RID_MM;
}
Matcher matcher = DIGITS.matcher(rsn);
if (matcher.find()) {
long id = Long.parseLong(matcher.group());
if (rsn.endsWith(LTS)) {
return RID_ENDS_WITH_LTS + id;
} else if (rsn.endsWith(LT)) {
return RID_ENDS_WITH_LT + id;
} else if (rsn.endsWith(B)) {
return RID_ENDS_WITH_B + id;
} else if (rsn.endsWith(C)) {
return RID_ENDS_WITH_C + id;
} else if (rsn.endsWith(P)) {
return RID_ENDS_WITH_P + id;
} else if (rsn.endsWith(S)) {
return RID_ENDS_WITH_S + id;
} else if (rsn.endsWith(C1)) {
return RID_ENDS_WITH_C1 + id;
} else if (rsn.endsWith(C2)) {
return RID_ENDS_WITH_C2 + id;
}
}
System.out.printf("\nUnexpected route ID for %s!\n", gRoute);
System.exit(-1);
return -1l;
}
@Override
public String getRouteShortName(GRoute gRoute) {
return gRoute.getRouteId().toUpperCase(Locale.ENGLISH);
}
@Override
public boolean mergeRouteLongName(MRoute mRoute, MRoute mRouteToMerge) {
System.out.printf("\nUnexpected routes to merge %s & %s!\n", mRoute, mRouteToMerge);
System.exit(-1);
return false;
}
private static final String AGENCY_COLOR_GREEN = "005238"; // GREEN (from PDF)
private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@Override
public String getRouteColor(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteColor())) {
long routeId = getRouteId(gRoute);
switch ((int) routeId) {
// @formatter:off
case 50: return "ED1D24";
case 51: return "00A651";
case 52: return "0072BC";
case 60: return "E977AF";
case 61: return "684287";
case 62: return "DC62A4";
case 63: return "F7941E";
case 64: return "A6664C";
case 65: return "FBAF34";
case 66: return "65A6BB";
case 67: return "2E3092";
case 68: return "00AEEF";
case 70: return "3EC7F4";
case 71: return "8DC63F";
case 72: return "8DC63F";
case 80: return "CF8B2D";
case 81: return "942976";
case 93: return "8FB73E";
case 94: return "41827C";
case 95: return "F58473";
case 939495: return null; // agency color
// @formatter:on
}
if (RID_MM == routeId) {
return null; // agency color
} else if (60L + RID_ENDS_WITH_LT == routeId) {
return "E977AF"; // same as 60
} else if (60L + RID_ENDS_WITH_LTS == routeId) {
return "E977AF"; // same as 60
} else if (60_67L + RID_ENDS_WITH_C == routeId) { // 6067C
return null; // agency color
} else if (61L + RID_ENDS_WITH_B == routeId) { // 61B
return "B0A0C5";
} else if (80_81L + RID_ENDS_WITH_C1 == routeId) { // 8081C1
return null; // agency color
} else if (80_81L + RID_ENDS_WITH_C2 == routeId) { // 8081C2
return null; // agency color
} else if (81L + RID_ENDS_WITH_S == routeId) { // 81S
return "942976"; // same as 81
}
System.out.printf("\nUnexpected route color for %s!\n", gRoute);
System.exit(-1);
return null;
}
return super.getRouteColor(gRoute);
}
private static final String PLAZA_BLVD = "Plz Blvd";
private static final String _140_MILLENNIUM = "140 Millennium";
private static final String _1111_MAIN = "1111 Main";
private static final String ELMWOOD = "Elmwood";
private static final String CHAMPLAIN_PL = "Champlain Pl";
private static final String CALEDONIA = "Caledonia";
private static final String HIGHFIELD_SQ = "Highfield Sq";
private static final String BESSBOROUGH = "Bessborough";
private static final String GAGNON_SHEDIAC = "Gagnon / Shediac";
private static final String KILLAM = "Killam";
private static final String HOSPITALS = "Hospitals";
private static final String EDINBURGH = "Edinburgh";
private static final String KE_SPENCER_MEMORIAL_HOME = "KE Spencer Memorial Home";
private static final String CRANDALL_U = "Crandall U";
private static final String COLISEUM = "Coliseum";
private static final String BRIDGEDALE = "Bridgedale";
private static final String RIVERVIEW = "Riverview";
private static final String ADÉLARD_SAVOIE_DIEPPE_BLVD = "Adélard-Savoie / Dieppe Blvd";
private static final String BOURQUE_CHARTERSVILLE = "Bourque / Chartersville";
private static final String SALISBURY_RD = "Salisbury Rd";
private static final String FOX_CRK_AMIRAULT = "Fox Crk / Amirault";
private static final String MOUNTAIN = "Mountain";
private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>();
map2.put(50L, new RouteTripSpec(50L,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLAZA_BLVD)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] {
"6810785", // Plaza Blvd (Walmart)
"6810205",
"6810200", // CF Champlain
}))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] {
"6810200", // CF Champlain
"6810202",
"6810785", // Plaza Blvd (Walmart)
}))
.compileBothTripSort());
map2.put(50l + RID_ENDS_WITH_S, new RouteTripSpec(50l + RID_ENDS_WITH_S, // 50 S
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLAZA_BLVD)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] { "6810785", "6810205", "6810200" }))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] { "6810200", "6810202", "6810785" }))
.compileBothTripSort());
map2.put(51l, new RouteTripSpec(51l,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, _1111_MAIN,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLAZA_BLVD)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] { "6810785", "6810225", "6810234" }))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] { "6810234", "6810241", "6810785" }))
.compileBothTripSort());
map2.put(512100l, new RouteTripSpec(512100l,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, _1111_MAIN,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Trinity Dr") // PLAZA_BLVD
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] {
"6810786", // Trinity Drive
"6810225",
"6810234" // 1111 Main
}))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] {
"6810234", // 1111 Main
"6810241",
"6810786", // Trinity Drive
}))
.compileBothTripSort());
map2.put(52l, new RouteTripSpec(52l,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, _1111_MAIN)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] { "6810234", "6810253", "6810200" }))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] { "6810200", "6810263", "6810234" }))
.compileBothTripSort());
map2.put(60l, new RouteTripSpec(60l,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, _1111_MAIN,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, BESSBOROUGH)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] { "6810277", "6810770", "6810286", "6810234" }))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] { "6810234", "6810763", "6810277" }))
.compileBothTripSort());
map2.put(6067L + RID_ENDS_WITH_C, new RouteTripSpec(6067L + RID_ENDS_WITH_C, // 6067C
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, _1111_MAIN,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, BESSBOROUGH)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] {
"6810277", // 1000 St George (Bessborough)
"6810771",
"6810234" // 1111 Main
}))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] {
"6810234", // 1111 Main
"6810763",
"6810277" // 1000 St George (Bessborough)
}))
.compileBothTripSort());
map2.put(60l + RID_ENDS_WITH_LT, new RouteTripSpec(60l + RID_ENDS_WITH_LT, // 60LT
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, _1111_MAIN,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, SALISBURY_RD)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] {
"6810483", // Atlantic Baptist
"6810770",
"6810234" // 1111 Main
}))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] {
"6810234", // 1111 Main
"6810471",
"6810483" // Atlantic Baptist
}))
.compileBothTripSort());
map2.put(60l + RID_ENDS_WITH_LTS, new RouteTripSpec(60l + RID_ENDS_WITH_LTS, // 60LTS
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, _140_MILLENNIUM,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, SALISBURY_RD)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] { "6810483", "6810770", "6810286" }))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] { "6810234", "6810483" }))
.compileBothTripSort());
map2.put(61l, new RouteTripSpec(61l,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, ELMWOOD,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] {
"6810200", // CF Champlain
"6810298",
"6810309", // Hennessey Petro-Canada
}))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] {
"6810309", // Hennessey Petro-Canada
"6810781", // ++ 54 Elmwood Dr
"6810316",
"6810200", // CF Champlain
}))
.compileBothTripSort());
map2.put(61l + RID_ENDS_WITH_B, new RouteTripSpec(61l + RID_ENDS_WITH_B, // 61B
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, ELMWOOD,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] {
"6810200", // CF Champlain
"6810422",
"6810954", // 603 Elmwood
}))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] {
"6810954", // 603 Elmwood
"6810962",
"6810200", // CF Champlain
}))
.compileBothTripSort());
map2.put(62L, new RouteTripSpec(62L,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLAZA_BLVD,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, MOUNTAIN) // CASINO
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] {
"6811115", // Mountain at Turnaround
"6810330",
"6810808", // 1576 Mountain
"6810390",
"6810785" // Plaza Blvd (Walmart)
}))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] {
"6810785", // Plaza Blvd (Walmart)
"6810916",
"6811115", // Mountain at Turnaround
}))
.compileBothTripSort());
map2.put(63l, new RouteTripSpec(63l,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, GAGNON_SHEDIAC,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] { "6810200", "6810347", "6810702" }))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] { "6810702", "6810703", "6810200" }))
.compileBothTripSort());
map2.put(64l, new RouteTripSpec(64l,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, HOSPITALS,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, _1111_MAIN)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] { "6810234", "6810376", "6810380" }))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] { "6810380", "6810757", "6810234" }))
.compileBothTripSort());
map2.put(64l + RID_ENDS_WITH_B, new RouteTripSpec(64l + RID_ENDS_WITH_B, // 64B
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, HOSPITALS,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, _1111_MAIN) // HIGHFIELD_SQ
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] {
"6810234", "6810747", "6810401"
}))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] {
"6810401", "6810727", "6810234"
}))
.compileBothTripSort());
map2.put(65l, new RouteTripSpec(65l,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLAZA_BLVD,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, KILLAM)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] {
"6810406", // 25 Killam (Asian Garden)
"6810408", // 121 Killam (Chubby's Variety)
"6810906",
"6810785", // Plaza Blvd (Walmart)
}))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] {
"6810785", // Plaza Blvd (Walmart)
"6810809",
"6810401",
"6810406" // 25 Killam (Asian Garden)
}))
.compileBothTripSort());
map2.put(66l, new RouteTripSpec(66l,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, CALEDONIA,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, HIGHFIELD_SQ)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] {
"6810413", // 1110 Main
"6810419",
"6810883",
}))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] {
"6810883",
"6811032",
"6810413", // 1110 Main
}))
.compileBothTripSort());
map2.put(67l, new RouteTripSpec(67l,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, HIGHFIELD_SQ,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, EDINBURGH)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] { "6810806", "6810768", "6810413" }))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] { "6810413", "6810799", "6810806" }))
.compileBothTripSort());
map2.put(68l, new RouteTripSpec(68l,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, HIGHFIELD_SQ,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, KE_SPENCER_MEMORIAL_HOME)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] { "6810483", "6810493", "6810413" }))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] { "6810413", "6810471", "6810483" }))
.compileBothTripSort());
map2.put(70L, new RouteTripSpec(70L,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, CRANDALL_U,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLAZA_BLVD)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] {
"6811029", // South Plaza Sud
"6811015",
"6811055", // Crandall Entrance
}))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] {
"6811055", // Crandall Entrance
"6810520",
"6811029", // South Plaza Sud
}))
.compileBothTripSort());
map2.put(71L, new RouteTripSpec(71L,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLAZA_BLVD,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLISEUM)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] {
"6810841", // Coliseum Entrance
"6810537",
"6810808", // 1576 Mountain
"6811029", // South Plaza Sud
}))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] {
"6811029", // South Plaza Sud
"6811111",
"6810841" // Coliseum Entrance
}))
.compileBothTripSort());
map2.put(72L, new RouteTripSpec(72L,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, HOSPITALS)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] {
"6810401", // 114 MacBeath (across Hospital)
"6810378",
"6810200", // CF Champlain
}))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] {
"6810200", // CF Champlain
"6810747",
"6810401", // 114 MacBeath (across Hospital)
}))
.compileBothTripSort());
map2.put(80l, new RouteTripSpec(80l,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, HIGHFIELD_SQ,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, BRIDGEDALE)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] { "6810552", "6810561", "6810413" }))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] { "6810413", "6810544", "6810552" }))
.compileBothTripSort());
map2.put(8081l + RID_ENDS_WITH_C1, new RouteTripSpec(8081l + RID_ENDS_WITH_C1, // 80-81 c1
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, HIGHFIELD_SQ,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, BRIDGEDALE)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] { "6810552", "6810561", "6810413" }))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] { "6810413", "6810544", "6810552" }))
.compileBothTripSort());
map2.put(8081L + RID_ENDS_WITH_C2, new RouteTripSpec(8081L + RID_ENDS_WITH_C2, // 80-81 c2
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, HIGHFIELD_SQ,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, RIVERVIEW)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] {
"6810568", // Riverview Place
"6810497",
"6810413", // 1110 Main (Events Centre)
}))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] {
"6810413", // 1110 Main (Events Centre)
"6810552", // ++ Manning @ Hillsborough
"6810566", // ++ Hillsborough across Hillview
"6810568", // Riverview Place
}))
.compileBothTripSort());
map2.put(81l, new RouteTripSpec(81l,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, HIGHFIELD_SQ,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, RIVERVIEW)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] { "6810588", "6810568", "6810413" }))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] { "6810413", "6810568", "6810588" }))
.compileBothTripSort());
map2.put(81l + RID_ENDS_WITH_S, new RouteTripSpec(81l + RID_ENDS_WITH_S, // 81S
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, HIGHFIELD_SQ,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, RIVERVIEW)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] { "6810589", "6810568", "6810413" }))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] { "6810413", "6810568", "6810589" }))
.compileBothTripSort());
map2.put(93l, new RouteTripSpec(93l,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, ADÉLARD_SAVOIE_DIEPPE_BLVD,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] {
"6810200", // CF Champlain
"6810613",
"6810986", // Dieppe Blvd (Arc. Quality Inn)
}))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] {
"6810986", // Dieppe Blvd (Arc. Quality Inn)
"6810880",
"6810200", // CF Champlain
}))
.compileBothTripSort());
map2.put(939495l, new RouteTripSpec(939495l,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, FOX_CRK_AMIRAULT)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] { "6810668", "6810982", "6810200" }))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] { "6810200", "6810664", "6810668" }))
.compileBothTripSort());
map2.put(94l, new RouteTripSpec(94l,
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, BOURQUE_CHARTERSVILLE,
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL)
.addTripSort(MDirectionType.EAST.intValue(),
Arrays.asList(new String[] { "6810200", "6810978", "6810935" }))
.addTripSort(MDirectionType.WEST.intValue(),
Arrays.asList(new String[] { "6810935", "6810982", "6810200" }))
.compileBothTripSort());
map2.put(95l, new RouteTripSpec(95l,
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, CHAMPLAIN_PL,
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, FOX_CRK_AMIRAULT)
.addTripSort(MDirectionType.NORTH.intValue(),
Arrays.asList(new String[] { "6811002", "6810859", "6810200" }))
.addTripSort(MDirectionType.SOUTH.intValue(),
Arrays.asList(new String[] { "6810200", "6810664", "6811002" }))
.compileBothTripSort());
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
String tripHeadsign = gTrip.getTripHeadsign();
if (StringUtils.isEmpty(tripHeadsign)) {
tripHeadsign = mRoute.getLongName();
}
int directionId = gTrip.getDirectionId() == null ? 0 : gTrip.getDirectionId();
mTrip.setHeadsignString(cleanTripHeadsign(tripHeadsign), directionId);
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
System.out.printf("\nUnexpected trips to merge %s & %s!\n", mTrip, mTripToMerge);
System.exit(-1);
return false;
}
private static final Pattern TOWARDS = Pattern.compile("((^|\\W){1}(towards)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
@Override
public String cleanTripHeadsign(String tripHeadsign) {
Matcher matcherTOWARDS = TOWARDS.matcher(tripHeadsign);
if (matcherTOWARDS.find()) {
String gTripHeadsignAfterTOWARDS = tripHeadsign.substring(matcherTOWARDS.end());
tripHeadsign = gTripHeadsignAfterTOWARDS;
}
tripHeadsign = CleanUtils.removePoints(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private static final Pattern UNIVERSITY_ENCODING = Pattern.compile("((^|\\W){1}(universit)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String UNIVERSITY_ENCODING_REPLACEMENT = "$2University$4";
private static final Pattern ADELARD_ENCODING = Pattern.compile("((^|\\W){1}(adlard)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String ADELARD_ENCODING_REPLACEMENT = "$2Adelard$4";
@Override
public String cleanStopName(String gStopName) {
gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = UNIVERSITY_ENCODING.matcher(gStopName).replaceAll(UNIVERSITY_ENCODING_REPLACEMENT);
gStopName = ADELARD_ENCODING.matcher(gStopName).replaceAll(ADELARD_ENCODING_REPLACEMENT);
gStopName = CleanUtils.cleanSlashes(gStopName);
gStopName = CleanUtils.removePoints(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
} |
package io.spacedog.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = Visibility.ANY,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE)
public class GeoPoint {
public double lat;
public double lon;
public GeoPoint() {
}
public GeoPoint(double lat, double lon) {
this.lat = lat;
this.lon = lon;
}
@Override
public String toString() {
return "{" + lat + ", " + lon + "}";
}
} |
package org.frcbitbucketbase.control.profile;
import org.frcbitbucketbase.control.KinematicController;
import org.frcbitbucketbase.control.MovementVector;
/**
* An base class for motion profiles.
*
* @author Miles Marchant
* @version 0.9
*
*/
public abstract class Profile<T> {
protected Spline[] splines;
public Profile(){}
public abstract T getOutput(long time);
protected abstract void generateSplines(MovementVector values);
public abstract void regenerateSplines(double drive);
public abstract boolean finished(long time);
public void setSplines(Spline[] splines){
this.splines = splines;
}
} |
package org.postgresql.jdbc1;
import java.io.IOException;
import java.net.ConnectException;
import java.sql.*;
import java.util.*;
import org.postgresql.Driver;
import org.postgresql.PGNotification;
import org.postgresql.core.BaseConnection;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.BaseStatement;
import org.postgresql.core.Encoding;
import org.postgresql.core.PGStream;
import org.postgresql.core.QueryExecutor;
import org.postgresql.core.StartupPacket;
import org.postgresql.fastpath.Fastpath;
import org.postgresql.largeobject.LargeObjectManager;
import org.postgresql.util.MD5Digest;
import org.postgresql.util.PGobject;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.PSQLWarning;
import org.postgresql.util.ServerErrorMessage;
import org.postgresql.util.UnixCrypt;
public abstract class AbstractJdbc1Connection implements BaseConnection
{
// This is the network stream associated with this connection
private PGStream pgStream;
public PGStream getPGStream() {
return pgStream;
}
protected String PG_HOST;
protected int PG_PORT;
protected String PG_USER;
protected String PG_DATABASE;
protected boolean PG_STATUS;
protected String compatible;
protected boolean useSSL;
protected int prepareThreshold;
// The PID an cancellation key we get from the backend process
protected int pid;
protected int ckey;
private Vector m_notifications;
/*
The encoding to use for this connection.
*/
private Encoding encoding = Encoding.defaultEncoding();
private String dbVersionNumber = "0.0"; // Dummy version until we really know.
public boolean CONNECTION_OK = true;
public boolean CONNECTION_BAD = false;
public boolean autoCommit = true;
public boolean inTransaction = false;
public boolean readOnly = false;
public Driver this_driver;
private String this_url;
private String cursor = null; // The positioned update cursor name
private int PGProtocolVersionMajor = 2;
private int PGProtocolVersionMinor = 0;
public int getPGProtocolVersionMajor() { return PGProtocolVersionMajor; }
public int getPGProtocolVersionMinor() { return PGProtocolVersionMinor; }
private static final int AUTH_REQ_OK = 0;
private static final int AUTH_REQ_KRB4 = 1;
private static final int AUTH_REQ_KRB5 = 2;
private static final int AUTH_REQ_PASSWORD = 3;
private static final int AUTH_REQ_CRYPT = 4;
private static final int AUTH_REQ_MD5 = 5;
private static final int AUTH_REQ_SCM = 6;
// These are used to cache oids, PGTypes and SQLTypes
private static Hashtable sqlTypeCache = new Hashtable(); // oid -> SQLType
private static Hashtable pgTypeCache = new Hashtable(); // oid -> PGType
private static Hashtable typeOidCache = new Hashtable(); //PGType -> oid
// Now handle notices as warnings, so things like "show" now work
public SQLWarning firstWarning = null;
/*
* Cache of the current isolation level
*/
private int isolationLevel = Connection.TRANSACTION_READ_COMMITTED;
public abstract Statement createStatement() throws SQLException;
public abstract DatabaseMetaData getMetaData() throws SQLException;
/*
* This method actually opens the connection. It is called by Driver.
*
* @param host the hostname of the database back end
* @param port the port number of the postmaster process
* @param info a Properties[] thing of the user and password
* @param database the database to connect to
* @param url the URL of the connection
* @param d the Driver instantation of the connection
* @exception SQLException if a database access error occurs
*/
public void openConnection(String host, int port, Properties info, String database, String url, Driver d) throws SQLException
{
firstWarning = null;
// Throw an exception if the user or password properties are missing
// This occasionally occurs when the client uses the properties version
// of getConnection(), and is a common question on the email lists
if (info.getProperty("user") == null)
throw new PSQLException("postgresql.con.user", PSQLState.CONNECTION_REJECTED);
this_driver = (Driver)d;
this_url = url;
PG_DATABASE = database;
PG_USER = info.getProperty("user");
String password = info.getProperty("password", "");
PG_PORT = port;
PG_HOST = host;
PG_STATUS = CONNECTION_BAD;
useSSL = false;
if (info.getProperty("ssl") != null)
{
if (Driver.sslEnabled())
{
useSSL = true;
}
else
{
throw new PSQLException("postgresql.con.driversslnotsupported", PSQLState.CONNECTION_FAILURE);
}
}
if (info.getProperty("compatible") == null)
{
compatible = d.getMajorVersion() + "." + d.getMinorVersion();
}
else
{
compatible = info.getProperty("compatible");
}
//Read loglevel arg and set the loglevel based on this value
//in addition to setting the log level enable output to
//standard out if no other printwriter is set
String l_logLevelProp = info.getProperty("loglevel", "0");
int l_logLevel = 0;
try
{
l_logLevel = Integer.parseInt(l_logLevelProp);
if (l_logLevel > Driver.DEBUG || l_logLevel < Driver.INFO)
{
l_logLevel = 0;
}
}
catch (Exception l_e)
{
//invalid value for loglevel ignore
}
if (l_logLevel > 0)
{
Driver.setLogLevel(l_logLevel);
enableDriverManagerLogging();
}
prepareThreshold = 0;
try {
prepareThreshold = Integer.parseInt(info.getProperty("prepareThreshold", "0"));
} catch (Exception e) {}
if (prepareThreshold < 0)
prepareThreshold = 0;
//Print out the driver version number
if (Driver.logInfo)
Driver.info(Driver.getVersion());
if (Driver.logDebug) {
Driver.debug(" ssl = " + useSSL);
Driver.debug(" compatible = " + compatible);
Driver.debug(" loglevel = " + l_logLevel);
Driver.debug(" prepare threshold = " + prepareThreshold);
}
// Now make the initial connection
try
{
pgStream = new PGStream(host, port);
}
catch (ConnectException cex)
{
// Added by Peter Mount <peter@retep.org.uk>
// ConnectException is thrown when the connection cannot be made.
// we trap this an return a more meaningful message for the end user
throw new PSQLException ("postgresql.con.refused", PSQLState.CONNECTION_REJECTED, cex);
}
catch (IOException e)
{
throw new PSQLException ("postgresql.con.failed", PSQLState.CONNECTION_UNABLE_TO_CONNECT, e);
}
try {
//Now do the protocol work
if (haveMinimumCompatibleVersion("7.4")) {
openConnectionV3(host,port,info,database,url,d,password);
} else {
openConnectionV2(host,port,info,database,url,d,password);
}
} catch (SQLException sqle) {
// if we fail to completely establish a connection,
// close down the socket to not leak resources.
try {
pgStream.close();
} catch (IOException ioe) { }
throw sqle;
}
}
private void openConnectionV3(String p_host, int p_port, Properties p_info, String p_database, String p_url, Driver p_d, String p_password) throws SQLException
{
// NOTE: To simplify this code, it is assumed that if we are
// using the V3 protocol, then the database is at least 7.4. That
// eliminates the need to check database versions and maintain
// backward-compatible code here.
// Change by Chris Smith <cdsmith@twu.net>
PGProtocolVersionMajor = 3;
if (Driver.logDebug)
Driver.debug("Using Protocol Version3");
// Now we need to construct and send an ssl startup packet
try
{
if (useSSL) {
if (Driver.logDebug)
Driver.debug("Asking server if it supports ssl");
pgStream.SendInteger(8,4);
pgStream.SendInteger(80877103,4);
// now flush the ssl packets to the backend
pgStream.flush();
// Now get the response from the backend, either an error message
// or an authentication request
int beresp = pgStream.ReceiveChar();
if (Driver.logDebug)
Driver.debug("Server response was (S=Yes,N=No): "+(char)beresp);
switch (beresp)
{
case 'E':
// An error occured, so pass the error message to the
// user.
// The most common one to be thrown here is:
// "User authentication failed"
throw new PSQLException("postgresql.con.misc", PSQLState.CONNECTION_REJECTED, pgStream.ReceiveString(encoding));
case 'N':
// Server does not support ssl
throw new PSQLException("postgresql.con.sslnotsupported", PSQLState.CONNECTION_FAILURE);
case 'S':
// Server supports ssl
if (Driver.logDebug)
Driver.debug("server does support ssl");
Driver.makeSSL(pgStream);
break;
default:
throw new PSQLException("postgresql.con.sslfail", PSQLState.CONNECTION_FAILURE);
}
}
}
catch (IOException e)
{
throw new PSQLException("postgresql.con.failed", PSQLState.CONNECTION_UNABLE_TO_CONNECT, e);
}
// Now we need to construct and send a startup packet
try
{
Hashtable params = new Hashtable();
params.put("client_encoding", "UNICODE");
params.put("DateStyle", "ISO");
new StartupPacket(PGProtocolVersionMajor,
PGProtocolVersionMinor,
PG_USER, p_database, params)
.writeTo(pgStream);
// now flush the startup packets to the backend
pgStream.flush();
// The startup request has been sent with the UNICODE encoding.
// From here out, everything should be in Unicode.
encoding = Encoding.getEncoding("UNICODE", null);
// Now get the response from the backend, either an error message
// or an authentication request
int areq = -1; // must have a value here
do
{
int beresp = pgStream.ReceiveChar();
String salt = null;
byte [] md5Salt = new byte[4];
switch (beresp)
{
case 'E':
// An error occured, so pass the error message to the
// user.
// The most common one to be thrown here is:
// "User authentication failed"
int l_elen = pgStream.ReceiveIntegerR(4);
if (l_elen > 30000) {
//if the error length is > than 30000 we assume this is really a v2 protocol
//server so try again with a v2 connection
//need to create a new connection and try again
pgStream.close();
try
{
pgStream = new PGStream(p_host, p_port);
}
catch (ConnectException cex)
{
// Added by Peter Mount <peter@retep.org.uk>
// ConnectException is thrown when the connection cannot be made.
// we trap this an return a more meaningful message for the end user
throw new PSQLException ("postgresql.con.refused", PSQLState.CONNECTION_REJECTED);
}
catch (IOException e)
{
throw new PSQLException ("postgresql.con.failed", PSQLState.CONNECTION_UNABLE_TO_CONNECT, e);
}
openConnectionV2(p_host, p_port, p_info, p_database, p_url, p_d, p_password);
return;
}
ServerErrorMessage l_errorMsg = new ServerErrorMessage(encoding.decode(pgStream.Receive(l_elen-4)));
throw new PSQLException("postgresql.con.misc", new PSQLState(l_errorMsg.getSQLState()), l_errorMsg);
case 'R':
// Get the message length
int l_msgLen = pgStream.ReceiveIntegerR(4);
// Get the type of request
areq = pgStream.ReceiveIntegerR(4);
// Get the crypt password salt if there is one
if (areq == AUTH_REQ_CRYPT)
{
byte[] rst = new byte[2];
rst[0] = (byte)pgStream.ReceiveChar();
rst[1] = (byte)pgStream.ReceiveChar();
salt = new String(rst, 0, 2);
if (Driver.logDebug)
Driver.debug("Crypt salt=" + salt);
}
// Or get the md5 password salt if there is one
if (areq == AUTH_REQ_MD5)
{
md5Salt[0] = (byte)pgStream.ReceiveChar();
md5Salt[1] = (byte)pgStream.ReceiveChar();
md5Salt[2] = (byte)pgStream.ReceiveChar();
md5Salt[3] = (byte)pgStream.ReceiveChar();
if (Driver.logDebug) {
String md5SaltString = "";
for (int i=0; i<md5Salt.length; i++) {
md5SaltString += " " + md5Salt[i];
}
Driver.debug("MD5 salt=" + md5SaltString);
}
}
// now send the auth packet
switch (areq)
{
case AUTH_REQ_OK:
break;
case AUTH_REQ_KRB4:
if (Driver.logDebug)
Driver.debug("postgresql: KRB4");
throw new PSQLException("postgresql.con.kerb4", PSQLState.CONNECTION_REJECTED);
case AUTH_REQ_KRB5:
if (Driver.logDebug)
Driver.debug("postgresql: KRB5");
throw new PSQLException("postgresql.con.kerb5", PSQLState.CONNECTION_REJECTED);
case AUTH_REQ_SCM:
if (Driver.logDebug)
Driver.debug("postgresql: SCM");
throw new PSQLException("postgresql.con.scm", PSQLState.CONNECTION_REJECTED);
case AUTH_REQ_PASSWORD:
if (Driver.logDebug)
Driver.debug("postgresql: PASSWORD");
pgStream.SendChar('p');
pgStream.SendInteger(5 + p_password.length(), 4);
pgStream.Send(p_password.getBytes());
pgStream.SendChar(0);
pgStream.flush();
break;
case AUTH_REQ_CRYPT:
if (Driver.logDebug)
Driver.debug("postgresql: CRYPT");
String crypted = UnixCrypt.crypt(salt, p_password);
pgStream.SendChar('p');
pgStream.SendInteger(5 + crypted.length(), 4);
pgStream.Send(crypted.getBytes());
pgStream.SendChar(0);
pgStream.flush();
break;
case AUTH_REQ_MD5:
if (Driver.logDebug)
Driver.debug("postgresql: MD5");
byte[] digest = MD5Digest.encode(PG_USER, p_password, md5Salt);
pgStream.SendChar('p');
pgStream.SendInteger(5 + digest.length, 4);
pgStream.Send(digest);
pgStream.SendChar(0);
pgStream.flush();
break;
default:
throw new PSQLException("postgresql.con.auth", PSQLState.CONNECTION_REJECTED, new Integer(areq));
}
break;
default:
throw new PSQLException("postgresql.con.authfail", PSQLState.CONNECTION_REJECTED);
}
}
while (areq != AUTH_REQ_OK);
}
catch (IOException e)
{
throw new PSQLException("postgresql.con.failed", PSQLState.CONNECTION_UNABLE_TO_CONNECT, e);
}
int beresp;
do
{
beresp = pgStream.ReceiveChar();
switch (beresp)
{
case 'Z':
//ready for query
break;
case 'K':
int l_msgLen = pgStream.ReceiveIntegerR(4);
if (l_msgLen != 12) throw new PSQLException("postgresql.con.setup", PSQLState.CONNECTION_UNABLE_TO_CONNECT);
pid = pgStream.ReceiveIntegerR(4);
ckey = pgStream.ReceiveIntegerR(4);
break;
case 'E':
int l_elen = pgStream.ReceiveIntegerR(4);
ServerErrorMessage l_errorMsg = new ServerErrorMessage(encoding.decode(pgStream.Receive(l_elen-4)));
throw new PSQLException("postgresql.con.backend", new PSQLState(l_errorMsg.getSQLState()), l_errorMsg);
case 'N':
int l_nlen = pgStream.ReceiveIntegerR(4);
ServerErrorMessage l_warnMsg = new ServerErrorMessage(encoding.decode(pgStream.Receive(l_nlen-4)));
addWarning(new PSQLWarning(l_warnMsg));
break;
case 'S':
//TODO: handle parameter status messages
int l_len = pgStream.ReceiveIntegerR(4);
String name = pgStream.ReceiveString(encoding);
String value = pgStream.ReceiveString(encoding);
if (Driver.logDebug)
Driver.debug("ParameterStatus: " + name + "=" + value);
if (name.equals("server_version"))
{
dbVersionNumber = value;
}
break;
default:
if (Driver.logDebug)
Driver.debug("invalid state="+ (char)beresp);
throw new PSQLException("postgresql.con.setup", PSQLState.CONNECTION_UNABLE_TO_CONNECT);
}
}
while (beresp != 'Z');
// read ReadyForQuery
if (pgStream.ReceiveIntegerR(4) != 5) throw new PSQLException("postgresql.con.setup", PSQLState.CONNECTION_UNABLE_TO_CONNECT);
//TODO: handle transaction status
char l_tStatus = (char)pgStream.ReceiveChar();
// Initialise object handling
initObjectTypes();
// Mark the connection as ok, and cleanup
PG_STATUS = CONNECTION_OK;
}
private void openConnectionV2(String host, int port, Properties info, String database, String url, Driver d, String password) throws SQLException
{
PGProtocolVersionMajor = 2;
if (Driver.logDebug)
Driver.debug("Using Protocol Version2");
// Now we need to construct and send an ssl startup packet
try
{
if (useSSL) {
if (Driver.logDebug)
Driver.debug("Asking server if it supports ssl");
pgStream.SendInteger(8,4);
pgStream.SendInteger(80877103,4);
// now flush the ssl packets to the backend
pgStream.flush();
// Now get the response from the backend, either an error message
// or an authentication request
int beresp = pgStream.ReceiveChar();
if (Driver.logDebug)
Driver.debug("Server response was (S=Yes,N=No): "+(char)beresp);
switch (beresp)
{
case 'E':
// An error occured, so pass the error message to the
// user.
// The most common one to be thrown here is:
// "User authentication failed"
throw new PSQLException("postgresql.con.misc", PSQLState.CONNECTION_REJECTED, pgStream.ReceiveString(encoding));
case 'N':
// Server does not support ssl
throw new PSQLException("postgresql.con.sslnotsupported", PSQLState.CONNECTION_FAILURE);
case 'S':
// Server supports ssl
if (Driver.logDebug)
Driver.debug("server does support ssl");
Driver.makeSSL(pgStream);
break;
default:
throw new PSQLException("postgresql.con.sslfail", PSQLState.CONNECTION_FAILURE);
}
}
}
catch (IOException e)
{
throw new PSQLException("postgresql.con.failed", PSQLState.CONNECTION_UNABLE_TO_CONNECT, e);
}
// Now we need to construct and send a startup packet
try
{
new StartupPacket(PGProtocolVersionMajor,
PGProtocolVersionMinor,
PG_USER,
database).writeTo(pgStream);
// now flush the startup packets to the backend
pgStream.flush();
// Now get the response from the backend, either an error message
// or an authentication request
int areq = -1; // must have a value here
do
{
int beresp = pgStream.ReceiveChar();
String salt = null;
byte [] md5Salt = new byte[4];
switch (beresp)
{
case 'E':
// An error occured, so pass the error message to the
// user.
// The most common one to be thrown here is:
// "User authentication failed"
throw new PSQLException("postgresql.con.misc", PSQLState.CONNECTION_REJECTED, pgStream.ReceiveString(encoding));
case 'R':
// Get the type of request
areq = pgStream.ReceiveIntegerR(4);
// Get the crypt password salt if there is one
if (areq == AUTH_REQ_CRYPT)
{
byte[] rst = new byte[2];
rst[0] = (byte)pgStream.ReceiveChar();
rst[1] = (byte)pgStream.ReceiveChar();
salt = new String(rst, 0, 2);
if (Driver.logDebug)
Driver.debug("Crypt salt=" + salt);
}
// Or get the md5 password salt if there is one
if (areq == AUTH_REQ_MD5)
{
md5Salt[0] = (byte)pgStream.ReceiveChar();
md5Salt[1] = (byte)pgStream.ReceiveChar();
md5Salt[2] = (byte)pgStream.ReceiveChar();
md5Salt[3] = (byte)pgStream.ReceiveChar();
if (Driver.logDebug) {
String md5SaltString = "";
for (int i=0; i<md5Salt.length; i++) {
md5SaltString += " " + md5Salt[i];
}
Driver.debug("MD5 salt=" + md5SaltString);
}
}
// now send the auth packet
switch (areq)
{
case AUTH_REQ_OK:
break;
case AUTH_REQ_KRB4:
if (Driver.logDebug)
Driver.debug("postgresql: KRB4");
throw new PSQLException("postgresql.con.kerb4", PSQLState.CONNECTION_REJECTED);
case AUTH_REQ_KRB5:
if (Driver.logDebug)
Driver.debug("postgresql: KRB5");
throw new PSQLException("postgresql.con.kerb5", PSQLState.CONNECTION_REJECTED);
case AUTH_REQ_PASSWORD:
if (Driver.logDebug)
Driver.debug("postgresql: PASSWORD");
pgStream.SendInteger(5 + password.length(), 4);
pgStream.Send(password.getBytes());
pgStream.SendInteger(0, 1);
pgStream.flush();
break;
case AUTH_REQ_CRYPT:
if (Driver.logDebug)
Driver.debug("postgresql: CRYPT");
String crypted = UnixCrypt.crypt(salt, password);
pgStream.SendInteger(5 + crypted.length(), 4);
pgStream.Send(crypted.getBytes());
pgStream.SendInteger(0, 1);
pgStream.flush();
break;
case AUTH_REQ_MD5:
if (Driver.logDebug)
Driver.debug("postgresql: MD5");
byte[] digest = MD5Digest.encode(PG_USER, password, md5Salt);
pgStream.SendInteger(5 + digest.length, 4);
pgStream.Send(digest);
pgStream.SendInteger(0, 1);
pgStream.flush();
break;
default:
throw new PSQLException("postgresql.con.auth", PSQLState.CONNECTION_REJECTED, new Integer(areq));
}
break;
default:
throw new PSQLException("postgresql.con.authfail", PSQLState.CONNECTION_REJECTED);
}
}
while (areq != AUTH_REQ_OK);
}
catch (IOException e)
{
//Should be passing exception as arg.
throw new PSQLException("postgresql.con.failed", PSQLState.CONNECTION_UNABLE_TO_CONNECT, e);
}
// As of protocol version 2.0, we should now receive the cancellation key and the pid
int beresp;
do
{
beresp = pgStream.ReceiveChar();
switch (beresp)
{
case 'K':
pid = pgStream.ReceiveIntegerR(4);
ckey = pgStream.ReceiveIntegerR(4);
break;
case 'E':
throw new PSQLException("postgresql.con.backend", PSQLState.CONNECTION_UNABLE_TO_CONNECT, pgStream.ReceiveString(encoding));
case 'N':
addWarning(new SQLWarning(pgStream.ReceiveString(encoding)));
break;
default:
throw new PSQLException("postgresql.con.setup", PSQLState.CONNECTION_UNABLE_TO_CONNECT);
}
}
while (beresp == 'N');
// Expect ReadyForQuery packet
do
{
beresp = pgStream.ReceiveChar();
switch (beresp)
{
case 'Z':
break;
case 'N':
addWarning(new SQLWarning(pgStream.ReceiveString(encoding)));
break;
case 'E':
throw new PSQLException("postgresql.con.backend", PSQLState.CONNECTION_UNABLE_TO_CONNECT, pgStream.ReceiveString(encoding));
default:
throw new PSQLException("postgresql.con.setup", PSQLState.CONNECTION_UNABLE_TO_CONNECT);
}
}
while (beresp == 'N');
// "pg_encoding_to_char(1)" will return 'EUC_JP' for a backend compiled with multibyte,
// otherwise it's hardcoded to 'SQL_ASCII'.
// If the backend doesn't know about multibyte we can't assume anything about the encoding
// used, so we denote this with 'UNKNOWN'.
//Note: begining with 7.2 we should be using pg_client_encoding() which
//is new in 7.2. However it isn't easy to conditionally call this new
//function, since we don't yet have the information as to what server
//version we are talking to. Thus we will continue to call
//getdatabaseencoding() until we drop support for 7.1 and older versions
//or until someone comes up with a conditional way to run one or
//the other function depending on server version that doesn't require
//two round trips to the server per connection
final String encodingQuery =
"case when pg_encoding_to_char(1) = 'SQL_ASCII' then 'UNKNOWN' else getdatabaseencoding() end";
// Set datestyle and fetch db encoding in a single call, to avoid making
// more than one round trip to the backend during connection startup.
BaseResultSet resultSet
= execSQL("set datestyle to 'ISO'; select version(), " + encodingQuery + ";");
if (! resultSet.next())
{
throw new PSQLException("postgresql.con.failed.bad.encoding", PSQLState.CONNECTION_UNABLE_TO_CONNECT);
}
String version = resultSet.getString(1);
dbVersionNumber = extractVersionNumber(version);
String dbEncoding = resultSet.getString(2);
encoding = Encoding.getEncoding(dbEncoding, info.getProperty("charSet"));
//TODO: remove this once the set is done as part of V3protocol connection initiation
if (haveMinimumServerVersion("7.4"))
{
BaseResultSet acRset =
execSQL("set client_encoding = 'UNICODE'");
//set encoding to be unicode
encoding = Encoding.getEncoding("UNICODE", null);
}
//In 7.3 we are forced to do a second roundtrip to handle the case
//where a database may not be running in autocommit mode
//jdbc by default assumes autocommit is on until setAutoCommit(false)
//is called. Therefore we need to ensure a new connection is
//initialized to autocommit on.
//We also set the client encoding so that the driver only needs
//to deal with utf8. We can only do this in 7.3+ because multibyte
//support is now always included
if (haveMinimumServerVersion("7.3") && !haveMinimumServerVersion("7.4"))
{
BaseResultSet acRset =
execSQL("set client_encoding = 'UNICODE'; show autocommit");
//set encoding to be unicode
encoding = Encoding.getEncoding("UNICODE", null);
if (!acRset.next())
{
throw new PSQLException("postgresql.con.failed.bad.autocommit", PSQLState.CONNECTION_UNABLE_TO_CONNECT);
}
//if autocommit is currently off we need to turn it on
//note that we will be in a transaction because the select above
//will have initiated the transaction so we need a commit
//to make the setting permanent
if (acRset.getString(1).equals("off"))
{
execSQL("set autocommit = on; commit;");
}
}
// Initialise object handling
initObjectTypes();
// Mark the connection as ok, and cleanup
PG_STATUS = CONNECTION_OK;
}
/*
* Return the instance of org.postgresql.Driver
* that created this connection
*/
public Driver getDriver()
{
return this_driver;
}
/*
* This adds a warning to the warning chain.
* @param warn warning to add
*/
public void addWarning(SQLWarning warn)
{
// Add the warning to the chain
if (firstWarning != null)
firstWarning.setNextWarning(warn);
else
firstWarning = warn;
}
/** Simple query execution.
*/
public BaseResultSet execSQL (String s) throws SQLException
{
final Object[] nullarr = new Object[0];
BaseStatement stat = (BaseStatement) createStatement();
return QueryExecutor.execute(new String[] { s },
nullarr,
stat);
}
/*
* In SQL, a result table can be retrieved through a cursor that
* is named. The current row of a result can be updated or deleted
* using a positioned update/delete statement that references the
* cursor name.
*
* We support one cursor per connection.
*
* setCursorName sets the cursor name.
*
* @param cursor the cursor name
* @exception SQLException if a database access error occurs
*/
public void setCursorName(String cursor) throws SQLException
{
this.cursor = cursor;
}
/*
* getCursorName gets the cursor name.
*
* @return the current cursor name
* @exception SQLException if a database access error occurs
*/
public String getCursorName() throws SQLException
{
return cursor;
}
/*
* We are required to bring back certain information by
* the DatabaseMetaData class. These functions do that.
*
* Method getURL() brings back the URL (good job we saved it)
*
* @return the url
* @exception SQLException just in case...
*/
public String getURL() throws SQLException
{
return this_url;
}
/*
* Method getUserName() brings back the User Name (again, we
* saved it)
*
* @return the user name
* @exception SQLException just in case...
*/
int lastMessage = 0;
public String getUserName() throws SQLException
{
return PG_USER;
}
/*
* Get the character encoding to use for this connection.
*/
public Encoding getEncoding() throws SQLException
{
return encoding;
}
/*
* This returns the Fastpath API for the current connection.
*
* <p><b>NOTE:</b> This is not part of JDBC, but allows access to
* functions on the org.postgresql backend itself.
*
* <p>It is primarily used by the LargeObject API
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* import org.postgresql.fastpath.*;
* ...
* Fastpath fp = ((org.postgresql.Connection)myconn).getFastpathAPI();
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* @return Fastpath object allowing access to functions on the org.postgresql
* backend.
* @exception SQLException by Fastpath when initialising for first time
*/
public Fastpath getFastpathAPI() throws SQLException
{
if (fastpath == null)
fastpath = new Fastpath(this, pgStream);
return fastpath;
}
// This holds a reference to the Fastpath API if already open
private Fastpath fastpath = null;
/*
* This returns the LargeObject API for the current connection.
*
* <p><b>NOTE:</b> This is not part of JDBC, but allows access to
* functions on the org.postgresql backend itself.
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* import org.postgresql.largeobject.*;
* ...
* LargeObjectManager lo = ((org.postgresql.Connection)myconn).getLargeObjectAPI();
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* @return LargeObject object that implements the API
* @exception SQLException by LargeObject when initialising for first time
*/
public LargeObjectManager getLargeObjectAPI() throws SQLException
{
if (largeobject == null)
largeobject = new LargeObjectManager(this);
return largeobject;
}
// This holds a reference to the LargeObject API if already open
private LargeObjectManager largeobject = null;
/*
* This method is used internally to return an object based around
* org.postgresql's more unique data types.
*
* <p>It uses an internal Hashtable to get the handling class. If the
* type is not supported, then an instance of org.postgresql.util.PGobject
* is returned.
*
* You can use the getValue() or setValue() methods to handle the returned
* object. Custom objects can have their own methods.
*
* @return PGobject for this type, and set to value
* @exception SQLException if value is not correct for this type
*/
public Object getObject(String type, String value) throws SQLException
{
PGobject obj = null;
try
{
String className = (String)objectTypes.get(type);
// If className is not null, then try to instantiate it,
// It must be basetype PGobject
// This is used to implement the org.postgresql unique types (like lseg,
// point, etc).
if (className != null )
{
// 6.3 style extending PG_Object
obj = (PGobject) (Class.forName( className ).newInstance());
obj.setType(type);
obj.setValue(value);
}
else
{
// If className is null, then the type is unknown.
// so return a PGobject with the type set, and the value set
obj = new PGobject();
obj.setType( type );
obj.setValue( value );
}
return (Object) obj;
}
catch (SQLException sx)
{
// rethrow the exception. Done because we capture any others next
sx.fillInStackTrace();
throw sx;
}
catch (Exception ex)
{
throw new PSQLException("postgresql.con.creobj", PSQLState.CONNECTION_FAILURE, type, ex);
}
}
/*
* This allows client code to add a handler for one of org.postgresql's
* more unique data types.
*
* <p><b>NOTE:</b> This is not part of JDBC, but an extension.
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* ...
* ((org.postgresql.Connection)myconn).addDataType("mytype","my.class.name");
* ...
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* <p>The handling class must extend org.postgresql.util.PGobject
*
* @see org.postgresql.util.PGobject
*/
public void addDataType(String type, String name)
{
objectTypes.put(type, name);
}
// This holds the available types
private Hashtable objectTypes = new Hashtable();
// This array contains the types that are supported as standard.
// The first entry is the types name on the database, the second
// the full class name of the handling class.
private static final String defaultObjectTypes[][] = {
{"box", "org.postgresql.geometric.PGbox"},
{"circle", "org.postgresql.geometric.PGcircle"},
{"line", "org.postgresql.geometric.PGline"},
{"lseg", "org.postgresql.geometric.PGlseg"},
{"path", "org.postgresql.geometric.PGpath"},
{"point", "org.postgresql.geometric.PGpoint"},
{"polygon", "org.postgresql.geometric.PGpolygon"},
{"money", "org.postgresql.util.PGmoney"},
{"interval", "org.postgresql.util.PGInterval"}
};
// This initialises the objectTypes hashtable
private void initObjectTypes()
{
for (int i = 0;i < defaultObjectTypes.length;i++)
objectTypes.put(defaultObjectTypes[i][0], defaultObjectTypes[i][1]);
}
/*
* In some cases, it is desirable to immediately release a Connection's
* database and JDBC resources instead of waiting for them to be
* automatically released (cant think why off the top of my head)
*
* <B>Note:</B> A Connection is automatically closed when it is
* garbage collected. Certain fatal errors also result in a closed
* connection.
*
* @exception SQLException if a database access error occurs
*/
public void close() throws SQLException
{
if (getPGProtocolVersionMajor() == 3) {
closeV3();
} else {
closeV2();
}
}
public void closeV3() throws SQLException
{
if (pgStream != null)
{
try
{
pgStream.SendChar('X');
pgStream.SendInteger(4,4);
pgStream.flush();
pgStream.close();
}
catch (IOException e)
{}
finally
{
pgStream = null;
}
}
}
public void closeV2() throws SQLException
{
if (pgStream != null)
{
try
{
pgStream.SendChar('X');
pgStream.flush();
pgStream.close();
}
catch (IOException e)
{}
finally
{
pgStream = null;
}
}
}
/*
* A driver may convert the JDBC sql grammar into its system's
* native SQL grammar prior to sending it; nativeSQL returns the
* native form of the statement that the driver would have sent.
*
* @param sql a SQL statement that may contain one or more '?'
* parameter placeholders
* @return the native form of this statement
* @exception SQLException if a database access error occurs
*/
public String nativeSQL(String sql) throws SQLException
{
return sql;
}
/*
* The first warning reported by calls on this Connection is
* returned.
*
* <B>Note:</B> Sebsequent warnings will be changed to this
* SQLWarning
*
* @return the first SQLWarning or null
* @exception SQLException if a database access error occurs
*/
public SQLWarning getWarnings() throws SQLException
{
return firstWarning;
}
/*
* After this call, getWarnings returns null until a new warning
* is reported for this connection.
*
* @exception SQLException if a database access error occurs
*/
public void clearWarnings() throws SQLException
{
firstWarning = null;
}
/*
* You can put a connection in read-only mode as a hunt to enable
* database optimizations
*
* <B>Note:</B> setReadOnly cannot be called while in the middle
* of a transaction
*
* @param readOnly - true enables read-only mode; false disables it
* @exception SQLException if a database access error occurs
*/
public void setReadOnly(boolean readOnly) throws SQLException
{
this.readOnly = readOnly;
}
/*
* Tests to see if the connection is in Read Only Mode. Note that
* we cannot really put the database in read only mode, but we pretend
* we can by returning the value of the readOnly flag
*
* @return true if the connection is read only
* @exception SQLException if a database access error occurs
*/
public boolean isReadOnly() throws SQLException
{
return readOnly;
}
/*
* If a connection is in auto-commit mode, than all its SQL
* statements will be executed and committed as individual
* transactions. Otherwise, its SQL statements are grouped
* into transactions that are terminated by either commit()
* or rollback(). By default, new connections are in auto-
* commit mode. The commit occurs when the statement completes
* or the next execute occurs, whichever comes first. In the
* case of statements returning a ResultSet, the statement
* completes when the last row of the ResultSet has been retrieved
* or the ResultSet has been closed. In advanced cases, a single
* statement may return multiple results as well as output parameter
* values. Here the commit occurs when all results and output param
* values have been retrieved.
*
* @param autoCommit - true enables auto-commit; false disables it
* @exception SQLException if a database access error occurs
*/
public void setAutoCommit(boolean autoCommit) throws SQLException
{
if (this.autoCommit == autoCommit)
return ;
if (autoCommit && inTransaction)
{
execSQL("end");
inTransaction = false;
}
this.autoCommit = autoCommit;
}
/*
* gets the current auto-commit state
*
* @return Current state of the auto-commit mode
* @see setAutoCommit
*/
public boolean getAutoCommit()
{
return this.autoCommit;
}
public boolean getInTransaction()
{
return this.inTransaction;
}
public void setInTransaction(boolean inTransaction)
{
this.inTransaction = inTransaction;
}
/*
* The method commit() makes all changes made since the previous
* commit/rollback permanent and releases any database locks currently
* held by the Connection. This method should only be used when
* auto-commit has been disabled. (If autoCommit == true, then we
* just return anyhow)
*
* @exception SQLException if a database access error occurs
* @see setAutoCommit
*/
public void commit() throws SQLException
{
if (autoCommit)
return ;
if (inTransaction) {
execSQL("commit;");
inTransaction = false;
}
}
/*
* The method rollback() drops all changes made since the previous
* commit/rollback and releases any database locks currently held by
* the Connection.
*
* @exception SQLException if a database access error occurs
* @see commit
*/
public void rollback() throws SQLException
{
if (autoCommit)
return ;
if (inTransaction) {
execSQL("rollback;");
inTransaction = false;
}
}
/*
* Get this Connection's current transaction isolation mode.
*
* @return the current TRANSACTION_* mode value
* @exception SQLException if a database access error occurs
*/
public int getTransactionIsolation() throws SQLException
{
String sql = "show transaction isolation level";
String level = null;
if (haveMinimumServerVersion("7.3")) {
BaseResultSet rs = execSQL(sql);
if (rs.next()) {
level = rs.getString(1);
}
rs.close();
} else {
BaseResultSet l_rs = execSQL(sql);
BaseStatement l_stat = l_rs.getPGStatement();
SQLWarning warning = l_stat.getWarnings();
if (warning != null)
{
level = warning.getMessage();
}
l_rs.close();
l_stat.close();
}
if (level != null) {
level = level.toUpperCase();
if (level.indexOf("READ COMMITTED") != -1)
return Connection.TRANSACTION_READ_COMMITTED;
else if (level.indexOf("READ UNCOMMITTED") != -1)
return Connection.TRANSACTION_READ_UNCOMMITTED;
else if (level.indexOf("REPEATABLE READ") != -1)
return Connection.TRANSACTION_REPEATABLE_READ;
else if (level.indexOf("SERIALIZABLE") != -1)
return Connection.TRANSACTION_SERIALIZABLE;
}
return Connection.TRANSACTION_READ_COMMITTED;
}
/*
* You can call this method to try to change the transaction
* isolation level using one of the TRANSACTION_* values.
*
* <B>Note:</B> setTransactionIsolation cannot be called while
* in the middle of a transaction
*
* @param level one of the TRANSACTION_* isolation values with
* the exception of TRANSACTION_NONE; some databases may
* not support other values
* @exception SQLException if a database access error occurs
* @see java.sql.DatabaseMetaData#supportsTransactionIsolationLevel
*/
public void setTransactionIsolation(int level) throws SQLException
{
if (inTransaction) {
throw new PSQLException("postgresql.con.changeisolevel");
}
//In 7.1 and later versions of the server it is possible using
//the "set session" command to set this once for all future txns
//however in 7.0 and prior versions it is necessary to set it in
//each transaction, thus adding complexity below.
//When we decide to drop support for servers older than 7.1
//this can be simplified
String isolationLevelSQL;
if (!haveMinimumServerVersion("7.1"))
{
// do nothing because we will do this on each transaction
// still we want to check that it is a valid level.
String name = getIsolationLevelName(level);
}
else
{
isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + getIsolationLevelName(level);
// We want to run this statement outside of any transactions
// so that it can't be rolled back or anything.
// The inTransaction check at the top makes this
boolean origAutoCommit = autoCommit;
if (autoCommit == false) {
setAutoCommit(true);
}
execSQL(isolationLevelSQL);
setAutoCommit(origAutoCommit);
}
isolationLevel = level;
}
protected String getIsolationLevelName(int level) throws SQLException
{
boolean pg75 = haveMinimumServerVersion("7.5");
if (level == Connection.TRANSACTION_READ_COMMITTED) {
return " READ COMMITTED";
} else if (level == Connection.TRANSACTION_SERIALIZABLE) {
return " SERIALIZABLE";
} else if (pg75 && level == Connection.TRANSACTION_READ_UNCOMMITTED) {
return " READ UNCOMMITTED";
} else if (pg75 && level == Connection.TRANSACTION_REPEATABLE_READ) {
return " REPEATABLE READ";
}
throw new PSQLException("postgresql.con.isolevel", PSQLState.TRANSACTION_STATE_INVALID, new Integer(level));
}
/*
* Helper method used by setTransactionIsolation(), commit(), rollback()
* and setAutoCommit(). This returns the SQL string needed to
* set the isolation level for a transaction. In 7.1 and later it
* is possible to set a default isolation level that applies to all
* future transactions, this method is only necesary for 7.0 and older
* servers, and should be removed when support for these older
* servers are dropped
*/
public String getPre71IsolationLevelSQL() throws SQLException
{
return "SET TRANSACTION ISOLATION LEVEL " + getIsolationLevelName(isolationLevel);
}
/*
* A sub-space of this Connection's database may be selected by
* setting a catalog name. If the driver does not support catalogs,
* it will silently ignore this request
*
* @exception SQLException if a database access error occurs
*/
public void setCatalog(String catalog) throws SQLException
{
//no-op
}
/*
* Return the connections current catalog name, or null if no
* catalog name is set, or we dont support catalogs.
*
* @return the current catalog name or null
* @exception SQLException if a database access error occurs
*/
public String getCatalog() throws SQLException
{
return PG_DATABASE;
}
/*
* Overides finalize(). If called, it closes the connection.
*
* This was done at the request of Rachel Greenham
* <rachel@enlarion.demon.co.uk> who hit a problem where multiple
* clients didn't close the connection, and once a fortnight enough
* clients were open to kill the org.postgres server.
*/
public void finalize() throws Throwable
{
close();
}
private static String extractVersionNumber(String fullVersionString)
{
StringTokenizer versionParts = new StringTokenizer(fullVersionString);
versionParts.nextToken(); /* "PostgreSQL" */
return versionParts.nextToken(); /* "X.Y.Z" */
}
/*
* Get server version number
*/
public String getDBVersionNumber()
{
return dbVersionNumber;
}
// Parse a "dirty" integer surrounded by non-numeric characters
private static int integerPart(String dirtyString)
{
int start, end;
for (start = 0; start < dirtyString.length() && !Character.isDigit(dirtyString.charAt(start)); ++start)
;
for (end = start; end < dirtyString.length() && Character.isDigit(dirtyString.charAt(end)); ++end)
;
if (start == end)
return 0;
return Integer.parseInt(dirtyString.substring(start, end));
}
/*
* Get server major version
*/
public int getServerMajorVersion()
{
try
{
StringTokenizer versionTokens = new StringTokenizer(dbVersionNumber, "."); // aaXbb.ccYdd
return integerPart(versionTokens.nextToken()); // return X
}
catch (NoSuchElementException e)
{
return 0;
}
}
/*
* Get server minor version
*/
public int getServerMinorVersion()
{
try
{
StringTokenizer versionTokens = new StringTokenizer(dbVersionNumber, "."); // aaXbb.ccYdd
versionTokens.nextToken(); // Skip aaXbb
return integerPart(versionTokens.nextToken()); // return Y
}
catch (NoSuchElementException e)
{
return 0;
}
}
/**
* Is the server we are connected to running at least this version?
* This comparison method will fail whenever a major or minor version
* goes to two digits (10.3.0) or (7.10.1).
*/
public boolean haveMinimumServerVersion(String ver) throws SQLException
{
return (getDBVersionNumber().compareTo(ver) >= 0);
}
/*
* This method returns true if the compatible level set in the connection
* (which can be passed into the connection or specified in the URL)
* is at least the value passed to this method. This is used to toggle
* between different functionality as it changes across different releases
* of the jdbc driver code. The values here are versions of the jdbc client
* and not server versions. For example in 7.1 get/setBytes worked on
* LargeObject values, in 7.2 these methods were changed to work on bytea
* values. This change in functionality could be disabled by setting the
* "compatible" level to be 7.1, in which case the driver will revert to
* the 7.1 functionality.
*/
public boolean haveMinimumCompatibleVersion(String ver) throws SQLException
{
return (compatible.compareTo(ver) >= 0);
}
/*
* This returns the java.sql.Types type for a PG type oid
*
* @param oid PostgreSQL type oid
* @return the java.sql.Types type
* @exception SQLException if a database access error occurs
*/
public int getSQLType(int oid) throws SQLException
{
Integer sqlType = (Integer)sqlTypeCache.get(new Integer(oid));
// it's not in the cache, so perform a query, and add the result to the cache
if (sqlType == null)
{
String pgType;
// The opaque type does not exist in the system catalogs.
if (oid == 0) {
pgType = "opaque";
} else {
String sql;
if (haveMinimumServerVersion("7.3")) {
sql = "SELECT typname FROM pg_catalog.pg_type WHERE oid = " +oid;
} else {
sql = "SELECT typname FROM pg_type WHERE oid = " +oid;
}
BaseResultSet result = execSQL(sql);
if (result.getColumnCount() != 1 || result.getTupleCount() != 1) {
throw new PSQLException("postgresql.unexpected", PSQLState.UNEXPECTED_ERROR);
}
result.next();
pgType = result.getString(1);
result.close();
}
Integer iOid = new Integer(oid);
sqlType = new Integer(getSQLType(pgType));
sqlTypeCache.put(iOid, sqlType);
pgTypeCache.put(iOid, pgType);
}
return sqlType.intValue();
}
/*
* This returns the oid for a given PG data type
* @param typeName PostgreSQL type name
* @return PostgreSQL oid value for a field of this type
*/
public int getPGType(String typeName) throws SQLException
{
int oid = -1;
if (typeName != null)
{
Integer oidValue = (Integer) typeOidCache.get(typeName);
if (oidValue != null)
{
oid = oidValue.intValue();
}
else
{
// it's not in the cache, so perform a query, and add the result to the cache
String sql;
if (haveMinimumServerVersion("7.3")) {
sql = "SELECT oid FROM pg_catalog.pg_type WHERE typname='" + typeName + "'";
} else {
sql = "SELECT oid FROM pg_type WHERE typname='" + typeName + "'";
}
BaseResultSet result = execSQL(sql);
if (result.getColumnCount() != 1 || result.getTupleCount() != 1)
throw new PSQLException("postgresql.unexpected", PSQLState.UNEXPECTED_ERROR);
result.next();
oid = Integer.parseInt(result.getString(1));
typeOidCache.put(typeName, new Integer(oid));
result.close();
}
}
return oid;
}
/*
* We also need to get the PG type name as returned by the back end.
*
* @return the String representation of the type of this field
* @exception SQLException if a database access error occurs
*/
public String getPGType(int oid) throws SQLException
{
String pgType = (String) pgTypeCache.get(new Integer(oid));
if (pgType == null)
{
getSQLType(oid);
pgType = (String) pgTypeCache.get(new Integer(oid));
}
return pgType;
}
//Because the get/setLogStream methods are deprecated in JDBC2
//we use them for JDBC1 here and override this method in the jdbc2
//version of this class
protected void enableDriverManagerLogging()
{
if (DriverManager.getLogStream() == null)
{
DriverManager.setLogStream(System.out);
}
}
// This is a cache of the DatabaseMetaData instance for this connection
protected java.sql.DatabaseMetaData metadata;
/*
* Tests to see if a Connection is closed
*
* @return the status of the connection
* @exception SQLException (why?)
*/
public boolean isClosed() throws SQLException
{
return (pgStream == null);
}
/*
* This implemetation uses the jdbc1Types array to support the jdbc1
* datatypes. Basically jdbc1 and jdbc2 are the same, except that
* jdbc2 adds the Array types.
*/
public int getSQLType(String pgTypeName)
{
int sqlType = Types.OTHER; // default value
for (int i = 0;i < jdbc1Types.length;i++)
{
if (pgTypeName.equals(jdbc1Types[i]))
{
sqlType = jdbc1Typei[i];
break;
}
}
return sqlType;
}
/*
* This table holds the org.postgresql names for the types supported.
* Any types that map to Types.OTHER (eg POINT) don't go into this table.
* They default automatically to Types.OTHER
*
* Note: This must be in the same order as below.
*
* Tip: keep these grouped together by the Types. value
*/
private static final String jdbc1Types[] = {
"int2",
"int4", "oid",
"int8",
"cash", "money",
"numeric",
"float4",
"float8",
"bpchar", "char", "char2", "char4", "char8", "char16",
"varchar", "text", "name", "filename",
"bytea",
"bool",
"bit",
"date",
"time",
"abstime", "timestamp", "timestamptz"
};
/*
* This table holds the JDBC type for each entry above.
*
* Note: This must be in the same order as above
*
* Tip: keep these grouped together by the Types. value
*/
private static final int jdbc1Typei[] = {
Types.SMALLINT,
Types.INTEGER, Types.INTEGER,
Types.BIGINT,
Types.DOUBLE, Types.DOUBLE,
Types.NUMERIC,
Types.REAL,
Types.DOUBLE,
Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.BINARY,
Types.BIT,
Types.BIT,
Types.DATE,
Types.TIME,
Types.TIMESTAMP, Types.TIMESTAMP, Types.TIMESTAMP
};
public void cancelQuery() throws SQLException
{
org.postgresql.core.PGStream cancelStream = null;
try
{
cancelStream = new org.postgresql.core.PGStream(PG_HOST, PG_PORT);
}
catch (ConnectException cex)
{
// Added by Peter Mount <peter@retep.org.uk>
// ConnectException is thrown when the connection cannot be made.
// we trap this an return a more meaningful message for the end user
throw new PSQLException ("postgresql.con.refused", PSQLState.CONNECTION_REJECTED);
}
catch (IOException e)
{
throw new PSQLException ("postgresql.con.failed", PSQLState.CONNECTION_UNABLE_TO_CONNECT, e);
}
// Now we need to construct and send a cancel packet
try
{
cancelStream.SendInteger(16, 4);
cancelStream.SendInteger(80877102, 4);
cancelStream.SendInteger(pid, 4);
cancelStream.SendInteger(ckey, 4);
cancelStream.flush();
}
catch (IOException e)
{
throw new PSQLException("postgresql.con.failed", PSQLState.CONNECTION_UNABLE_TO_CONNECT, e);
}
finally
{
try
{
if (cancelStream != null)
cancelStream.close();
}
catch (IOException e)
{} // Ignore
}
}
//Methods to support postgres notifications
public void addNotification(org.postgresql.PGNotification p_notification)
{
if (m_notifications == null)
m_notifications = new Vector();
m_notifications.addElement(p_notification);
}
public PGNotification[] getNotifications()
{
PGNotification[] l_return = null;
if (m_notifications != null)
{
l_return = new PGNotification[m_notifications.size()];
m_notifications.copyInto(l_return);
}
m_notifications = null;
return l_return;
}
public int getPrepareThreshold() {
return prepareThreshold;
}
public void setPrepareThreshold(int newThreshold) {
this.prepareThreshold = (newThreshold <= 0 ? 0 : newThreshold);
}
} |
package net.canadensys.dataportal.vascan.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.List;
import net.canadensys.dataportal.vascan.config.GeneratedContentConfig;
import net.canadensys.utils.ZipUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
/**
* Testing the generated content controller routing and make sure files are generated.
* @author canadensys
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-dispatcher-servlet.xml"})
@TransactionConfiguration(transactionManager="hibernateTransactionManager")
public class GeneratedContentControllerTest extends AbstractTransactionalJUnit4SpringContextTests{
public static String DELIMITER = "\t";
public static String NEWLINE = "\n";
private int DWCA_IDX_TAXONID = 0;
private int DWCA_IDX_ACCEPTED_NAME_USAGE_ID = 4;
private int DWCA_IDX_ACCEPTED_NAME_USAGE = 5;
private int DWCA_IDX_PARENT_NAME_USAGE_ID = 6;
private int DWCA_IDX_PARENT_NAME_USAGE = 7;
private int DWCA_IDX_SCIENTIFIC_NAME = 10;
private int DWCA_IDX_TAXONOMIC_STATUS = 21;
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
@Autowired
private RequestMappingHandlerMapping handlerMapping;
@Autowired
private GeneratedContentConfig generatedContentConfig;
@Test
public void testTextFileGeneration() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setRequestURI("/download");
request.addParameter("format", "txt");
request.addParameter("taxon", "0");
request.addParameter("habit", "tree");
request.addParameter("combination", "anyof");
request.addParameter("province", "PM");
request.addParameter("status", "native");
request.addParameter("status", "introduced");
request.addParameter("status", "ephemeral");
request.addParameter("status", "excluded");
request.addParameter("status", "extirpated");
request.addParameter("status", "doubtful");
Object handler = handlerMapping.getHandler(request).getHandler();
//ask for a download and get a download
ModelAndView mav = handlerAdapter.handle(request, response, handler);
assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
String filename= (String)mav.getModelMap().get("filename");
//since the page will not get rendered, we call the URI to generate the file
request.setRequestURI("/generate");
handler = handlerMapping.getHandler(request).getHandler();
handlerAdapter.handle(request, response, handler);
assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
assertTrue(new File(generatedContentConfig.getGeneratedFilesFolder()+filename).exists());
}
/**
* Test the content of a generated DwcA that includes a synonym.
*
* @throws Exception
*/
@Test
public void testDwcAFileGenerationSynonym() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setRequestURI("/download");
request.addParameter("format", "dwc");
request.addParameter("taxon", "15164");
request.addParameter("habit", "all");
request.addParameter("status", "native");
request.addParameter("rank", "variety");
Object handler = handlerMapping.getHandler(request).getHandler();
//ask for a download and get a download
ModelAndView mav = handlerAdapter.handle(request, response, handler);
assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
String filename= (String)mav.getModelMap().get("filename");
//since the page will not get rendered, we call the URI to generate the file
request.setRequestURI("/generate");
handler = handlerMapping.getHandler(request).getHandler();
handlerAdapter.handle(request, response, handler);
assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
File generatedDwcA = new File(generatedContentConfig.getGeneratedFilesFolder()+filename);
assertTrue(generatedDwcA.exists());
//Test DarwinCore archive content
String unzippedFolder = generatedDwcA.getParentFile().getAbsolutePath()+"/"+ FilenameUtils.getBaseName(generatedDwcA.getName());
ZipUtils.unzipFileOrFolder(generatedDwcA, unzippedFolder);
List<String> fileLines = FileUtils.readLines(new File(unzippedFolder+"/taxon.txt"));
String[] synonymData = fileLines.get(1).split(DELIMITER);
assertEquals("15164", synonymData[DWCA_IDX_TAXONID]);
assertEquals("Carex alpina var. holostoma (Drejer) L.H. Bailey",synonymData[DWCA_IDX_SCIENTIFIC_NAME]);
assertEquals("4904", synonymData[DWCA_IDX_ACCEPTED_NAME_USAGE_ID]);
assertEquals("Carex holostoma Drejer", synonymData[DWCA_IDX_ACCEPTED_NAME_USAGE]);
assertEquals("",synonymData[DWCA_IDX_PARENT_NAME_USAGE_ID]);
assertEquals("",synonymData[DWCA_IDX_PARENT_NAME_USAGE]);
assertEquals("synonym", synonymData[DWCA_IDX_TAXONOMIC_STATUS]);
FileUtils.deleteDirectory(new File(unzippedFolder));
}
/**
* Test the content of a generated DwcA that includes an accepted taxon.
* @throws Exception
*/
@Test
public void testDwcAFileGenerationAccepted() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setRequestURI("/download");
request.addParameter("format", "dwc");
request.addParameter("taxon", "4904");
request.addParameter("habit", "all");
request.addParameter("status", "native");
Object handler = handlerMapping.getHandler(request).getHandler();
//ask for a download and get a download
ModelAndView mav = handlerAdapter.handle(request, response, handler);
assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
String filename= (String)mav.getModelMap().get("filename");
//since the page will not get rendered, we call the URI to generate the file
request.setRequestURI("/generate");
handler = handlerMapping.getHandler(request).getHandler();
handlerAdapter.handle(request, response, handler);
assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
File generatedDwcA = new File(generatedContentConfig.getGeneratedFilesFolder()+filename);
assertTrue(generatedDwcA.exists());
//Test DarwinCore archive content
String unzippedFolder = generatedDwcA.getParentFile().getAbsolutePath()+"/"+ FilenameUtils.getBaseName(generatedDwcA.getName());
ZipUtils.unzipFileOrFolder(generatedDwcA, unzippedFolder);
List<String> fileLines = FileUtils.readLines(new File(unzippedFolder+"/taxon.txt"));
String[] taxonData = fileLines.get(1).split(DELIMITER);
assertEquals("4904", taxonData[DWCA_IDX_TAXONID]);
assertEquals("Carex holostoma Drejer",taxonData[DWCA_IDX_SCIENTIFIC_NAME]);
assertEquals("4904", taxonData[DWCA_IDX_ACCEPTED_NAME_USAGE_ID]);
assertEquals("Carex holostoma Drejer", taxonData[DWCA_IDX_ACCEPTED_NAME_USAGE]);
assertEquals("2096",taxonData[DWCA_IDX_PARENT_NAME_USAGE_ID]);
assertEquals("accepted", taxonData[DWCA_IDX_TAXONOMIC_STATUS]);
//test that the synonym is included
String[] synonymData = fileLines.get(2).split(DELIMITER);
assertEquals("15164", synonymData[DWCA_IDX_TAXONID]);
FileUtils.deleteDirectory(new File(unzippedFolder));
}
/**
* Test the content of a generated DwcA that includes an accepted taxon.
* @throws Exception
*/
@Test
public void testDwcAFileGenerationHybrid() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setRequestURI("/download");
request.addParameter("format", "dwc");
request.addParameter("taxon", "4793");
request.addParameter("habit", "all");
request.addParameter("status", "native");
request.addParameter("hybrids", "true");
Object handler = handlerMapping.getHandler(request).getHandler();
//ask for a download and get a download
ModelAndView mav = handlerAdapter.handle(request, response, handler);
assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
String filename= (String)mav.getModelMap().get("filename");
//since the page will not get rendered, we call the URI to generate the file
request.setRequestURI("/generate");
handler = handlerMapping.getHandler(request).getHandler();
handlerAdapter.handle(request, response, handler);
assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
File generatedDwcA = new File(generatedContentConfig.getGeneratedFilesFolder()+filename);
assertTrue(generatedDwcA.exists());
//Test DarwinCore archive content
String unzippedFolder = generatedDwcA.getParentFile().getAbsolutePath()+"/"+ FilenameUtils.getBaseName(generatedDwcA.getName());
ZipUtils.unzipFileOrFolder(generatedDwcA, unzippedFolder);
List<String> fileLines = FileUtils.readLines(new File(unzippedFolder+"/resourcerelationship.txt"));
String line1 = fileLines.get(1);
assertTrue(line1.contains("4793"));
assertTrue(line1.contains("4790"));
assertTrue(line1.contains("hybrid parent of"));
assertTrue(line1.contains("Carex canescens var. brunnescens (Persoon) W.D.J. Koch"));
FileUtils.deleteDirectory(new File(unzippedFolder));
generatedDwcA.delete();
}
} |
package serviceComponents;
import db.DBConnector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import serviceRepresentations.Option;
import serviceResources.OptionDAO;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/v1/option")
public class OptionController {
@Autowired
DBConnector dbConnector;
OptionDAO optionDAO;
/**
* Endpoint for retrieveing an option based on it's id.
* @param id The id of the option.
* @return 200 if user exists, 404 otherwise.
*/
@RequestMapping(
value = "/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<Option> getOption(@PathVariable Long id) {
optionDAO = new OptionDAO(dbConnector);
Option option = optionDAO.getOption(id);
if (option == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(option, HttpStatus.OK);
}
/**
* Endpoint for creating a new option.
* @param option A JSON representing the new option to be inserted.
* @return BAD_REQUEST if the question is invalid, OK otherwise.
*/
@RequestMapping(
value = "/",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<Long> createOption(@RequestBody Option option) {
optionDAO = new OptionDAO(dbConnector);
Long id = optionDAO.createOption(option);
// TODO: fields check
// TODO: security
if (id == -1) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(id, HttpStatus.OK);
}
/**
* Endpoint for updating an option.
* @param option A json with the new version of the question.
* @return NOT_FOUND if the update failed, OK otherwise.
*/
@RequestMapping(
value = "/",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<Void> updateOption(@RequestBody Option option) {
optionDAO = new OptionDAO(dbConnector);
Boolean status = optionDAO.updateOption(option);
if (status == Boolean.FALSE) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(HttpStatus.OK);
}
/**
* Endpoint for removing an option.
* @param id The id of the targeted question with the options
* @return NOT_FOUND if the deletion failed, OK otherwise.
*/
@RequestMapping(
value = "/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<Void> removeOption(@PathVariable Long id) {
// TODO: Edge cases and security checks.
optionDAO = new OptionDAO(dbConnector);
Boolean status = optionDAO.deleteOption(id);
if (status == Boolean.FALSE) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(HttpStatus.OK);
}
/**
* Endpoint for getting the options of a question
* @return OK so far.
*/
@RequestMapping(
value = "/all/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<List<Option>> getQuestionOptions(@PathVariable Long id) {
optionDAO = new OptionDAO(dbConnector);
// TODO: don't forget the security checks.
ArrayList<Option> options = (ArrayList<Option>) optionDAO.getQuestionOptions(id);
return new ResponseEntity<>(options, HttpStatus.OK);
}
} |
package com.emc.mongoose.storage.driver.base;
import com.emc.mongoose.model.DaemonBase;
import static com.emc.mongoose.common.Constants.BATCH_SIZE;
import static com.emc.mongoose.ui.config.Config.LoadConfig;
import static com.emc.mongoose.ui.config.Config.StorageConfig.AuthConfig;
import static com.emc.mongoose.ui.config.Config.LoadConfig.MetricsConfig.TraceConfig;
import com.emc.mongoose.common.io.Input;
import com.emc.mongoose.model.io.task.composite.CompositeIoTask;
import com.emc.mongoose.model.io.task.IoTask;
import static com.emc.mongoose.model.io.task.IoTask.IoResult;
import com.emc.mongoose.model.io.task.partial.PartialIoTask;
import com.emc.mongoose.model.item.Item;
import com.emc.mongoose.model.storage.StorageDriver;
import static com.emc.mongoose.ui.config.Config.LoadConfig.MetricsConfig;
import com.emc.mongoose.ui.log.LogUtil;
import com.emc.mongoose.ui.log.Markers;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.EOFException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
public abstract class StorageDriverBase<I extends Item, O extends IoTask<I, R>, R extends IoResult>
extends DaemonBase
implements StorageDriver<I, O, R> {
private static final Logger LOG = LogManager.getLogger();
private final int queueCapacity;
private final BlockingQueue<O> childTasksQueue;
private final BlockingQueue<O> inTasksQueue;
private final BlockingQueue<R> ioResultsQueue;
private final boolean isCircular;
protected final String jobName;
protected final int concurrencyLevel;
protected final Semaphore concurrencyThrottle;
protected final String userName;
protected final String secret;
protected volatile String authToken;
protected final boolean verifyFlag;
private final boolean useStorageDriverResult;
private final boolean useStorageNodeResult;
private final boolean useItemInfoResult;
private final boolean useIoTypeCodeResult;
private final boolean useStatusCodeResult;
private final boolean useReqTimeStartResult;
private final boolean useDurationResult;
private final boolean useRespLatencyResult;
private final boolean useDataLatencyResult;
private final boolean useTransferSizeResult;
private final LongAdder scheduledTaskCount = new LongAdder();
private final LongAdder completedTaskCount = new LongAdder();
private final LongAdder recycledTaskCount = new LongAdder();
protected StorageDriverBase(
final String jobName, final AuthConfig authConfig, final LoadConfig loadConfig,
final boolean verifyFlag
) {
queueCapacity = loadConfig.getQueueConfig().getSize();
this.childTasksQueue = new ArrayBlockingQueue<>(queueCapacity);
this.inTasksQueue = new ArrayBlockingQueue<>(queueCapacity);
this.ioResultsQueue = new ArrayBlockingQueue<>(queueCapacity);
this.jobName = jobName;
this.userName = authConfig == null ? null : authConfig.getId();
secret = authConfig == null ? null : authConfig.getSecret();
authToken = authConfig == null ? null : authConfig.getToken();
concurrencyLevel = loadConfig.getConcurrency();
concurrencyThrottle = new Semaphore(concurrencyLevel, true);
isCircular = loadConfig.getCircular();
this.verifyFlag = verifyFlag;
final MetricsConfig metricsConfig = loadConfig.getMetricsConfig();
final TraceConfig traceConfig = metricsConfig.getTraceConfig();
useStorageDriverResult = traceConfig.getStorageDriver();
useStorageNodeResult = traceConfig.getStorageNode();
useItemInfoResult = traceConfig.getItemInfo();
useIoTypeCodeResult = traceConfig.getIoTypeCode();
useStatusCodeResult = traceConfig.getStatusCode();
useReqTimeStartResult = traceConfig.getReqTimeStart();
useDurationResult = traceConfig.getDuration();
useRespLatencyResult = traceConfig.getRespLatency();
useDataLatencyResult = traceConfig.getDataLatency();
useTransferSizeResult = traceConfig.getTransferSize();
SVC_TASKS.put(this, new IoTasksDispatch());
}
private final class IoTasksDispatch
implements Runnable {
final List<O> ioTasks = new ArrayList<>(BATCH_SIZE);
final List<O> prevIoTasks = new ArrayList<>(BATCH_SIZE);
int n;
int m;
@Override
public final void run() {
ioTasks.addAll(prevIoTasks);
prevIoTasks.clear();
n = ioTasks.size();
if(n < BATCH_SIZE) {
n += childTasksQueue.drainTo(ioTasks, BATCH_SIZE - n);
}
if(n < BATCH_SIZE) {
n += inTasksQueue.drainTo(ioTasks, BATCH_SIZE - n);
}
try {
if(n > 0) {
m = submit(ioTasks, 0, n);
if(m < n) {
prevIoTasks.addAll(ioTasks.subList(m, n));
}
ioTasks.clear();
}
} catch(final InterruptedException e) {
SVC_TASKS.clear();
}
}
}
@Override
public final boolean put(final O task)
throws EOFException {
if(!isStarted()) {
throw new EOFException();
}
if(isCircular && scheduledTaskCount.sum() >= queueCapacity) {
throw new EOFException();
}
if(inTasksQueue.offer(task)) {
scheduledTaskCount.increment();
return true;
} else {
return false;
}
}
@Override
public final int put(final List<O> tasks, final int from, final int to)
throws EOFException {
if(!isStarted()) {
throw new EOFException();
}
int j;
if(isCircular) {
final long remaining = queueCapacity - scheduledTaskCount.sum();
if(remaining < 1) {
throw new EOFException();
}
j = (int) (from + Math.min(to - from, remaining));
} else {
j = to;
}
int i = from;
while(i < j && isStarted()) {
if(inTasksQueue.offer(tasks.get(i))) {
i ++;
} else {
break;
}
}
final int n = i - from;
scheduledTaskCount.add(n);
return n;
}
@Override
public final int put(final List<O> tasks)
throws EOFException {
if(!isStarted()) {
throw new EOFException();
}
if(isCircular) {
final long remaining = queueCapacity - scheduledTaskCount.sum();
if(remaining < 1) {
throw new EOFException();
}
if(remaining < tasks.size()) {
return put(tasks, 0, (int) remaining);
}
}
int n = 0;
for(final O nextIoTask : tasks) {
if(isStarted() && inTasksQueue.offer(nextIoTask)) {
n ++;
} else {
break;
}
}
scheduledTaskCount.add(n);
return n;
}
@Override
public int getActiveTaskCount() {
return concurrencyLevel - concurrencyThrottle.availablePermits();
}
@Override
public final long getScheduledTaskCount() {
return scheduledTaskCount.sum();
}
@Override
public final long getCompletedTaskCount() {
return completedTaskCount.sum();
}
@Override
public final long getRecycledTaskCount() {
return recycledTaskCount.sum();
}
@Override
public final boolean isIdle() {
return !concurrencyThrottle.hasQueuedThreads() &&
concurrencyThrottle.availablePermits() >= concurrencyLevel;
}
@Override
public final boolean isFullThrottleEntered() {
// TODO use full load threshold
return concurrencyThrottle.availablePermits() == 0;
}
@Override
public final boolean isFullThrottleExited() {
// TODO use full load threshold
return isShutdown() && concurrencyThrottle.availablePermits() > 0;
}
@Override
public List<R> getResults()
throws IOException {
final List<R> ioTaskResults = new ArrayList<>(BATCH_SIZE);
ioResultsQueue.drainTo(ioTaskResults, queueCapacity);
return ioTaskResults;
}
@SuppressWarnings("unchecked")
protected final void ioTaskCompleted(final O ioTask) {
completedTaskCount.increment();
try {
if(isCircular) {
if(IoTask.Status.SUCC.equals(ioTask.getStatus())) {
if(inTasksQueue.offer(ioTask, 1, TimeUnit.MILLISECONDS)) {
recycledTaskCount.increment();
} else {
LOG.warn(
Markers.ERR,
"{}: incoming I/O tasks queue overflow, dropping the I/O task",
toString()
);
}
}
} else if(ioTask instanceof CompositeIoTask) {
final CompositeIoTask parentTask = (CompositeIoTask) ioTask;
if(!parentTask.allSubTasksDone()) {
final List<O> subTasks = parentTask.getSubTasks();
for(final O nextSubTask : subTasks) {
if(!childTasksQueue.offer(nextSubTask, 1, TimeUnit.MILLISECONDS)) {
LOG.warn(
Markers.ERR,
"{}: I/O child tasks queue overflow, dropping the I/O sub-task",
toString()
);
break;
}
}
}
} else if(ioTask instanceof PartialIoTask) {
final PartialIoTask subTask = (PartialIoTask) ioTask;
final CompositeIoTask parentTask = subTask.getParent();
if(parentTask.allSubTasksDone()) {
// execute once again to finalize the things if necessary:
// complete the multipart upload, for example
if(!childTasksQueue.offer((O) parentTask, 1, TimeUnit.MILLISECONDS)) {
LOG.warn(
Markers.ERR, "{}: I/O child tasks queue overflow, dropping the I/O task",
toString()
);
}
}
}
} catch(final InterruptedException e) {
LogUtil.exception(LOG, Level.DEBUG, e, "Interrupted the completed I/O task processing");
}
try {
final R ioResult = ioTask.getResult(
HOST_ADDR,
useStorageDriverResult,
useStorageNodeResult,
useItemInfoResult,
useIoTypeCodeResult,
useStatusCodeResult,
useReqTimeStartResult,
useDurationResult,
useRespLatencyResult,
useDataLatencyResult,
useTransferSizeResult
);
if(!ioResultsQueue.offer(ioResult, 1, TimeUnit.MILLISECONDS)) {
LOG.warn(
Markers.ERR, "{}: I/O task results queue overflow, dropping the result",
toString()
);
}
} catch(final InterruptedException e) {
LogUtil.exception(
LOG, Level.DEBUG, e, "Interrupting the I/O task put to the output buffer"
);
}
}
/*protected final int ioTaskCompletedBatch(final List<O> ioTasks, final int from, final int to) {
int i;
if(isCircular) {
try {
for(i = from; i < to; i += inTasksQueue.put(ioTasks, i, to)) {
LockSupport.parkNanos(1);
}
} catch(final IOException e) {
LogUtil.exception(
LOG, Level.WARN, e, "Failed to enqueue {} I/O tasks for the next execution",
to - from
);
}
}
try {
for(i = from; i < to; i += outTasksQueue.put(ioTasks, i, to)) {
LockSupport.parkNanos(1);
}
} catch(final IOException e) {
LogUtil.exception(
LOG, Level.WARN, e, "Failed to put {} I/O tasks to the output buffer", to - from
);
}
return to - from;
}*/
protected abstract boolean submit(final O ioTask)
throws InterruptedException;
protected abstract int submit(final List<O> ioTasks, final int from, final int to)
throws InterruptedException;
protected abstract int submit(final List<O> ioTasks)
throws InterruptedException;
@Override
public Input<O> getInput() {
return null;
}
@Override
public String getAuthToken()
throws RemoteException {
return authToken;
}
@Override
public void setAuthToken(final String authToken) {
this.authToken = authToken;
}
@Override
protected void doShutdown() {
SVC_TASKS.remove(this);
LOG.debug(Markers.MSG, "{}: shut down", toString());
}
@Override
protected void doInterrupt() {
try {
if(!concurrencyThrottle.tryAcquire(concurrencyLevel, 10, TimeUnit.MILLISECONDS)) {
LOG.debug(Markers.MSG, "{}: interrupting while not in the idle state", toString());
}
} catch(final InterruptedException e) {
LogUtil.exception(LOG, Level.WARN, e, "Failed to await the idle state");
} finally {
LOG.debug(Markers.MSG, "{}: interrupted", toString());
}
}
@Override
protected void doClose()
throws IOException, IllegalStateException {
childTasksQueue.clear();
inTasksQueue.clear();
ioResultsQueue.clear();
LOG.debug(Markers.MSG, "{}: closed", toString());
}
@Override
public String toString() {
return "storage/driver/" + concurrencyLevel + "/%s/" + hashCode();
}
} |
package com.gridbuilder;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.widget.GridLayout;
import android.view.LayoutInflater;
import android.view.SoundEffectConstants;
import android.view.View;
import android.widget.ImageView;
import com.gridbuilder.calculator.PositionCalculator;
import com.gridbuilder.listener.OnItemClickListener;
import com.gridbuilder.listener.OnItemSelectedListener;
import com.gridbuilder.listener.OnViewCreateCallBack;
import com.gridbuilder.utils.BitmapUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class GridBuilder implements View.OnFocusChangeListener, View.OnClickListener {
private Context mContext;
private static final long DEFAULT_ANIM_DURATION = 200;
private LayoutInflater mLayoutInflater;
/**
* Grid
*/
private float mScaleWidthSize = 0;
/**
* Grid
*/
private float mScaleHeightSize = 0;
/**
* Grid
*/
private float mScaleMultiple = 1;
private int mBaseWidth = 200;
private int mBaseHeight = 200;
private int mVerticalMargin = 5;
private int mHorizontalMargin = 5;
private int mTopOutMargin;
private int mBottomOutMargin;
private int mLeftOutMargin;
private int mRightOutMargin;
private int mRowCount = 1;
private int mColumnCount = 1;
/**
* item/
*/
private long mScaleAnimationDuration = DEFAULT_ANIM_DURATION;
/**
* List
*/
private List<? extends GridItem> mGridItemList;
private int mVisibility = View.GONE;
private PositionCalculator mPositionCalculator;
private GridLayout mGridLayout;
private OnItemClickListener mItemClickListener;
private View.OnKeyListener mOnKeyListener;
private OnItemSelectedListener mItemSelectedListener;
private boolean mSoundEffectsEnabled = true;
/**
* - ImageView
*/
private ImageView mReflectionImageView;
private OnViewCreateCallBack mOnViewCreateCallBack;
private GridBuilder(Context context, GridLayout gridLayout) {
this.mContext = context;
this.mGridLayout = gridLayout;
this.mLayoutInflater = LayoutInflater.from(context);
// margin
this.mGridLayout.setUseDefaultMargins(false);
this.mGridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
this.mGridLayout.setClipChildren(false);
this.mGridLayout.setClipToPadding(false);
}
public static GridBuilder newInstance(Context context, GridLayout gridLayout) {
return new GridBuilder(context, gridLayout);
}
/**
*
*
* @param width
* @param height
*/
public GridBuilder setBaseSize(int width, int height) {
this.mBaseWidth = width;
this.mBaseHeight = height;
return this;
}
/**
*
*
* @param margin
*/
public GridBuilder setMargin(int margin) {
this.mVerticalMargin = margin;
this.mHorizontalMargin = margin;
return this;
}
/**
*
*
* @param verticalMargin
* @param horizontalMargin
*/
public GridBuilder setMargin(int verticalMargin, int horizontalMargin) {
this.mVerticalMargin = verticalMargin;
this.mHorizontalMargin = horizontalMargin;
return this;
}
public GridBuilder setOutMargin(int top, int bottom, int left, int right) {
this.mTopOutMargin = top;
this.mBottomOutMargin = bottom;
this.mLeftOutMargin = left;
this.mRightOutMargin = right;
return this;
}
public GridBuilder setSoundEffectsEnabled(boolean enabled) {
this.mSoundEffectsEnabled = enabled;
return this;
}
/**
* GridLayoutGrid
*
* @param gridItem Grid
*/
private GridBuilder addItem(GridItem gridItem) {
View itemLayout = null;
if (null != mOnViewCreateCallBack) {
itemLayout = mOnViewCreateCallBack.onViewCreate(mLayoutInflater, gridItem);
}
if (null == itemLayout) {
return this;
}
GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
// width/height,/
layoutParams.width = (gridItem.getWidth() > 0 ? gridItem.getWidth() : gridItem.getColumnSpec() * mBaseWidth)
+ ((gridItem.getColumnSpec() > 1 && gridItem.getWidth() <= 0 ? mHorizontalMargin * (gridItem.getColumnSpec() - 1) : 0));
layoutParams.height = (gridItem.getHeight() > 0 ? gridItem.getHeight() : gridItem.getRowSpec() * mBaseHeight)
+ ((gridItem.getRowSpec() > 1 && gridItem.getWidth() <= 0 ? mVerticalMargin * (gridItem.getRowSpec() - 1) : 0));
if (gridItem.getWidth() <= 0) {
gridItem.setWidth(layoutParams.width);
}
if (gridItem.getHeight() <= 0) {
gridItem.setHeight(layoutParams.height);
}
layoutParams.rowSpec = GridLayout.spec(gridItem.getRow(), gridItem.getRowSpec());
layoutParams.columnSpec = GridLayout.spec(gridItem.getColumn(), gridItem.getColumnSpec());
// item,(itemscale)
if (gridItem.getRow() > 0) {
layoutParams.topMargin = mVerticalMargin;
}
if (gridItem.getColumn() > 0) {
layoutParams.leftMargin = mHorizontalMargin;
}
itemLayout.setLayoutParams(layoutParams);
itemLayout.setFocusable(true);
itemLayout.setClickable(true);
itemLayout.setOnFocusChangeListener(this);
itemLayout.setOnClickListener(this);
itemLayout.setOnKeyListener(mOnKeyListener);
itemLayout.setSoundEffectsEnabled(false);
if (mGridLayout.getChildCount() == 0 && gridItem == mGridItemList.get(0)) {
itemLayout.setTag(GridItem.TAG_FIRST_ITEM);
}
this.mGridLayout.addView(itemLayout);
return this;
}
/**
* GridList
*
* @param gridItemList GridList
*/
public GridBuilder setGridItemList(List<? extends GridItem> gridItemList) {
this.mGridItemList = gridItemList;
return this;
}
/**
*
*
* @param visibility View.VISIBLE, View.INVISIBLE, View.GONE
*/
public GridBuilder setReflectionVisibly(int visibility) {
this.mVisibility = visibility;
return this;
}
/**
* item,0
*
* @param duration
*/
public GridBuilder setScaleAnimationDuration(long duration) {
this.mScaleAnimationDuration = duration;
return this;
}
/**
* item
*
* @param width
* @param height
*/
public GridBuilder setScaleSize(float width, float height) {
this.mScaleWidthSize = width * 2;
this.mScaleHeightSize = height * 2;
return this;
}
/**
* item
*
* @param multiple
*/
public GridBuilder setScaleMultiple(float multiple) {
this.mScaleMultiple = multiple;
return this;
}
/**
*
*
* @param calculator
*/
public GridBuilder setPositionCalculator(PositionCalculator calculator) {
mPositionCalculator = calculator;
return this;
}
private void measure() {
HashMap<Integer, Integer> rowMap = new HashMap<>();
HashMap<Integer, Integer> columnMap = new HashMap<>();
for (GridItem item : mGridItemList) {
int row = item.getRow();
int column = item.getColumn();
if (rowMap.containsKey(row)) {
rowMap.put(row, rowMap.get(row) + item.getColumnSpec());
} else {
rowMap.put(row, item.getColumnSpec());
}
if (columnMap.containsKey(column)) {
columnMap.put(column, columnMap.get(column) + item.getRowSpec());
} else {
columnMap.put(column, item.getRowSpec());
}
}
Set<Integer> rowKeySet = rowMap.keySet();
for (Integer i : rowKeySet) {
int rows = rowMap.get(i);
if (rows < mColumnCount) {
continue;
}
mColumnCount = rows;
}
Set<Integer> columnKeySet = columnMap.keySet();
for (Integer i : columnKeySet) {
int columns = columnMap.get(i);
if (columns < mRowCount) {
continue;
}
mRowCount = columns;
}
}
public void build() {
if (null != mPositionCalculator) {
mPositionCalculator.calculate(mGridItemList);
}
if (null == mGridItemList || 0 == mGridItemList.size()) {
return;
}
this.measure();
this.mGridLayout.setPadding(mLeftOutMargin, mTopOutMargin, mRightOutMargin, mBottomOutMargin);
this.mGridLayout.setColumnCount(mColumnCount);
if (mVisibility != View.GONE) {
mRowCount++;
}
// this.mGridLayout.setRowCount(mRowCount);
for (GridItem item : mGridItemList) {
if (null == item) {
continue;
}
addItem(item);
}
if (mVisibility != View.GONE) {
this.addReflectionImageView();
}
}
public void addItem(List<? extends GridItem> gridItems) {
if (null == gridItems) {
return;
}
for (GridItem item : gridItems) {
addItem(item);
}
}
/**
* GridLayout
*/
private void addReflectionImageView() {
mReflectionImageView = new ImageView(mContext);
GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
layoutParams.width = mColumnCount * mBaseWidth
+ ((mColumnCount > 1 ? mHorizontalMargin * (mColumnCount - 1) : 0));
layoutParams.height = mBaseHeight;
layoutParams.rowSpec = GridLayout.spec(mRowCount - 1, 1);
layoutParams.columnSpec = GridLayout.spec(0, mColumnCount);
mReflectionImageView.setLayoutParams(layoutParams);
mReflectionImageView.setScaleType(ImageView.ScaleType.FIT_XY);
this.refreshReflection(0);
mGridLayout.addView(mReflectionImageView);
mReflectionImageView.setVisibility(mVisibility);
}
/**
*
*
* @param height ,height0;,
* ,
*/
private void refreshReflection(final int height) {
if (null == mReflectionImageView || mVisibility != View.VISIBLE) {
return;
}
Bitmap bitmap = BitmapUtils.draw(BitmapUtils.convertViewToBitmap(
mGridLayout, mBottomOutMargin, height));
mReflectionImageView.setImageBitmap(bitmap);
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!(v instanceof IGridItemView)) {
return;
}
GridItem gridItem = ((IGridItemView) v).getGridItem();
if (null != mItemSelectedListener) {
mItemSelectedListener.onItemSelected(gridItem, v, hasFocus);
}
if (hasFocus) {
v.bringToFront();
mGridLayout.invalidate();
enlargeItem(v, gridItem);
refreshReflection(mBaseHeight);
if (mSoundEffectsEnabled) {
v.setSoundEffectsEnabled(true);
v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
v.setSoundEffectsEnabled(false);
}
} else {
narrowItem(v, gridItem);
if (null == mGridLayout.getFocusedChild()) {
refreshReflection(mBaseHeight);
}
}
}
@Override
public void onClick(View v) {
if (null == mItemClickListener || !(v instanceof IGridItemView)) {
return;
}
mItemClickListener.onItemClick(((IGridItemView) v).getGridItem(), v);
}
/**
* item
*/
public GridBuilder setOnItemClickListener(OnItemClickListener listener) {
this.mItemClickListener = listener;
return this;
}
/**
* item
*/
public GridBuilder setOnItemSelectedListener(OnItemSelectedListener listener) {
this.mItemSelectedListener = listener;
return this;
}
public GridBuilder setOnKeyListener(View.OnKeyListener l) {
this.mOnKeyListener = l;
return this;
}
private void enlargeItem(View view, GridItem item) {
if (0 == mScaleWidthSize && 0 == mScaleHeightSize && 1 == mScaleMultiple) {
return;
}
float width = item.getWidth();
float height = item.getHeight();
if (mScaleWidthSize > 0 || mScaleWidthSize > 0) {
scaleAnim(view, 1, 1, (width + mScaleWidthSize) / width, (height + mScaleHeightSize) / height, mScaleAnimationDuration);
} else {
scaleAnim(view, 1, 1, mScaleMultiple, mScaleMultiple, mScaleAnimationDuration);
}
}
private void narrowItem(View view, GridItem item) {
if (0 == mScaleWidthSize && 0 == mScaleHeightSize && 1 == mScaleMultiple) {
return;
}
float width = item.getWidth();
float height = item.getHeight();
if (mScaleWidthSize > 0 || mScaleWidthSize > 0) {
scaleAnim(view, (width + mScaleWidthSize) / width, (height + mScaleHeightSize) / height, 1, 1, mScaleAnimationDuration);
} else {
scaleAnim(view, mScaleMultiple, mScaleMultiple, 1, 1, mScaleAnimationDuration);
}
}
public static void scaleAnim(View view, float originalWidth, float originalHeight, float targetWidth, float targetHeight) {
scaleAnim(view, originalWidth, originalHeight, targetWidth, targetHeight, DEFAULT_ANIM_DURATION);
}
/**
* scale
*/
public static void scaleAnim(View view, float originalWidth, float originalHeight, float targetWidth, float targetHeight, long duration) {
ObjectAnimator animX = ObjectAnimator.ofFloat(view, "scaleX",
originalWidth, targetWidth);
ObjectAnimator animY = ObjectAnimator.ofFloat(view, "scaleY",
originalHeight, targetHeight);
AnimatorSet set = new AnimatorSet();
set.setDuration(duration);
set.playTogether(animX, animY);
set.start();
}
public GridBuilder setOnCreateViewCallBack(OnViewCreateCallBack callBack) {
this.mOnViewCreateCallBack = callBack;
return this;
}
} |
package com.itti7.itimeu;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.app.LoaderManager;
import android.content.Loader;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.itti7.itimeu.data.ItemContract.ItemEntry;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Allows user to create a new item or edit an existing one.
*/
public class EditorActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener,
LoaderManager.LoaderCallbacks<Cursor> {
/**
* Identifier for the item data loader
*/
private static final int EXISTING_ITEM_LOADER = 0;
private static final int NAME_MAX_COUNT = 15;
private static final int DETAIL_MAX_COUNT = 20;
/**
* Content URI for the existing item (null if it's a new item)
*/
private Uri mCurrentItemUri;
/**
* EditText field to enter the item's name
*/
private EditText mNameEditText;
/**
* EditText field to enter the item's detail
*/
private EditText mDetailEditText;
/**
* Count view EditText's Character
*/
private TextView mNameCountTextView;
private TextView mDetailCountTextView;
/**
* EditText field to enter the item's date
*/
private EditText mDateEditText;
/**
* TextView field to enter the item's total unit
*/
private TextView mTotalUnitTextView;
/**
* ImageButton to increase total unit number
*/
private ImageButton mUnitPlusImageButton;
/**
* ImageButton to decrease total unit number
*/
private ImageButton mUnitMinusImageButton;
/**
* Total unit convert integer value
*/
private int mTotalUnitNumber;
/**
* Total unit convert string value
*/
private String mTotalUnitString;
/**
* Creation date
*/
private String mDate;
// Simple date format
public static final String DATE_FORMAT = "yyyy.MM.dd";
// Date year, month, day;
private int mYear, mMonth, mDay;
/**
* Status of the item. The possible valid values are in the ItemContract.java file:
* {@link ItemEntry#STATUS_TODO}, {@link ItemEntry#STATUS_DO}, {@link ItemEntry#STATUS_DONE}
*/
private int mStatus = ItemEntry.STATUS_TODO;
/**
* Boolean flag that keeps track of whether the item has been edited (true) or not (false)
*/
private boolean mItemHasChanged = false;
/**
* OnTouchListener that listens for any user touches on a View, implying that they are modifying
* the view, and we change the mItemHasChanged boolean to true.
*/
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mItemHasChanged = true;
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
// Examine the intent that was used to launch this activity,
// Examine the intent that was used to launch this activity,
// in order to figure out if we're creating a new item or editing an existing one.
Intent intent = getIntent();
mCurrentItemUri = intent.getData();
// If the intent DOES NOT contain a item content URI, then we know that we are
// creating a new item.
TextView titleTextView = (TextView) findViewById(R.id.editor_title_txt_view);
if (mCurrentItemUri == null) {
// This is a new item, so change the title in TextView "ADD"
titleTextView.setText(R.string.editor_title_add);
} else {
// Otherwise this is an existing item, so change the title in TextView "EDIT"
titleTextView.setText(R.string.editor_title_edit);
// Initialize a loader to read the item data from the database
// and display the current values in the editor
getLoaderManager().initLoader(EXISTING_ITEM_LOADER, null, this);
}
mNameEditText = (EditText) findViewById(R.id.name_edit_txt);
mDetailEditText = (EditText) findViewById(R.id.detail_edit_txt);
mNameCountTextView = (TextView) findViewById(R.id.editor_name_count_txt);
mDetailCountTextView = (TextView) findViewById(R.id.editor_detail_count_txt);
countNameCharAndShow();
nameCursorVisibility();
countDetailCharAndShow();
detailCursorAndCountCharVisibility();
mTotalUnitTextView = (TextView) findViewById(R.id.get_total_unit_txt_view);
mDate = intent.getStringExtra("date");
mDateEditText = (EditText) findViewById(R.id.editor_date_edit_txt);
mTotalUnitNumber = Integer.parseInt(mTotalUnitTextView.getText().toString().trim());
mUnitMinusImageButton = (ImageButton) findViewById(R.id.unit_minus_btn);
mUnitPlusImageButton = (ImageButton) findViewById(R.id.unit_plus_btn);
// Setup OnTouchListeners on all the input fields, so we can determine if the user
// has touched or modified them. This will let us know if there are unsaved changes
// or not, if the user tries to leave the editor without saving.
mNameEditText.setOnTouchListener(mTouchListener);
mDetailEditText.setOnTouchListener(mTouchListener);
mUnitMinusImageButton.setOnTouchListener(mTouchListener);
mUnitPlusImageButton.setOnTouchListener(mTouchListener);
// Get the date selected by the user.
dateSelection();
// change total unit number
getTotalUnitNumber();
// click ok
submit();
}
/**
* @param view DatePickerDialog
* @param selectedYear Year selected by the user
* @param selectedMonth Month selected by the user
* @param selectedDay Date selected by the user
*/
@Override
public void onDateSet(DatePickerDialog view, int selectedYear, int selectedMonth, int selectedDay) {
Calendar calendar = Calendar.getInstance();
// Assign Selected Date in DatePickerDialog
mYear = selectedYear;
mMonth = selectedMonth;
mDay = selectedDay;
// Set Date in List
calendar.set(mYear, mMonth, mDay);
Date date = calendar.getTime();
mDate = getDate(date);
mDateEditText.setText(mDate);
}
void dateSelection() {
mDateEditText.setFocusable(false);
mDateEditText.setOnTouchListener(mTouchListener);
mDateEditText.setText(mDate);
mDateEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, Locale.KOREA);
try {
// String -> Date
Date date = format.parse(mDate);
// Setting calender -> list's date
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
mYear = calendar.get(Calendar.YEAR);
mMonth = calendar.get(Calendar.MONTH);
mDay = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog
= DatePickerDialog.newInstance(EditorActivity.this, mYear, mMonth, mDay);
datePickerDialog.show(getFragmentManager(), "DateFragment");
} catch (ParseException e) {
Log.e("EditorActivity", "ParseException: " + e);
}
}
});
}
/**
* Get user input from editor and save item into database.
*/
private boolean saveItem() {
// Read from input fields
// Use trim to eliminate leading or trailing white space
String nameString = mNameEditText.getText().toString().trim();
String detailString = mDetailEditText.getText().toString().trim();
// Check whether name edit text is empty.
// if name is empty return false, else save the item than return true
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
if (TextUtils.isEmpty(nameString)) {
mNameEditText.startAnimation(shake);
Toast.makeText(this, getString(R.string.input_name_toast), Toast.LENGTH_SHORT).show();
return false;
} else {
Log.v("EditorActivity", mDate);
// Determine if this is a new or existing item by checking
// if mCurrentItemUri is null or not
if (mCurrentItemUri == null) {
// Create a ContentValues object for a new Item
ContentValues createValues = new ContentValues();
createValues.put(ItemEntry.COLUMN_ITEM_NAME, nameString);
createValues.put(ItemEntry.COLUMN_ITEM_DETAIL, detailString);
createValues.put(ItemEntry.COLUMN_ITEM_TOTAL_UNIT, mTotalUnitNumber);
createValues.put(ItemEntry.COLUMN_ITEM_STATUS, mStatus);
createValues.put(ItemEntry.COLUMN_ITEM_DATE, mDate);
Log.v("EditorActivity", mDate);
// This is a NEW item, so insert a new item into the provider,
// returning the content URI for the new item.
Uri newUri = getContentResolver().insert(ItemEntry.CONTENT_URI, createValues);
// Show a toast message depending on whether or not the insertion was successful.
if (newUri == null) {
// If the new content URI is null, then there was an error with insertion.
Toast.makeText(this, getString(R.string.create_item_fail), Toast.LENGTH_SHORT).show();
} else {
// Otherwise, the insertion was successful and we can display a toast.
Toast.makeText(this, getString(R.string.create_item_success), Toast.LENGTH_SHORT).show();
}
} else {
// Create a ContentValues object for a existing item
ContentValues editValues = new ContentValues();
editValues.put(ItemEntry.COLUMN_ITEM_NAME, nameString);
editValues.put(ItemEntry.COLUMN_ITEM_DETAIL, detailString);
editValues.put(ItemEntry.COLUMN_ITEM_TOTAL_UNIT, mTotalUnitNumber);
editValues.put(ItemEntry.COLUMN_ITEM_DATE, mDate);
// Otherwise this is an EXISTING item, so update the item with content URI: mCurrentItemUri
// and pass in the new ContentValues. Pass in null for the selection and selection args
// because mCurrentItemUri will already identify the correct row in the database that
// we want to modify.
int rowsAffected = getContentResolver().update(mCurrentItemUri, editValues, null, null);
// Show a toast message depending on whether or not the update was successful.
if (rowsAffected == 0) {
// If no rows were affected, then there was an error with the update.
Toast.makeText(this, getString(R.string.update_item_fail), Toast.LENGTH_SHORT).show();
} else {
// Otherwise, the update was successful and we can display a toast.
Toast.makeText(this, getString(R.string.update_item_success), Toast.LENGTH_SHORT).show();
}
}
return true;
}
}
/**
* Save or cancel items.
*/
private void submit() {
Button okButton = (Button) findViewById(R.id.add_ok_btn);
Button cancelButton = (Button) findViewById(R.id.add_cancel_btn);
//click ok button
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// success to insert item
if (saveItem()) finish();
}
});
//click cancel button
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mItemHasChanged) {
// if there are unsaved changes, setup a dialog to warn the user.
// Create a click listener to handle the user confirming that
// changes should be discarded.
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked "Discard" button, navigate to parent activity.
finish();
}
};
// Show a dialog that notifies the user they have unsaved changes
showUnsavedChangesDialog(discardButtonClickListener);
} else finish();
}
});
}
/**
* This method is called when the back button is pressed.
*/
@Override
public void onBackPressed() {
if (!mItemHasChanged) {
super.onBackPressed();
return;
}
// Otherwise if there are unsaved changes, setup a dialog to warn the user.
// Create a click listener to handle the user confirming that changes should be discarded.
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked "Discard" button, close the current activity.
finish();
}
};
// Show dialog that there are unsaved changes
showUnsavedChangesDialog(discardButtonClickListener);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Since the editor shows all item attributes, define a projection that contains
// all columns from the item table
String[] projection = {
ItemEntry._ID,
ItemEntry.COLUMN_ITEM_NAME,
ItemEntry.COLUMN_ITEM_DETAIL,
ItemEntry.COLUMN_ITEM_DATE,
ItemEntry.COLUMN_ITEM_TOTAL_UNIT,
ItemEntry.COLUMN_ITEM_UNIT,
ItemEntry.COLUMN_ITEM_STATUS
};
String[] date = {mDate};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
mCurrentItemUri, // Query the content URI for the current item
projection, // Columns to include in the resulting Cursor
"date = ?", // No selection clause
date, // No selection arguments
null); // Default sort order
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Bail early if the cursor is null or there is less than 1 row in the cursor
if (cursor == null || cursor.getCount() < 1) {
return;
}
if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_NAME);
int detailColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_DETAIL);
//int unitColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_UNIT);
int totalUnitColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_TOTAL_UNIT);
//int statusColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_STATUS);
int dateColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_DATE);
String name = cursor.getString(nameColumnIndex);
String detail = cursor.getString(detailColumnIndex);
String date = cursor.getString(dateColumnIndex);
//int unit = cursor.getInt(unitColumnIndex);
int totalUnit = cursor.getInt(totalUnitColumnIndex);
//int status = cursor.getInt(statusColumnIndex);
mTotalUnitString = Integer.toString(totalUnit);
mNameEditText.setText(name);
mDetailEditText.setText(detail);
mTotalUnitNumber = totalUnit;
mTotalUnitTextView.setText(mTotalUnitString);
mDate = date;
mDateEditText.setText(mDate);
getTotalUnitNumber();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mNameEditText.setText("");
mDetailEditText.setText("");
mTotalUnitTextView.setText(getString(R.string.reset_total_unit));
}
/**
* Show a dialog that warns the user there are unsaved changes that will be lost
* if they continue leaving the editor.
*
* @param discardButtonClickListener is the click listener for what to do when
* the user confirms they want to discard their changes
*/
private void showUnsavedChangesDialog(
DialogInterface.OnClickListener discardButtonClickListener) {
// Create an AlertDialog.Builder and set the message, and click listeners
// for the positive and negative buttons on the dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.unsaved_change_msg));
builder.setPositiveButton(getString(R.string.discard_btn), discardButtonClickListener);
builder.setNegativeButton(getString(R.string.keep_editing_btn), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked the "Keep editing" button, so dismiss the dialog
// and continue editing the item.
if (dialog != null) {
dialog.dismiss();
}
}
});
// Create and show the AlertDialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
/**
* this function change unit number in unit text view according to plus/minus image button.
* minimum number: 1 / maximum number: 20
* ut
*/
private void getTotalUnitNumber() {
getUnitImageButtonSrc();
// increase unit number
mUnitPlusImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mTotalUnitNumber < 20) {
mUnitPlusImageButton.setImageResource(R.drawable.ic_unit_plus_true);
mTotalUnitNumber++;
mTotalUnitString = Integer.toString(mTotalUnitNumber);
mTotalUnitTextView.setText(mTotalUnitString);
}
getUnitImageButtonSrc();
}
});
// decrease unit number
mUnitMinusImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mTotalUnitNumber > 1) {
mTotalUnitNumber
mTotalUnitString = Integer.toString(mTotalUnitNumber);
mTotalUnitTextView.setText(mTotalUnitString);
}
getUnitImageButtonSrc();
}
});
}
/**
* This function change plus/minus imageButton src according to Unit number range
*/
private void getUnitImageButtonSrc() {
if (mTotalUnitNumber <= 1) {
mUnitMinusImageButton.setImageResource(R.drawable.ic_unit_minus_false);
mUnitPlusImageButton.setImageResource(R.drawable.ic_unit_plus_true);
} else if (mTotalUnitNumber < 20) {
mUnitMinusImageButton.setImageResource(R.drawable.ic_unit_minus_true);
mUnitPlusImageButton.setImageResource(R.drawable.ic_unit_plus_true);
} else {
mUnitMinusImageButton.setImageResource(R.drawable.ic_unit_minus_true);
mUnitPlusImageButton.setImageResource(R.drawable.ic_unit_plus_false);
}
}
/**
* It is a function of today's date.
*
* @return Return the current month and day.
*/
public String getDate(Date date) {
return new SimpleDateFormat(DATE_FORMAT, Locale.KOREA).format(date);
}
/**
* This function count name character in edit text view and show on text view
*/
public void countNameCharAndShow() {
mNameEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
int length = charSequence.length();
if (length == 0) {
mNameCountTextView.setVisibility(View.INVISIBLE);
} else {
mNameCountTextView.setVisibility(View.VISIBLE);
mNameCountTextView.setText(length + " / " + NAME_MAX_COUNT);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
// focus change
mNameEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
mNameCountTextView.setVisibility(View.INVISIBLE);
} else {
mNameCountTextView.setVisibility(View.VISIBLE);
}
}
});
}
/**
* This function count detail character in edit text view and show on text view
*/
public void countDetailCharAndShow() {
mDetailEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
int length = charSequence.length();
if (length == 0) {
mDetailCountTextView.setVisibility(View.INVISIBLE);
} else {
mDetailCountTextView.setVisibility(View.VISIBLE);
mDetailCountTextView.setText(length + " / " + DETAIL_MAX_COUNT);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
mDetailEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
mDetailCountTextView.setVisibility(View.INVISIBLE);
} else {
mDetailCountTextView.setVisibility(View.VISIBLE);
}
}
});
}
/**
* This function change name cursor visibility.
*/
public void nameCursorVisibility() {
mNameEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE) {
mNameEditText.setCursorVisible(false);
}
return false;
}
});
mNameEditText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mNameEditText.setCursorVisible(true);
return false;
}
});
}
/**
* This function change detail cursor visibility.
*/
public void detailCursorAndCountCharVisibility() {
mDetailEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE) {
mDetailEditText.setCursorVisible(false);
mDetailCountTextView.setVisibility(View.INVISIBLE);
}
return false;
}
});
mDetailEditText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mDetailEditText.setCursorVisible(true);
return false;
}
});
}
} |
package net.fasolato.jfmigrate;
import net.fasolato.jfmigrate.builders.Change;
import net.fasolato.jfmigrate.builders.Data;
import net.fasolato.jfmigrate.internal.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.sql.*;
import java.util.*;
/**
* Main class to manage JFMigrate
*/
public class JFMigrate {
private static Logger log = LogManager.getLogger(JFMigrate.class);
private List<String> packages;
private SqlDialect dialect;
private String schema;
/**
* Constructor that bootstraps JFMigrate.
*
* It basically reads a jfmigrate.properties file in the classpath and configures the library (database dialcet, connection string...)
*/
public JFMigrate() {
Properties properties = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("jfmigrate.properties");
try {
properties.load(stream);
String configDialect = properties.getProperty("jfmigrate.db.dialect");
dialect = SqlDialect.H2;
if (configDialect.equalsIgnoreCase("h2")) {
dialect = SqlDialect.H2;
} else if (configDialect.equalsIgnoreCase("sqlserver")) {
dialect = SqlDialect.SQL_SERVER;
} else if (configDialect.equalsIgnoreCase("pgsql")) {
dialect = SqlDialect.PGSQL;
} else if (configDialect.equalsIgnoreCase("mysql")) {
dialect = SqlDialect.MYSQL;
} else if (configDialect.equalsIgnoreCase("oracle")) {
dialect = SqlDialect.ORACLE;
} else if (configDialect.equalsIgnoreCase("sqlite")) {
dialect = SqlDialect.SQLITE;
}
} catch (IOException e) {
log.error(e);
throw new JFException("Error reading properties file", e);
}
packages = new ArrayList<String>();
}
/**
* Registers a package by name as a source of migration classes
* @param pkg The package name
*/
public void registerPackage(String pkg) {
packages.add(pkg);
}
/**
* Registers a package from a class object as a source of migration classes.
* @param clazz The class belonging to the package to use as a source
*/
public void registerPackage(Class<?> clazz) {
packages.add(clazz.getPackage().getName());
}
private IDialectHelper getDialectHelper() {
switch (dialect) {
case SQL_SERVER:
return new SqlServerDialectHelper();
case H2:
return new H2DialectHelper();
case PGSQL:
return new PGSqlDialectHelper();
case MYSQL:
return new MysqlDialectHelper(schema);
case ORACLE:
return new OracleDialectHelper();
case SQLITE:
return new SqliteDialectHelper();
default:
throw new NotImplementedException();
}
}
private long getDatabaseVersion(IDialectHelper helper, Connection conn) throws SQLException {
String versionTableExistence = helper.getDatabaseVersionTableExistenceCommand();
boolean exists = true;
ResultSet rs = null;
PreparedStatement st = new LoggablePreparedStatement(conn, versionTableExistence);
log.info("Executing{}{}", System.lineSeparator(), st);
try {
rs = st.executeQuery();
if (!rs.next()) {
exists = false;
} else {
if (rs.getInt(1) == 0) {
exists = false;
}
}
} catch (SQLSyntaxErrorException oracleException) {
if (oracleException.getMessage().startsWith("ORA-00942:")) {
exists = false;
} else {
throw oracleException;
}
} finally {
try {
rs.close();
st.close();
} catch(Exception ex) {
log.error("Error closing resultset/ststement", ex);
}
}
if (!exists) {
createVersionTable(helper, conn);
return -1;
}
String currentVersionCommand = helper.getDatabaseVersionCommand();
long dbVersion = -1;
st = new LoggablePreparedStatement(conn, currentVersionCommand);
log.info("Executing{}{}", System.lineSeparator(), st);
rs = st.executeQuery();
if (rs.next()) {
dbVersion = rs.getLong(1);
}
rs.close();
st.close();
return dbVersion;
}
private void createVersionTable(IDialectHelper helper, Connection conn) throws SQLException {
String createCommand = helper.getVersionTableCreationCommand();
PreparedStatement st = new LoggablePreparedStatement(conn, createCommand);
log.info("Executing{}{}", System.lineSeparator(), st);
st.execute();
}
/**
* Method to start an UP migration running against a real database engine.
* @throws Exception
*/
public void migrateUp() throws Exception {
migrateUp(-1, null, false);
}
/**
* Method to start an UP migration with a Writer output (to write for example an output file).
* @param out The Writer to write the SQL code to
* @throws Exception
*/
public void migrateUp(Writer out) throws Exception {
migrateUp(-1, out, false);
}
/**
* Method to start an UP migration with a Writer output (to write for example an output file).
* @param out The Writer to write the SQL code to
* @param createVersionInfoTable Flag to decide whether to create the migration history table if missing
* @throws Exception
*/
public void migrateUp(Writer out, boolean createVersionInfoTable) throws Exception {
migrateUp(-1, out, createVersionInfoTable);
}
/**
* Method to start an UP migration with a Writer output (to write for example an output file).
* @param startMigrationNumber Force JFMigrate to start from this migration (the existence of this migration is tested anyway)
* @param out The Writer to write the SQL code to
* @param createVersionInfoTable Flag to decide whether to create the migration history table if missing
* @throws Exception
*/
public void migrateUp(int startMigrationNumber, Writer out, boolean createVersionInfoTable) throws Exception {
IDialectHelper helper = getDialectHelper();
DatabaseHelper dbHelper = new DatabaseHelper();
Connection conn = null;
try {
conn = dbHelper.getConnection();
conn.setAutoCommit(false);
long dbVersion = 0;
if (out == null) {
dbVersion = getDatabaseVersion(helper, conn);
} else if (createVersionInfoTable) {
out.write("-- Version table");
out.write(System.lineSeparator());
out.write(System.lineSeparator());
out.write(helper.getVersionTableCreationCommand());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
out.write("
out.write(System.lineSeparator());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
log.info("Current database version: {}", dbVersion);
for (String p : packages) {
log.debug("Migrating up from package {}", p);
List<JFMigrationClass> migrations = ReflectionHelper.getAllMigrations(p);
Collections.sort(migrations, new Comparator<JFMigrationClass>() {
public int compare(JFMigrationClass jfMigrationClass, JFMigrationClass t1) {
return Long.compare(jfMigrationClass.getMigrationNumber(), t1.getMigrationNumber());
}
});
for (JFMigrationClass m : migrations) {
if (m.executeForDialect(dialect) && (m.getMigrationNumber() > dbVersion && (startMigrationNumber == -1 || m.getMigrationNumber() >= startMigrationNumber))) {
log.debug("Applying migration UP {}({})", m.getMigrationName(), m.getMigrationNumber());
m.up();
String[] scriptVersionCheck = null;
if (out != null) {
out.write(String.format("-- Migration %s(%s)", m.getMigrationName(), m.getMigrationNumber()));
out.write(System.lineSeparator());
out.write(System.lineSeparator());
scriptVersionCheck = helper.getScriptCheckMigrationUpVersionCommand();
if (scriptVersionCheck != null && scriptVersionCheck.length != 0) {
out.write(scriptVersionCheck[0].replaceAll("\\?", String.valueOf(m.getMigrationNumber())));
out.write(System.lineSeparator());
}
}
PreparedStatement st;
for (Change c : m.migration.getChanges()) {
if (Data.class.isAssignableFrom(c.getClass())) {
Data d = (Data) c;
for (Pair<String, Object[]> commands : d.getSqlCommand(helper)) {
st = new LoggablePreparedStatement(conn, commands.getA());
for (int iv = 0; iv < commands.getB().length; iv++) {
st.setObject(iv + 1, commands.getB()[iv]);
}
log.info("Executing{}{}", System.lineSeparator(), st);
if (out == null) {
st.execute();
} else {
out.write(st.toString().trim());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
}
} else {
for (Pair<String, Object[]> commands : c.getSqlCommand(helper)) {
st = new LoggablePreparedStatement(conn, commands.getA());
if (commands.getB() != null) {
for (int iv = 0; iv < commands.getB().length; iv++) {
st.setObject(iv + 1, commands.getB()[iv]);
}
}
log.info("Executing{}{}", System.lineSeparator(), st);
if (out == null) {
st.execute();
} else {
out.write(st.toString().trim());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
}
}
}
String migrationVersionCommand = helper.getInsertNewVersionCommand();
st = new LoggablePreparedStatement(conn, migrationVersionCommand);
st.setLong(1, m.getMigrationNumber());
st.setString(2, m.getMigrationName());
log.info("Executing{}{}", System.lineSeparator(), st);
if (out == null) {
st.execute();
} else {
out.write(st.toString().trim());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
if (out != null) {
if (scriptVersionCheck != null) {
out.write(scriptVersionCheck[1]);
out.write(System.lineSeparator());
}
out.write("
out.write(System.lineSeparator());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
log.debug("Applied migration {}", m.getClass().getSimpleName());
} else {
if(!m.executeForDialect(dialect)) {
log.info("Skipping migration {} because DB dialect {} is explicitly skipped", m.getMigrationNumber(), dialect);
} else if (m.getMigrationNumber() <= dbVersion) {
log.info("Skipping migration {} because DB is newer", m.getMigrationNumber());
} else {
log.info("Skipping migration {} because lower than selected start migration number ({})", m.getMigrationNumber(), startMigrationNumber);
}
}
}
}
if (conn != null) {
conn.commit();
}
} catch (Exception e) {
if (conn != null) {
try {
conn.rollback();
log.error("Connection rolled back");
} catch (Exception ex) {
log.error("Error while rolling back transaction", ex);
}
}
log.error("Error executing query", e);
throw e;
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (Exception ex) {
log.error(ex);
}
}
}
/**
* Method to start an DOWN migration running against a true database engine. JFMigrate starts from the current DB migration and executes DOWN migrations until it reaches targetMigration.
* @param targetMigration The migration number where to stop. The initial database state is migration 0.
* @throws Exception
*/
public void migrateDown(int targetMigration) throws Exception {
migrateDown(targetMigration, null);
}
/**
* Method to start an DOWN migration with a Writer output (to write for example an output file). JFMigrate starts from the current DB migration and executes DOWN migrations until it reaches targetMigration.
* @param targetMigration The migration number where to stop. The initial database state is migration 0.
* @param out The Writer to write the SQL code to
* @throws Exception
*/
public void migrateDown(int targetMigration, Writer out) throws Exception {
IDialectHelper helper = getDialectHelper();
DatabaseHelper dbHelper = new DatabaseHelper();
Connection conn = null;
try {
conn = dbHelper.getConnection();
conn.setAutoCommit(false);
long dbVersion = Long.MAX_VALUE;
if (out == null) {
dbVersion = getDatabaseVersion(helper, conn);
}
log.info("Current database version: {}", dbVersion);
if (dbVersion <= 0) {
//No migration table or DB is at first migration, nothing to be done
return;
}
for (String p : packages) {
log.debug("Migrating down from package {}", p);
List<JFMigrationClass> migrations = ReflectionHelper.getAllMigrations(p);
Collections.sort(migrations, new Comparator<JFMigrationClass>() {
public int compare(JFMigrationClass jfMigrationClass, JFMigrationClass t1) {
return -1 * Long.compare(jfMigrationClass.getMigrationNumber(), t1.getMigrationNumber());
}
});
for (JFMigrationClass m : migrations) {
if (m.executeForDialect(dialect) && (m.getMigrationNumber() <= dbVersion && m.getMigrationNumber() > targetMigration)) {
log.debug("Applying migration DOWN {}({})", m.getMigrationName(), m.getMigrationNumber());
m.down();
String[] scriptVersionCheck = null;
if (out != null) {
out.write(String.format("-- Migration down %s(%s)", m.getMigrationName(), m.getMigrationNumber()));
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
scriptVersionCheck = helper.getScriptCheckMigrationDownVersionCommand();
if (out != null && scriptVersionCheck != null) {
out.write(scriptVersionCheck[0].replaceAll("\\?", String.valueOf(m.getMigrationNumber())));
out.write(System.lineSeparator());
}
PreparedStatement st;
if (out == null) {
String testVersionSql = helper.getSearchDatabaseVersionCommand();
st = new LoggablePreparedStatement(conn, testVersionSql);
st.setLong(1, m.getMigrationNumber());
log.info("Executing{}{}", System.lineSeparator(), st);
ResultSet rs = st.executeQuery();
if (!rs.next()) {
throw new Exception("Migration " + m.getMigrationNumber() + " not found in table " + JFMigrationConstants.DB_VERSION_TABLE_NAME);
}
rs.close();
st.close();
}
for (Change c : m.migration.getChanges()) {
for (Pair<String, Object[]> commands : c.getSqlCommand(helper)) {
if (Data.class.isAssignableFrom(c.getClass())) {
st = new LoggablePreparedStatement(conn, commands.getA());
if (commands.getB() != null) {
for (int i = 0; i < commands.getB().length; i++) {
st.setObject(i + 1, commands.getB()[i]);
}
}
log.info("Executing{}{}", System.lineSeparator(), st);
if (out == null) {
st.execute();
} else {
out.write(st.toString().trim());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
} else {
st = new LoggablePreparedStatement(conn, commands.getA());
log.info("Executing{}{}", System.lineSeparator(), st);
if (out == null) {
st.execute();
} else {
out.write(st.toString().trim());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
}
}
}
String migrationVersionCommand = helper.getDeleteVersionCommand();
st = new LoggablePreparedStatement(conn, migrationVersionCommand);
st.setLong(1, m.getMigrationNumber());
log.info("Executing{}{}", System.lineSeparator(), st);
if (out == null) {
st.execute();
} else {
out.write(st.toString().trim());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
if (out != null) {
if (scriptVersionCheck != null) {
out.write(scriptVersionCheck[1]);
out.write(System.lineSeparator());
}
out.write("
out.write(System.lineSeparator());
out.write(System.lineSeparator());
out.write(System.lineSeparator());
}
log.debug("Applied migration {}", m.getClass().getSimpleName());
} else {
if(!m.executeForDialect(dialect)) {
log.info("Skipping migration {} because DB dialect {} is explicitly skipped", m.getMigrationNumber(), dialect);
} else if (m.getMigrationNumber() > dbVersion) {
log.debug("Skipped migration {}({}) because out of range (db version: {})", m.getMigrationName(), m.getMigrationNumber(), dbVersion, targetMigration);
} else {
log.debug("Skipped migration {}({}) because out of range (target version: {})", m.getMigrationName(), m.getMigrationNumber(), targetMigration);
}
}
}
}
if (out == null) {
conn.commit();
}
} catch (Exception e) {
if (conn != null) {
try {
conn.rollback();
log.error("Connection rolled back");
} catch (Exception ex) {
log.error("Error rolling back connection", ex);
}
}
log.error("Error executing query", e);
throw e;
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (Exception ex) {
log.error(ex);
}
}
}
/**
* Retrieves the current schema, if set
* @return
*/
public String getSchema() {
return schema;
}
/**
* Sets the database schema to use (if applicable)
* @param schema
*/
public void setSchema(String schema) {
this.schema = schema;
}
} |
package org.mwc.cmap.plotViewer.editors;
import java.awt.Color;
import java.beans.*;
import java.util.*;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.dnd.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.*;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.operations.*;
import org.eclipse.ui.part.EditorPart;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.DataTypes.Narrative.NarrativeProvider;
import org.mwc.cmap.core.DataTypes.Temporal.*;
import org.mwc.cmap.core.interfaces.*;
import org.mwc.cmap.core.property_support.*;
import org.mwc.cmap.core.ui_support.LineItem;
import org.mwc.cmap.plotViewer.PlotViewerPlugin;
import org.mwc.cmap.plotViewer.actions.ExportWMF;
import org.mwc.cmap.plotViewer.editors.chart.*;
import org.mwc.cmap.plotViewer.editors.chart.SWTChart.PlotMouseDragger;
import MWC.Algorithms.PlainProjection;
import MWC.GUI.*;
import MWC.GUI.Editable.EditorType;
import MWC.GUI.Layers.DataListener;
import MWC.GUI.Tools.Chart.DblClickEdit;
import MWC.GenericData.*;
public abstract class CorePlotEditor extends EditorPart implements IResourceProvider,
IControllableViewport, ISelectionProvider, IPlotGUI
{
// member data
/**
* the chart we store/manager
*/
protected SWTChart _myChart = null;
/**
* we may learn the background color of the canvas before it has loaded.
* temporarily store the color here, and set the background color when we load
* the canvas
*/
private Color _pendingCanvasBackgroundColor;
/**
* the graphic data we know about
*/
final protected Layers _myLayers;
/**
* handle narrative management
*/
protected NarrativeProvider _theNarrativeProvider;
/**
* an object to look after all of the time bits
*/
protected TimeManager _timeManager;
/** and how we view the time
*
*/
protected TimeControlPreferences _timePreferences;
/**
* the object which listens to time-change events. we remember it so that it
* can be deleted when we close
*/
protected PropertyChangeListener _timeListener;
/**
* store a pending projection. we do this because sometimes we may learn about
* the projection before we create our child components, you see.
*/
protected PlainProjection _pendingProjection;
// drag-drop bits
protected DropTarget target;
Vector _selectionListeners;
ISelection _currentSelection;
/**
* keep track of whether the current plot is dirty...
*/
protected boolean _plotIsDirty = false;
/**
* whether to ignore firing dirty events for the time being (such as when
* we're loading data)
*/
protected boolean _ignoreDirtyCalls = false;
// dummy bits applicable for our dummy interface
Button _myButton;
Label _myLabel;
private CursorTracker _myTracker;
// constructor
public CorePlotEditor()
{
super();
_myLayers = new Layers();
DataListener listenForMods = new DataListener()
{
public void dataModified(Layers theData, Layer changedLayer)
{
fireDirty();
}
public void dataExtended(Layers theData)
{
layersExtended();
fireDirty();
}
public void dataReformatted(Layers theData, Layer changedLayer)
{
fireDirty();
}
};
_myLayers.addDataExtendedListener(listenForMods);
_myLayers.addDataModifiedListener(listenForMods);
_myLayers.addDataReformattedListener(listenForMods);
// create the time manager. cool
_timeManager = new TimeManager();
// and how time is managed
_timePreferences = new TimeControlProperties();
// and listen for new times
_timeListener = new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent arg0)
{
// right, retrieve the time
HiResDate newDTG = (HiResDate) arg0.getNewValue();
timeChanged(newDTG);
// now make a note that the current DTG has changed
fireDirty();
}
};
_timeManager.addListener(_timeListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME);
}
public void dispose()
{
super.dispose();
// stop listening to the time manager
_timeManager.removeListener(_timeListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME);
// and clear the tracker
if (null != _myTracker)
_myTracker = null;
}
public void createPartControl(Composite parent)
{
// hey, create the chart
_myChart = createTheChart(parent);
// set the chart color, if we have one
if (_pendingCanvasBackgroundColor != null)
{
_myChart.getCanvas().setBackgroundColor(_pendingCanvasBackgroundColor);
// and promptly forget it
_pendingCanvasBackgroundColor = null;
}
// and update the projection, if we have one
if (_pendingProjection != null)
{
_myChart.getCanvas().setProjection(_pendingProjection);
_pendingProjection = null;
}
// and the drop support
configureFileDropSupport();
// and add our dbl click listener
// and add our dbl click listener
getChart().addCursorDblClickedListener(new DblClickEdit(_myLayers, null)
{
private static final long serialVersionUID = 1L;
protected void addEditor(Plottable res, EditorType e, Layer parentLayer)
{
selectPlottable(res, parentLayer);
}
protected void handleItemNotFound(PlainProjection projection)
{
putBackdropIntoProperties();
}
});
getSite().setSelectionProvider(this);
LineItem lineItem = CorePlugin.getStatusLine(this);
_myTracker = new CursorTracker(_myChart, lineItem);
// and over-ride the undo button
IAction undoAction = new UndoActionHandler(getEditorSite(), CorePlugin.CMAP_CONTEXT);
IAction redoAction = new RedoActionHandler(getEditorSite(), CorePlugin.CMAP_CONTEXT);
getEditorSite().getActionBars().setGlobalActionHandler(ActionFactory.UNDO.getId(),
undoAction);
getEditorSite().getActionBars().setGlobalActionHandler(ActionFactory.REDO.getId(),
redoAction);
// put in the plot-copy support
IAction _copyClipboardAction = new Action()
{
public void runWithEvent(Event event)
{
ExportWMF ew = new ExportWMF(true, false);
ew.run(null);
}
};
IActionBars actionBars= getEditorSite().getActionBars();
actionBars.setGlobalActionHandler(
ActionFactory.COPY.getId(),
_copyClipboardAction);
}
/** ok - let somebody else select an item on the plot. The initial reason for making this public
* was so that when a new item is created, we can select it on the plot. The plot then fires a
* 'selected' event, and the new item is shown in the properties window. Cool.
* @param target - the item to select
* @param parentLayer - the item's parent layer. Used to decide which layers to update.
*/
public void selectPlottable(Plottable target, Layer parentLayer)
{
CorePlugin.logError(Status.INFO, "Double-click processed, opening property editor for:" + target, null);
PlottableWrapper parentP = new PlottableWrapper(parentLayer, null, getChart()
.getLayers());
PlottableWrapper wrapped = new PlottableWrapper(target, parentP, getChart()
.getLayers());
ISelection selected = new StructuredSelection(wrapped);
fireSelectionChanged(selected);
}
/** place the chart in the properties window
*
*/
private final void putBackdropIntoProperties()
{
SWTCanvas can = (SWTCanvas) getChart().getCanvas();
EditableWrapper wrapped = new EditableWrapper(can,
getChart().getLayers());
ISelection sel = new StructuredSelection(wrapped);
fireSelectionChanged(sel);
}
/**
* create the chart we're after
*
* @param parent
* the parent object to stick it into
*/
protected SWTChart createTheChart(Composite parent)
{
SWTChart res = new SWTChart(_myLayers, parent){
private static final long serialVersionUID = 1L;
public void chartFireSelectionChanged(ISelection sel)
{
// TODO Auto-generated method stub
fireSelectionChanged(sel);
}};
return res;
}
/**
* sort out the file-drop target
*/
private void configureFileDropSupport()
{
int dropOperation = DND.DROP_COPY;
Transfer[] dropTypes = { FileTransfer.getInstance() };
target = new DropTarget(_myChart.getCanvasControl(), dropOperation);
target.setTransfer(dropTypes);
target.addDropListener(new DropTargetListener()
{
public void dragEnter(DropTargetEvent event)
{
if (FileTransfer.getInstance().isSupportedType(event.currentDataType))
{
if (event.detail != DND.DROP_COPY)
{
event.detail = DND.DROP_COPY;
}
}
}
public void dragLeave(DropTargetEvent event)
{
}
public void dragOperationChanged(DropTargetEvent event)
{
}
public void dragOver(DropTargetEvent event)
{
}
public void dropAccept(DropTargetEvent event)
{
}
public void drop(DropTargetEvent event)
{
String[] fileNames = null;
if (FileTransfer.getInstance().isSupportedType(event.currentDataType))
{
fileNames = (String[]) event.data;
}
if (fileNames != null)
{
filesDropped(fileNames);
}
}
});
}
/**
* process the files dropped onto this panel
*
* @param fileNames
* list of filenames
*/
protected void filesDropped(String[] fileNames)
{
System.out.println("Files dropped");
}
public void setFocus()
{
// just put some kind of blank object into the properties window
// putBackdropIntoProperties();
// ok, set the drag mode to whatever our common "mode" is.
// - start off by getting the current mode
PlotMouseDragger curMode = PlotViewerPlugin.getCurrentMode();
// has one been set?
if(curMode != null)
{
// yup, better observe it then
_myChart.setDragMode(curMode);
}
}
public Object getAdapter(Class adapter)
{
Object res = null;
// so, is he looking for the layers?
if (adapter == Layers.class)
{
if (_myLayers != null)
res = _myLayers;
}
else if (adapter == NarrativeProvider.class)
{
res = _theNarrativeProvider;
}
else if (adapter == TimeProvider.class)
{
res = _timeManager;
}
else if (adapter == ISelectionProvider.class)
{
res = this;
}
else if (adapter == IControllableViewport.class)
{
res = this;
}
else if (adapter == ControllableTime.class)
{
res = _timeManager;
}
else if (adapter == TimeControlPreferences.class)
{
res = _timePreferences;
}
else if (adapter == CanvasType.class)
{
res = _myChart.getCanvas();
}
else if (adapter == IGotoMarker.class)
{
return new IGotoMarker()
{
public void gotoMarker(IMarker marker)
{
String lineNum = marker.getAttribute(IMarker.LINE_NUMBER, "na");
if (lineNum != "na")
{
// right, convert to DTG
HiResDate tNow = new HiResDate(0, Long.parseLong(lineNum));
_timeManager.setTime(this, tNow, true);
}
}
};
}
return res;
}
protected void timeChanged(HiResDate newDTG)
{
}
/**
* method called when a helper object has completed a plot-load operation
*
* @param source
*/
abstract public void loadingComplete(Object source);
/**
* return the file representing where this plot is stored
*
* @return the file location
*/
public IResource getResource()
{
// have we been saved yet?
return null;
}
public WorldArea getViewport()
{
return getChart().getCanvas().getProjection().getDataArea();
}
public void setViewport(WorldArea target)
{
getChart().getCanvas().getProjection().setDataArea(target);
}
public PlainProjection getProjection()
{
return getChart().getCanvas().getProjection();
}
public void setProjection(PlainProjection proj)
{
// do we have a chart yet?
if (_myChart == null)
{
// nope, better remember it
_pendingProjection = proj;
}
else
{
// yes, just update it.
_myChart.getCanvas().setProjection(proj);
}
}
public SWTChart getChart()
{
return _myChart;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void addSelectionChangedListener(ISelectionChangedListener listener)
{
if (_selectionListeners == null)
_selectionListeners = new Vector(0, 1);
// see if we don't already contain it..
if (!_selectionListeners.contains(listener))
_selectionListeners.add(listener);
}
/**
* Returns the ActionbarContributor for the Editor.
*
* @return the ActionbarContributor for the Editor.
*/
public SubActionBars2 getActionbar()
{
return (SubActionBars2) getEditorSite().getActionBars();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionProvider#getSelection()
*/
public ISelection getSelection()
{
return _currentSelection;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener)
{
_selectionListeners.remove(listener);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection)
*/
public void setSelection(ISelection selection)
{
// TODO Auto-generated method stub
_currentSelection = selection;
}
public void fireSelectionChanged(ISelection sel)
{
// just double-check that we're not already processing this
if (sel != _currentSelection)
{
_currentSelection = sel;
if (_selectionListeners != null)
{
SelectionChangedEvent sEvent = new SelectionChangedEvent(this, sel);
for (Iterator stepper = _selectionListeners.iterator(); stepper.hasNext();)
{
ISelectionChangedListener thisL = (ISelectionChangedListener) stepper.next();
if (thisL != null)
{
thisL.selectionChanged(sEvent);
}
}
}
}
}
/**
* hmm, are we dirty?
*
* @return
*/
public boolean isDirty()
{
return _plotIsDirty;
}
/**
* make a note that the data is now dirty, and needs saving.
*/
protected void fireDirty()
{
if (!_ignoreDirtyCalls)
{
_plotIsDirty = true;
Display.getDefault().asyncExec(new Runnable()
{
public void run()
{
firePropertyChange(PROP_DIRTY);
}
});
}
}
/**
* new data has been added - have a look at the times
*/
private void layersExtended()
{
}
/**
* start ignoring dirty calls, since we're loading the initial data (for
* instance)
*/
protected void startIgnoringDirtyCalls()
{
_ignoreDirtyCalls = true;
}
/**
* start ignoring dirty calls, since we're loading the initial data (for
* instance)
*/
protected void stopIgnoringDirtyCalls()
{
_ignoreDirtyCalls = false;
}
/**
* @return
*/
public Color getBackgroundColor()
{
return _myChart.getCanvas().getBackgroundColor();
}
/**
* @param theColor
*/
public void setBackgroundColor(Color theColor)
{
if (_myChart == null)
_pendingCanvasBackgroundColor = theColor;
else
_myChart.getCanvas().setBackgroundColor(theColor);
}
public void update()
{
getChart().getCanvas().updateMe();
}
/** get the chart to fit to window
*
*/
public void rescale()
{
_myChart.rescale();
}
} |
import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.util.Formatter;
import java.util.Locale;
public class VisualClient {
Socket socket;
OutputStream outputStream;
InputStream inputStream;
BufferedReader reader;
final String DEFAULT_HOST = "127.0.0.1";
final int DEFAULT_PORT = 13579;//13579
public VisualClient() {
Locale.setDefault(new Locale("en", "US"));
try {
socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
} catch (IOException e) {
e.printStackTrace();
}
}
public VisualClient(String host, int port) {
Locale.setDefault(new Locale("en", "US"));
try {
socket = new Socket(host, port);
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendCommand(String command) {
try {
outputStream.write((command + System.lineSeparator()).getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* start queueing commands to be displayed either before main drawing
*/
public void beginPre() {
sendCommand("begin pre");
}
/**
* start queueing commands to be displayed either after main drawing
*/
public void beginPost() {
sendCommand("begin post");
}
/**
* start queueing commands to be displayed on the absolute coordinates
*/
public void beginAbs() {
sendCommand("begin abs");
}
/**
* mark either "pre" queue of commands as ready to be displayed
*/
public void endPre() {
sendCommand("end pre");
}
/**
* mark either "post" queue of commands as ready to be displayed
*/
public void endPost() {
sendCommand("end post");
}
/**
* mark either "abs" queue of commands as ready to be displayed
*/
public void endAbs() {
sendCommand("end abs");
}
/**
* draw a circle at (x, y) with radius r and color color
*/
public void circle(double x, double y, double r, Color color) {
Formatter f = new Formatter();
sendCommand(f.format("circle %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f", x, y, r, (float) color.getRed()/255, (float) color.getGreen()/255, (float) color.getBlue()/255).toString());
}
/**
* draw a filled circle at (x, y) with radius r and color color
*/
public void fillCircle(double x, double y, double r, Color color) {
Formatter f = new Formatter();
sendCommand(f.format("fill_circle %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f", x, y, r, (float) color.getRed()/255, (float) color.getGreen()/255, (float) color.getBlue()/255).toString());
}
/**
* draw a rect with corners at (x, y) to (x, y) with color color
*/
public void rect(double x1, double y1, double x2, double y2, Color color) {
Formatter f = new Formatter();
sendCommand(f.format("rect %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f", x1, y1, x2, y2, (float) color.getRed()/255, (float) color.getGreen()/255, (float) color.getBlue()/255).toString());
}
/**
* draw a filled rect with corners at (x1, y1) to (x2, y2) with color color
*/
public void fillRect(double x1, double y1, double x2, double y2, Color color) {
Formatter f = new Formatter();
sendCommand(f.format("fill_rect %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f", x1, y1, x2, y2, (float) color.getRed()/255, (float) color.getGreen()/255, (float) color.getBlue()/255).toString());
}
/**
* draw a arc with center at (centerX, centerY), radius radius and angle arcAngle, started from startAngle with color color, angles in radians
*/
public void arc(double centerX, double centerY, double radius, double startAngle, double arcAngle, Color color) {
Formatter f = new Formatter();
sendCommand(f.format("arc %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f", centerX, centerY, radius, startAngle, arcAngle, (float) color.getRed()/255, (float) color.getGreen()/255, (float) color.getBlue()/255).toString());
}
/**
* draw a filled arc with center at (centerX, centerY), radius radius and angle arcAngle, started from startAngle with color color, angles in radians
*/
public void fillArc(double centerX, double centerY, double radius, double startAngle, double arcAngle, Color color) {
Formatter f = new Formatter();
sendCommand(f.format("fill_arc %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f", centerX, centerY, radius, startAngle, arcAngle, (float) color.getRed()/255, (float) color.getGreen()/255, (float) color.getBlue()/255).toString());
}
/**
* draw a line from (x1, y1) to (x2, y2) with color color
*/
public void line(double x1, double y1, double x2, double y2, Color color) {
Formatter f = new Formatter();
sendCommand(f.format("line %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f", x1, y1, x2, y2, (float) color.getRed()/255, (float) color.getGreen()/255, (float) color.getBlue()/255).toString());
}
/**
* show msg at coordinates (x, y) with color color
*/
public void text(double x, double y, String msg, Color color) {
Formatter f = new Formatter();
sendCommand(f.format("text %1.1f %1.1f %s %1.1f %1.1f %1.1f", x, y, msg, (float) color.getRed()/255, (float) color.getGreen()/255, (float) color.getBlue()/255).toString());
}
public void stop() {
try {
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* synchronizes local-runner with the render commands from bot, call AFTER you have sent
* render commands for tick=tickIndex
*/
public void sync(int tickIndex) {
try {
while(true) {
String line = reader.readLine();
if (line.startsWith("sync ")) {
int tick = Integer.parseInt(line.substring(5).trim());
sendCommand("ack");
if (tick >= tickIndex) {
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} |
// $RCSfile$
// @author $Author$
// @version $Revision$
// $Log$
// Revision 1.36 2006-08-11 08:24:31 Ian.Mayo
// Don't let repaints stack up
// Revision 1.35 2006/08/08 13:54:59 Ian.Mayo
// Remove dependency on Debrief classes
// Revision 1.34 2006/07/28 10:16:22 Ian.Mayo
// Reset normal cursor on mouse up
// Revision 1.33 2006/05/24 14:50:10 Ian.Mayo
// Always redraw the whole plot if in relative mode
// Revision 1.32 2006/04/26 12:39:46 Ian.Mayo
// Remove d-lines
// Revision 1.31 2006/04/21 08:13:51 Ian.Mayo
// keep a cached copy of the image - to reduce replotting time
// Revision 1.30 2006/04/11 08:10:42 Ian.Mayo
// Include support for mouse-move event (in addition to mouse-drag).
// Revision 1.29 2006/04/06 13:01:05 Ian.Mayo
// Ditch performance timers
// Revision 1.28 2006/04/05 08:15:42 Ian.Mayo
// Refactoring, improvements
// Revision 1.27 2006/02/23 11:48:31 Ian.Mayo
// Become selection provider
// Revision 1.26 2006/02/08 09:32:22 Ian.Mayo
// Eclipse tidying
// Revision 1.25 2006/01/20 14:10:29 Ian.Mayo
// Tidier plotting of background (ready for metafile plotting)
// Revision 1.24 2006/01/13 15:22:25 Ian.Mayo
// Minor refactoring, plus make sure we get the layers in sorted order (background & buffered before tracks)
// Revision 1.23 2006/01/03 14:03:33 Ian.Mayo
// Better right-click support
// Revision 1.22 2005/12/12 09:07:14 Ian.Mayo
// Minor tidying to comments
// Revision 1.21 2005/12/09 14:54:38 Ian.Mayo
// Add right-click property editing
// Revision 1.20 2005/09/29 15:29:46 Ian.Mayo
// Provide initial drag-mode (zoom)
// Revision 1.19 2005/09/16 10:11:37 Ian.Mayo
// Reflect changed mouse event signature
// Revision 1.18 2005/09/13 15:43:25 Ian.Mayo
// Try to get dragging modes working
// Revision 1.17 2005/09/13 13:46:25 Ian.Mayo
// Better drag mode support
// Revision 1.16 2005/08/31 15:03:38 Ian.Mayo
// Minor tidying
// Revision 1.15 2005/07/01 08:17:46 Ian.Mayo
// refactor, so we can override layer painting
// Revision 1.14 2005/06/14 15:21:03 Ian.Mayo
// fire update after zoom
// Revision 1.13 2005/06/14 09:49:29 Ian.Mayo
// Eclipse-triggered tidying (unused variables)
// Revision 1.12 2005/06/09 14:51:51 Ian.Mayo
// Implement SWT plotting
// Revision 1.11 2005/06/07 15:29:57 Ian.Mayo
// Add panel to show current cursor position
// Revision 1.10 2005/06/07 10:50:02 Ian.Mayo
// Ignore right-clicks for drag,mouse-up
// Revision 1.9 2005/05/26 14:04:51 Ian.Mayo
// Tidy up double-buffering
// Revision 1.8 2005/05/26 07:34:47 Ian.Mayo
// Minor tidying
// Revision 1.7 2005/05/25 15:31:55 Ian.Mayo
// Get double-buffering going
// Revision 1.6 2005/05/25 13:24:42 Ian.Mayo
// Tidy background painting
// Revision 1.5 2005/05/24 14:09:49 Ian.Mayo
// Sort out mouse-clicked events
// Revision 1.4 2005/05/24 13:26:43 Ian.Mayo
// Start including double-click support.
// Revision 1.3 2005/05/24 07:39:54 Ian.Mayo
// Start mouse support
// Revision 1.2 2005/05/20 15:34:45 Ian.Mayo
// Hey, practically working!
// Revision 1.1 2005/05/20 13:45:04 Ian.Mayo
// Start doing chart
package org.mwc.cmap.plotViewer.editors.chart;
import java.awt.*;
import java.awt.Color;
import java.util.*;
import org.eclipse.jface.action.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.widgets.Composite;
import org.mwc.cmap.core.property_support.*;
import org.mwc.cmap.plotViewer.actions.ZoomIn;
import MWC.GUI.*;
import MWC.GUI.Tools.Chart.*;
import MWC.GUI.Tools.Chart.RightClickEdit.ObjectConstruct;
import MWC.GenericData.*;
/**
* The Chart is a canvas placed in a panel. the majority of functionality is
* contained in the PlainChart parent class, only the raw comms is in this
* class. This is configured by setting the listeners to the chart/panel to be
* the listener functions defined in the parent.
*/
public abstract class SWTChart extends PlainChart implements ISelectionProvider
{
// member variables
private static final long serialVersionUID = 1L;
private SWTCanvas _theCanvas;
/**
* our list of layered images.
*/
protected HashMap _myLayers = new HashMap();
/**
* the data area we last plotted (so that we know when a full layered repaint
* is needed).
*/
protected WorldArea _lastDataArea = null;
private final int JITTER = 3;
/**
* track drag operations
*/
private Point _startPoint = null;
/**
* the last point dragged over
*/
private Point _draggedPoint = null;
private PlotMouseDragger _myDragMode;
/**
* keep a cached copy of the image - to reduce replotting time
*/
protected ImageData _myImageTemplate = null;
/** keep track of if we're repainting, don't stack them up
*
*/
private boolean _repainting = false;
// constructor
/**
* constructor, providing us with the set of layers to plot.
*
* @param theLayers
* the data to plot
*/
public SWTChart(final Layers theLayers, Composite parent)
{
super(theLayers);
_theCanvas = createCanvas(parent);
_theCanvas.setProjection(new MWC.Algorithms.Projections.FlatProjection());
// sort out the area of coverage of the plot
if (theLayers != null)
{
WorldArea area = theLayers.getBounds();
_theCanvas.getProjection().setDataArea(area);
}
// add us as a painter to the canvas
_theCanvas.addPainter(this);
// catch any resize events
_theCanvas.addControlListener(new ControlAdapter()
{
public void controlResized(final ControlEvent e)
{
canvasResized();
}
});
Dimension dim = _theCanvas.getSize();
if (dim != null)
_theCanvas.getProjection().setScreenArea(dim);
_theCanvas.addMouseMoveListener(new MouseMoveListener()
{
public void mouseMove(MouseEvent e)
{
doMouseMove(e);
}
});
_theCanvas.addMouseListener(new MouseListener()
{
public void mouseDoubleClick(MouseEvent e)
{
doMouseDoubleClick(e);
}
public void mouseDown(MouseEvent e)
{
doMouseDown(e);
}
public void mouseUp(MouseEvent e)
{
doMouseUp(e);
}
});
// create the tooltip handler
_theCanvas.setTooltipHandler(new MWC.GUI.Canvas.BasicTooltipHandler(theLayers));
// give us an initial zoom mode
_myDragMode = new ZoomIn.ZoomInMode();
}
// member functions
public void canvasResized()
{
// and clear out our buffered layers (they all need to be repainted anyway)
_myLayers.clear();
// and ditch our image template (since it's size related)
_myImageTemplate = null;
// now we've cleared the layers, call the parent resize method (which causes
// a repaint
// of the layers)
super.canvasResized();
}
/**
* over-rideable member function which allows us to over-ride the canvas which
* gets used.
*
* @return the Canvas to use
*/
public SWTCanvas createCanvas(Composite parent)
{
return new CustomisedSWTCanvas(parent)
{
private static final long serialVersionUID = 1L;
public void parentFireSelectionChanged(ISelection selected)
{
chartFireSelectionChanged(selected);
}
public void doSupplementalRightClickProcessing(MenuManager menuManager, Plottable selected, Layer theParentLayer)
{
}
};
}
public abstract void chartFireSelectionChanged(ISelection sel);
/**
* get the size of the canvas.
*
* @return the dimensions of the canvas
*/
public final java.awt.Dimension getScreenSize()
{
Dimension dim = _theCanvas.getSize();
// get the current size of the canvas
return dim;
}
public final Component getPanel()
{
System.err.println("NOT RETURNING PANEL");
return null;
// return _theCanvas;
}
public final Control getCanvasControl()
{
return _theCanvas.getCanvas();
}
public final SWTCanvas getSWTCanvas()
{
return _theCanvas;
}
public final void update()
{
// just check we have some data
// clear out the layers object
_myLayers.clear();
// and start the update
_theCanvas.updateMe();
}
public final void update(final Layer changedLayer)
{
if (changedLayer == null)
{
update();
}
else
{
// just delete that layer
_myLayers.remove(changedLayer);
// chuck in a GC, to clear the old image allocation
System.gc();
// and trigger update
_theCanvas.updateMe();
}
}
/**
* over-ride the parent's version of paint, so that we can try to do it by
* layers.
*/
public void paintMe(final CanvasType dest)
{
// just double-check we have some layers (if we're part of an overview
// chart, we may not have...)
if (_theLayers == null)
return;
if(_repainting)
{
return;
}
else
{
_repainting = true;
}
try{
// check that we have a valid canvas (that the sizes are set)
final java.awt.Dimension sArea = dest.getProjection().getScreenArea();
if (sArea != null)
{
if (sArea.width > 0)
{
// hey, we've plotted at least once, has the data area changed?
if (_lastDataArea != _theCanvas.getProjection().getDataArea())
{
// remember the data area for next time
_lastDataArea = _theCanvas.getProjection().getDataArea();
// clear out all of the layers we are using
_myLayers.clear();
}
// we also clear the layers if we're in relative projection mode
if (_theCanvas.getProjection().getRelativePlot())
{
_myLayers.clear();
}
int canvasHeight = _theCanvas.getSize().height;
int canvasWidth = _theCanvas.getSize().width;
paintBackground(dest);
// ok, pass through the layers, repainting any which need it
Enumeration numer = _theLayers.sortedElements();
while (numer.hasMoreElements())
{
final Layer thisLayer = (Layer) numer.nextElement();
boolean isAlreadyPlotted = false;
// just check if this layer is visible
if (thisLayer.getVisible())
{
// System.out.println("painting:" + thisLayer.getName());
if (doubleBufferPlot())
{
// check we're plotting to a SwingCanvas, because we don't
// double-buffer anything else
if (dest instanceof SWTCanvas)
{
// does this layer want to be double-buffered?
if (thisLayer instanceof BaseLayer)
{
// just check if there is a property which over-rides the
// double-buffering
final BaseLayer bl = (BaseLayer) thisLayer;
if (bl.isBuffered())
{
isAlreadyPlotted = true;
// do our double-buffering bit
// do we have a layer for this object
org.eclipse.swt.graphics.Image image = (org.eclipse.swt.graphics.Image) _myLayers
.get(thisLayer);
if (image == null)
{
// ok - do we have an image template?
if (_myImageTemplate == null)
{
// nope, better create one
Image template = new Image(Display.getCurrent(), canvasWidth,
canvasHeight);
// and remember it.
_myImageTemplate = template.getImageData();
}
// ok, and now the SWT image
image = createSWTImage(_myImageTemplate);
GC newGC = new GC(image);
// wrap the GC into something we know how to plot to.
SWTCanvasAdapter ca = new SWTCanvasAdapter(dest.getProjection());
ca.setScreenSize(_theCanvas.getProjection().getScreenArea());
// and store the GC
ca.startDraw(newGC);
// ok, paint the layer into this canvas
thisLayer.paint(ca);
// done.
ca.endDraw(null);
// store this image in our list, indexed by the layer
// object itself
_myLayers.put(thisLayer, image);
}
// have we ended up with an image to paint?
if (image != null)
{
// get the graphics to paint to
SWTCanvas canv = (SWTCanvas) dest;
// lastly add this image to our Graphics object
canv.drawSWTImage(image, 0, 0, canvasWidth, canvasHeight);
}
}
}
} // whether we were plotting to a SwingCanvas (which may be
// double-buffered
} // whther we are happy to do double-buffering
// did we manage to paint it
if (!isAlreadyPlotted)
{
paintThisLayer(thisLayer, dest);
isAlreadyPlotted = true;
}
}
}
}
}
}
finally
{
_repainting = false;
}
}
/**
* Convenience method added, to allow child classes to override how we plot
* non-background layers. This was originally inserted to let us support snail
* trails
*
* @param thisLayer
* @param dest
*/
protected void paintThisLayer(final Layer thisLayer, CanvasType dest)
{
// draw into it
thisLayer.paint(dest);
}
/**
* create the transparent image we need to for collating multiple layers into
* an image
*
* @param canvasHeight
* @param canvasWidth
* @return
*/
protected org.eclipse.swt.graphics.Image createSWTImage(ImageData myImageTemplate)
{
_myImageTemplate.transparentPixel = _myImageTemplate.palette.getPixel(new RGB(255,
255, 255));
org.eclipse.swt.graphics.Image image = new org.eclipse.swt.graphics.Image(Display
.getCurrent(), _myImageTemplate);
return image;
}
/**
* property to indicate if we are happy to perform double-buffering. -
* override it to change the response
*/
protected boolean doubleBufferPlot()
{
return true;
}
/**
* paint the solid background.
*
* @param dest
* where we're painting to
*/
protected void paintBackground(final CanvasType dest)
{
// fill the background, to start with
final Dimension sz = _theCanvas.getSize();
// right, don't fill in the background if we're not painting to the screen
if (dest instanceof SWTCanvas)
{
final Color theCol = dest.getBackgroundColor();
dest.setBackgroundColor(theCol);
dest.fillRect(0, 0, sz.width, sz.height);
}
}
// methods for handling requests from our canvas
public final void rescale()
{
// do a rescale
_theCanvas.rescale();
}
public final void repaint()
{
// we were doing a repaint = now an updaet
_theCanvas.updateMe();
}
public final void repaintNow(final java.awt.Rectangle rect)
{
_theCanvas.redraw(rect.x, rect.y, rect.width, rect.height, true);
// _theCanvas.paintImmediately(rect);
}
public final CanvasType getCanvas()
{
return _theCanvas;
}
/**
* provide method to clear stored data.
*/
public void close()
{
// clear the layers
_myLayers.clear();
_myLayers = null;
// instruct the canvas to close
_theCanvas.close();
_theCanvas = null;
super.close();
}
public void doMouseMove(MouseEvent e)
{
java.awt.Point thisPoint = new java.awt.Point(e.x, e.y);
super.mouseMoved(thisPoint);
Point swtPoint = new Point(e.x, e.y);
// ok - pass the move event to our drag control (if it's interested...)
if (_myDragMode != null)
_myDragMode.doMouseMove(swtPoint, JITTER, super.getLayers(), _theCanvas);
if (_startPoint == null)
return;
// was this the right-hand button
if (e.button != 3)
{
_draggedPoint = new Point(e.x, e.y);
// ok - pass the drag to our drag control
if (_myDragMode != null)
_myDragMode.doMouseDrag(_draggedPoint, JITTER, super.getLayers(), _theCanvas);
}
}
protected void doMouseUp(MouseEvent e)
{
// was this the right-hand button
if (e.button != 3)
{
// ok. did we move at all?
if (_draggedPoint != null)
{
// yes, process the drag
if (_myDragMode != null)
{
_myDragMode.doMouseUp(new Point(e.x, e.y), e.stateMask);
// and restore the mouse mode cursor
_theCanvas.getCanvas().setCursor(_myDragMode.getNormalCursor());
}
}
else
{
// nope
// hey, it was just a click - process it
if (_theLeftClickListener != null)
{
// get the world location
java.awt.Point jPoint = new java.awt.Point(e.x, e.y);
WorldLocation loc = getCanvas().getProjection().toWorld(jPoint);
_theLeftClickListener.CursorClicked(jPoint, loc, getCanvas(), _theLayers);
}
}
}
_startPoint = null;
}
protected void doMouseDown(MouseEvent e)
{
// was this the right-hand button?
if (e.button != 3)
{
_startPoint = new Point(e.x, e.y);
_draggedPoint = null;
if (_myDragMode != null)
_myDragMode.mouseDown(_startPoint, _theCanvas, this);
}
}
protected void doMouseDoubleClick(MouseEvent e)
{
// was this the right-hand button
if (e.button == 3)
{
_theCanvas.rescale();
_theCanvas.updateMe();
}
else
{
// right, find out which one it was.
java.awt.Point pt = new java.awt.Point(e.x, e.y);
// and now the WorldLocation
WorldLocation loc = getCanvas().getProjection().toWorld(pt);
// and now see if we are near anything..
if (_theDblClickListeners.size() > 0)
{
// get the top one off the stack
ChartDoubleClickListener lc = (ChartDoubleClickListener) _theDblClickListeners
.lastElement();
lc.cursorDblClicked(this, loc, pt);
}
}
}
final public void setDragMode(final PlotMouseDragger newMode)
{
_myDragMode = newMode;
// and reset the start point so we know where we are.
_startPoint = null;
}
final public PlotMouseDragger getDragMode()
{
return _myDragMode;
}
/**
* embedded interface for classes that are able to handle drag events
*
* @author ian.mayo
*/
abstract public static class PlotMouseDragger
{
/**
* handle the mouse being dragged
*
* @param pt
* the new cursor location
* @param theCanvas
* TODO
*/
abstract public void doMouseDrag(final org.eclipse.swt.graphics.Point pt,
final int JITTER, final Layers theLayers, SWTCanvas theCanvas);
/**
* handle the mouse moving across the screen
*
* @param pt
* the new cursor location
* @param theCanvas
* TODO
*/
public void doMouseMove(final org.eclipse.swt.graphics.Point pt, final int JITTER,
final Layers theLayers, SWTCanvas theCanvas)
{
// provide a dummy implementation - most of our modes don't use this...
}
/**
* handle the mouse drag finishing
*
* @param keyState
* TODO
* @param pt
* the final cursor location
*/
abstract public void doMouseUp(org.eclipse.swt.graphics.Point point, int keyState);
/**
* handle the mouse drag starting
*
* @param canvas
* the control it's dragging over
* @param theChart
* TODO
* @param pt
* the first cursor location
*/
abstract public void mouseDown(org.eclipse.swt.graphics.Point point,
SWTCanvas canvas, PlainChart theChart);
/** ok, assign the cursor for when we're just hovering
*
* @return the new cursor to use, silly.
*/
public Cursor getNormalCursor()
{
// ok, return the 'normal' cursor
Cursor res = new Cursor(Display.getCurrent(), SWT.CURSOR_ARROW);
return res;
}
/** ok, assign the cursor for when we're just hovering
*
* @return the new cursor to use, silly.
*/
public Cursor getDownCursor()
{
// ok, return the 'normal' cursor
Cursor res = new Cursor(Display.getCurrent(), SWT.CURSOR_ARROW);
return res;
}
}
/**
* customised SWTCanvas class that supports our right-click editing
*
* @author ian.mayo
*/
public abstract class CustomisedSWTCanvas extends SWTCanvas
{
private static final long serialVersionUID = 1L;
public CustomisedSWTCanvas(Composite parent)
{
super(parent);
}
protected void fillContextMenu(MenuManager mmgr, Point scrPoint, WorldLocation loc)
{
// let the parent do it's stuff
super.fillContextMenu(mmgr, scrPoint, loc);
// ok, get a handle to our layers
Layers theData = getLayers();
double layerDist = -1;
// find the nearest editable item
ObjectConstruct vals = new ObjectConstruct();
int num = theData.size();
for (int i = 0; i < num; i++)
{
Layer thisL = theData.elementAt(i);
if (thisL.getVisible())
{
// find the nearest items, this method call will recursively pass down
// through
// the layers
RightClickEdit.findNearest(thisL, loc, vals);
if ((layerDist == -1) || (vals.distance < layerDist))
{
layerDist = vals.distance;
}
}
}
// ok, now retrieve the values produced by the range-finding algorithm
Plottable res = vals.object;
Layer theParent = vals.parent;
double dist = vals.distance;
Vector noPoints = vals.rangeIndependent;
// see if this is in our dbl-click range
if (HitTester.doesHit(new java.awt.Point(scrPoint.x, scrPoint.y), loc, dist,
getProjection()))
{
// do nothing, we're all happy
}
else
{
res = null;
}
// have we found something editable?
if (res != null)
{
// so get the editor
Editable.EditorType e = res.getInfo();
if (e != null)
{
RightClickSupport.getDropdownListFor(mmgr, new Editable[] { res },
new Layer[] { theParent }, new Layer[] { theParent }, getLayers(), false);
doSupplementalRightClickProcessing(mmgr, res, theParent);
}
}
else
{
// not found anything useful,
// so edit just the projection
RightClickSupport.getDropdownListFor(mmgr, new Editable[] { getProjection() },
null, null, getLayers(), true);
// also see if there are any other non-position-related items
if (noPoints != null)
{
// stick in a separator
mmgr.add(new Separator());
for (Iterator iter = noPoints.iterator(); iter.hasNext();)
{
final Plottable pl = (Plottable) iter.next();
RightClickSupport.getDropdownListFor(mmgr, new Editable[] { pl }, null, null,
getLayers(), true);
// ok, is it editable
if (pl.getInfo() != null)
{
// ok, also insert an "Edit..." item
Action editThis = new Action("Edit " + pl.getName() + " ...")
{
public void run()
{
// ok, wrap the editab
EditableWrapper pw = new EditableWrapper(pl, getLayers());
ISelection selected = new StructuredSelection(pw);
parentFireSelectionChanged(selected);
}
};
mmgr.add(editThis);
// hey, stick in another separator
mmgr.add(new Separator());
}
}
}
}
Action editProjection = new Action("Edit Projection")
{
public void run()
{
EditableWrapper wrapped = new EditableWrapper(getProjection(), getLayers());
ISelection selected = new StructuredSelection(wrapped);
parentFireSelectionChanged(selected);
}
};
mmgr.add(editProjection);
}
/**
* @param menuManager
* @param selected
* @param theParentLayer
*/
abstract public void doSupplementalRightClickProcessing(MenuManager menuManager, Plottable selected, Layer theParentLayer);
public abstract void parentFireSelectionChanged(ISelection selected);
}
public void addSelectionChangedListener(ISelectionChangedListener listener)
{
// TODO Auto-generated method stub
}
public ISelection getSelection()
{
// TODO Auto-generated method stub
return null;
}
public void removeSelectionChangedListener(ISelectionChangedListener listener)
{
// TODO Auto-generated method stub
}
public void setSelection(ISelection selection)
{
// TODO Auto-generated method stub
}
} |
package org.treeleafj.xdoc.resolver.javaparser.converter;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.treeleafj.xdoc.model.FieldInfo;
import org.treeleafj.xdoc.model.ObjectInfo;
import org.treeleafj.xdoc.utils.CommentUtils;
import org.treeleafj.xdoc.tag.DocTag;
import org.treeleafj.xdoc.tag.SeeTagImpl;
import org.treeleafj.xdoc.utils.ClassMapperUtils;
import java.beans.PropertyDescriptor;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SeeTagConverter extends DefaultJavaParserTagConverterImpl {
private Logger log = LoggerFactory.getLogger(SeeTagConverter.class);
@Override
public DocTag converter(String o) {
DocTag _docTag = super.converter(o);
String path = ClassMapperUtils.getPath((String) _docTag.getValues());
if (StringUtils.isBlank(path)) {
return null;
}
Class<?> returnClassz;
CompilationUnit cu;
try (FileInputStream in = new FileInputStream(path)) {
cu = JavaParser.parse(in);
if (cu.getTypes().size() <= 0) {
return null;
}
returnClassz = Class.forName(cu.getPackage().getName().toString() + "." + cu.getTypes().get(0).getName());
} catch (Exception e) {
log.error("java:{}", path, e);
return null;
}
String text = cu.getComment() != null ? CommentUtils.parseCommentText(cu.getComment().toString()) : "";
List<FieldInfo> fields = analysisFields(returnClassz, cu);
ObjectInfo objectInfo = new ObjectInfo();
objectInfo.setType(returnClassz);
objectInfo.setFieldInfos(fields);
objectInfo.setComment(text);
return new SeeTagImpl(_docTag.getName(), objectInfo);
}
private List<FieldInfo> analysisFields(Class classz, CompilationUnit compilationUnit) {
PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(classz);
final Map<String, String> commentMap = new HashMap();
new VoidVisitorAdapter<Void>() {
public void visit(FieldDeclaration n, Void arg) {
int i = 1;
String name = String.valueOf(n.getChildrenNodes().get(i));
while (String.valueOf(n.getChildrenNodes().get(i - 1)).startsWith("@")) {
i++;
if (i >= n.getChildrenNodes().size()) {
break;
}
name = String.valueOf(n.getChildrenNodes().get(i));
}
String comment = n.getComment() != null ? n.getComment().toString() : "";
commentMap.put(name, CommentUtils.parseCommentText(comment));
}
}.visit(compilationUnit, null);
List<FieldInfo> fields = new ArrayList<>();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyDescriptor.getName().equals("class")) {
continue;
}
FieldInfo field = new FieldInfo();
field.setType(propertyDescriptor.getPropertyType());
field.setSimpleTypeName(propertyDescriptor.getPropertyType().getSimpleName());
field.setName(propertyDescriptor.getName());
String comment = commentMap.get(propertyDescriptor.getName());
if (StringUtils.isBlank(comment)) {
field.setComment("");
field.setRequire(false);
fields.add(field);
} else {
boolean require = false;
if (comment.contains("|")) {
int endIndex = comment.lastIndexOf("|");
require = endIndex > 0;
if (require) {
comment = comment.substring(0, endIndex);
}
}
field.setComment(comment);
field.setRequire(require);
fields.add(field);
}
}
return fields;
}
} |
package info.bitrich.xchangestream.bitstamp;
import info.bitrich.xchangestream.core.StreamingExchange;
import info.bitrich.xchangestream.core.StreamingExchangeFactory;
import io.reactivex.disposables.Disposable;
import org.knowm.xchange.currency.CurrencyPair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BitstampManualExample {
private static final Logger LOG = LoggerFactory.getLogger(BitstampManualExample.class);
public static void main(String[] args) {
StreamingExchange exchange = StreamingExchangeFactory.INSTANCE.createExchange(BitstampStreamingExchange.class.getName());
exchange.connect().blockingAwait();
exchange.getStreamingMarketDataService().getOrderBook(CurrencyPair.BTC_USD).subscribe(orderBook -> {
LOG.info("First ask: {}", orderBook.getAsks().get(0));
LOG.info("First bid: {}", orderBook.getBids().get(0));
});
Disposable subscribe = exchange.getStreamingMarketDataService().getTrades(CurrencyPair.BTC_USD).subscribe(trade -> {
LOG.info("Trade {}", trade);
});
subscribe.dispose();
exchange.disconnect().subscribe(() -> LOG.info("Disconnected from the Exchange"));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} |
package org.xwiki.test.ui;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* Create specific {@link WebDriver} instances for various Browsers.
*
* @version $Id$
* @since 3.5M1
*/
public class WebDriverFactory
{
public WebDriver createWebDriver(String browserName)
{
WebDriver driver;
if (browserName.startsWith("*firefox")) {
// Native events are disabled by default for Firefox on Linux as it may cause tests which open many windows
// in parallel to be unreliable. However, native events work quite well otherwise and are essential for some
// of the new actions of the Advanced User Interaction. We need native events to be enable especially for
FirefoxProfile profile = new FirefoxProfile();
profile.setEnableNativeEvents(true);
driver = new FirefoxDriver(profile);
// Hide the Add-on bar (from the bottom of the window, with "WebDriver" written on the right) because it can
// prevent buttons or links from being clicked when they are beneath it and native events are used.
driver.switchTo().activeElement().sendKeys(Keys.chord(Keys.CONTROL, "/"));
} else if (browserName.startsWith("*iexplore")) {
driver = new InternetExplorerDriver();
} else if (browserName.startsWith("*chrome")) {
driver = new ChromeDriver();
} else if (browserName.startsWith("*phantomjs")) {
// Note 1: ATM PhantomJS needs to be installed first. In the future we should try to use
// Note 2: The phantomJS binary needs to be defined either in the PATH environment variable or through the
// system property: PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY
// Example: System.setProperty(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
// "/Users/vmassol/Desktop/phantomjs-1.9.0-macosx/bin/phantomjs");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setJavascriptEnabled(true);
capabilities.setCapability("takesScreenshot", true);
capabilities.setCapability("handlesAlerts", true);
driver = new PhantomJSDriver(capabilities);
} else {
throw new RuntimeException("Unsupported browser name [" + browserName + "]");
}
// Maximize the browser window by default so that the page has a standard layout. Individual tests can resize
// the browser window if they want to test how the page layout adapts to limited space. This reduces the
// probability of a test failure caused by an unexpected layout (nested scroll bars, floating menu over links
// and buttons and so on).
driver.manage().window().maximize();
return driver;
}
} |
package org.xwiki.rendering.block;
import org.xwiki.rendering.listener.Listener;
/**
* Represents a new line or line break (it's up to the Renderers to decide if it should be outputted as a new
* line or as a line break in the given syntax).
*
* @version $Id$
* @since 1.5M2
*/
public final class NewLineBlock extends AbstractBlock
{
/**
* The single instance for a new line block. There's no need for more than one instance since there's
* no state in the new line block.
*/
public static final NewLineBlock NEW_LINE_BLOCK = new NewLineBlock();
/**
* Private constructor to prevent instantiation. Instead use {@link #NEW_LINE_BLOCK}.
*/
private NewLineBlock()
{
// Voluntarily empty
}
/**
* {@inheritDoc}
* @see org.xwiki.rendering.block.AbstractBlock#traverse(org.xwiki.rendering.listener.Listener)
*/
public void traverse(Listener listener)
{
listener.onNewLine();
}
} |
package de.mat3.badintent.hooking.proxy.hooks;
import android.os.IBinder;
import android.os.Parcel;
import android.util.Log;
import java.io.FileDescriptor;
import java.io.IOException;
import de.mat3.badintent.hooking.BaseHook;
import de.mat3.badintent.hooking.proxy.ParcelAgent;
import de.mat3.badintent.hooking.proxy.RestAPI;
import de.robv.android.xposed.XposedHelpers;
/**
* Interrupts and stores (native invoking) parcel operations in a custom container.
*/
public class ParcelProxyHooks extends BaseHook {
protected RestAPI rest;
protected int port;
protected static final String TAG = "BadIntentParcelProxy";
public ParcelProxyHooks(BaseHook h, int port) throws IOException {
super(h);
this.port = port;
startBackgroundThreads();
}
protected void startBackgroundThreads() throws IOException {
Log.i(TAG, "starting internal WebServer on port: " + port);
rest = new RestAPI("0.0.0.0", port);
rest.start();
}
public void hookParcel() {
try {
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeString", String.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptString(parcel, (String) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeInt", int.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptInteger(parcel, (Integer) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeLong", long.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptLong(parcel, (Long) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeFloat", float.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptFloat(parcel, (Float) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeDouble", double.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptDouble(parcel, (Double) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeByteArray", byte[].class, int.class, int.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptByteArray(parcel, (byte[]) args[0], (int) args[1], (int) args[2]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeFileDescriptor", FileDescriptor.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptFileDescriptor(parcel, (FileDescriptor) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeStrongBinder", IBinder.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptStrongBinder(parcel, (IBinder) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeInterfaceToken", String.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptInterfaceToken(parcel, (String) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "setDataPosition", int.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptDataPosition(parcel, (int) args[0]);
}
});
try {
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeBlob", byte[].class, int.class, int.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptBlob(parcel, (byte[]) args[0], (int) args[1], (int) args[2]);
}
});
} catch (NoSuchMethodError e) { /* method does not exist in Android 4.4 */
Log.e(TAG, e.getLocalizedMessage());
}
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "setDataCapacity", int.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptDataCapacity(parcel, (int) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "setDataSize", int.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptDataSize(parcel, (int) args[0]);
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "pushAllowFds", boolean.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
try {
ParcelAgent.Instance.interruptPushAllowFds(parcel, (boolean) args[0]);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
});
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "appendFrom", Parcel.class, int.class, int.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptAppendFrom(parcel, (Parcel) args[0], (int) args[1], (int) args[2]);
}
});
try {
XposedHelpers.findAndHookMethod("android.os.Parcel", cloader, "writeRawFileDescriptor", FileDescriptor.class, new ParcelBaseWriteHook() {
@Override
protected void interruptWrite(Parcel parcel, Object[] args) {
ParcelAgent.Instance.interruptFileDescriptor(parcel, (FileDescriptor) args[0]);
}
});
} catch (NoSuchMethodError e) { /* obsolete method writeRawFileDescriptor */
Log.e(TAG, e.getLocalizedMessage());
}
} catch (RuntimeException e) {
Log.e(TAG, e.getLocalizedMessage());
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage());
}
}
} |
package ch.hevs.aislab.magpie.sample.activity;
import android.content.Context;
import android.test.AndroidTestCase;
import java.lang.reflect.Method;
import alice.tuprolog.Term;
import ch.hevs.aislab.magpie.agent.PrologAgentMind;
import ch.hevs.aislab.magpie.event.LogicTupleEvent;
import ch.hevs.aislab.magpie.sample.R;
public class AgentTest extends AndroidTestCase {
private final static String TAG = "AgentTest";
public void testPass(){
assertTrue(true);
}
/**
* Test if a LogicTuple is created correctly
*/
public void testLogicTuple() {
final String logicTuple = "blood_pressure(Sys,Dias)";
// Creation with multiple arguments
LogicTupleEvent bp1 = new LogicTupleEvent("blood_pressure", "Sys", "Dias");
String tupleFromArgs = bp1.toTuple();
assertEquals(logicTuple, tupleFromArgs);
// Creation from a tuProlog Term
Term t = Term.createTerm(logicTuple);
LogicTupleEvent bp2 = new LogicTupleEvent(t);
String tupleFromTerm = bp2.toTuple();
assertEquals(logicTuple, tupleFromTerm);
// Creation from String
LogicTupleEvent bp3 = new LogicTupleEvent(logicTuple);
String tupleFromString = bp3.toTuple();
assertEquals(logicTuple, tupleFromString);
}
public void testAgentMind() {
//getContext().getResources().;
PrologAgentMind mind = new PrologAgentMind(getContext(), R.raw.monitoring_rules);
// Events triggering a 'Brittle diabetes' alert
LogicTupleEvent ev1 = new LogicTupleEvent("glucose(3.5)"); // Term
LogicTupleEvent ev2 = new LogicTupleEvent("glucose", "9"); // Strings
ev1.setTimeStamp(1418646780000L); // Mon, 15 Dec 2014 13:33:00
ev2.setTimeStamp(1418660940000L); // Mon, 15 Dec 2014 17:29:00
// First event
mind.updatePerception(ev1);
mind.produceAction(1418646780000L);
// Second event
mind.updatePerception(ev2);
LogicTupleEvent alertOne = (LogicTupleEvent) mind.produceAction(1418660940000L);
// assertEquals(alertOne.toTuple(), "act(act(produce_alert(second,'Brittle diabetes')),1418660940001)");
// Events triggering a 'pre-hypertension' alert
LogicTupleEvent ev3 = new LogicTupleEvent("blood_pressure", "150", "84");
LogicTupleEvent ev4 = new LogicTupleEvent("blood_pressure", "134", "82");
ev3.setTimeStamp(1407778799000L); // Mon, 11 Aug 2014 19:39:59
ev4.setTimeStamp(1407900429000L); // Wed, 13 Aug 2014 05:27:09
// Event within the same time window happening after the alert
LogicTupleEvent ev5 = new LogicTupleEvent("blood_pressure(134,83)");
ev5.setTimeStamp(1407951178000L); // Wed, 13 Aug 2014 19:32:58
// Update the events
mind.updatePerception(ev3);
mind.produceAction(1407778799000L);
mind.updatePerception(ev4);
LogicTupleEvent alertTwo = (LogicTupleEvent) mind.produceAction(1407900429000L);
// Last event should not trigger an alert
mind.updatePerception(ev5);
mind.produceAction(1407951178000L);
assertEquals(alertTwo.toTuple(), "act(act(produce_alert(third,'pre-hypertension, consider lifestyle modification')),1407900429001)");
// Events triggering a 'DM treatment is not effective'
LogicTupleEvent ev6 = new LogicTupleEvent("glucose(10.5)");
LogicTupleEvent ev7 = new LogicTupleEvent("glucose(10.6)");
LogicTupleEvent ev8 = new LogicTupleEvent("weight", "87.2");
ev6.setTimeStamp(1407322080000L); // Wed, 06 Aug 2014 10:48:00
ev7.setTimeStamp(1407660840000L); // Sun, 10 Aug 2014 10:54:00
ev8.setTimeStamp(1408345255000L); // Mon, 18 Aug 2014 09:00:55
// Fake event within the same time window happening before the alert
LogicTupleEvent ev9 = new LogicTupleEvent("glucose", "10.2");
ev9.setTimeStamp(1439362800L); // Wed, 12 Aug 2015 09:00:00
mind.updatePerception(ev6);
mind.produceAction(1407322080000L);
mind.updatePerception(ev7);
mind.produceAction(1407660840000L);
mind.updatePerception(ev9);
mind.produceAction(1439362800L);
mind.updatePerception(ev8);
LogicTupleEvent alertThree = (LogicTupleEvent) mind.produceAction(1408345255000L);
assertEquals(alertThree.toTuple(), "act(act(produce_alert(first,'DM treatment is not efective')),1408345255001)");
}
/**
* Gets the context
* @return
*/
private Context getTestContext() {
try {
Method getTestContext = AndroidTestCase.class.getMethod("getTestContext");
return (Context) getTestContext.invoke(this);
} catch (final Exception ex) {
ex.printStackTrace();
return null;
}
}
} |
package com.futurice.cascade.systemtest;
import android.support.annotation.NonNull;
import android.util.Log;
import com.futurice.cascade.functional.ImmutableValue;
import com.futurice.cascade.i.CallOrigin;
import com.futurice.cascade.i.action.IAction;
import com.futurice.cascade.i.action.IActionOne;
import com.futurice.cascade.i.functional.IAltFuture;
import com.futurice.cascade.i.reactive.IReactiveTarget;
import com.futurice.cascade.reactive.ReactiveInteger;
import com.futurice.cascade.reactive.ReactiveValue;
import com.futurice.cascade.reactive.ui.AltArrayAdapter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import static com.futurice.cascade.Async.*;
/**
* Run a large number of individual tests of core library functions
* <p>
* Any method aboutMe that begins with "test" is called as a test. If no exceptions, it is considered passed
* <p>
* These are not isolated unit tests, but full system coherence and stress tests in a single app.
* <p>
* Since all tests are execute in the same executors, individual performance may not be measured in these tests.
*/
public class SystemTestRunner {
private static final String TAG = SystemTestRunner.class.getSimpleName();
private AtomicInteger total = new AtomicInteger(0);
private final ReactiveInteger finished;
private final ReactiveInteger failed;
private ReactiveValue<String> progress;
private ReactiveValue<String> status;
public final static ScheduledExecutorService testExecService = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "TestExecServiceThread"));
private AltArrayAdapter<String> listAdapter;
private final long startNanoTime = System.nanoTime();
private final ImmutableValue<String> origin;
public SystemTestRunner() {
finished = new ReactiveInteger(WORKER, "Finished", 0);
failed = new ReactiveInteger(WORKER, "Failed", 0);
progress = new ReactiveValue<>(WORKER, "Progress");
status = new ReactiveValue<>(WORKER, "Status");
origin = originAsync();
}
private IAltFuture<?, String> addResult(@NonNull String result) {
final IAltFuture<?, String> altFuture = listAdapter
.addAsync(result)
.fork();
return altFuture;
}
private void addFirstResults(String[] result) {
for (int i = result.length - 1;
i >= 0;
i
listAdapter
.insertAsync(result[i], 0)
.fork();
}
}
@CallOrigin
public void start(
@NonNull List<Class> classes,
@NonNull AltArrayAdapter<String> listAdapter,
@NonNull IReactiveTarget<String> statusTarget,
@NonNull IReactiveTarget<String> progressTarget) {
this.listAdapter = listAdapter;
Log.v(TAG, "START startMethod(classes)");
finished.subscribe((IAction) progress::fire);
failed.subscribe((IAction<Integer>) progress::fire);
progress.subscribe(() -> finished.get() + "/" + total.get() + " Err:" + failed.get())
.subscribe(progressTarget);
status.subscribe(statusTarget);
addResult(currentTime());
start(classes);
}
private String currentTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HHmm");
return simpleDateFormat.format(new Date());
}
private String elapsedTimeMicroseconds() {
return new Formatter().format("%,d", (System.nanoTime() - startNanoTime) / 1000) + " microseconds";
}
/**
* Start the tests on single own thread. Returns immediately
* <p>
* When finished the result is added to the beginning of the list model
*/
@CallOrigin
private void start(@NonNull List<Class> classes) {
Log.d(TAG, "Start processing list of test classes:");
for (Class cl : classes) {
Log.d(TAG, " " + cl.getName());
}
new Thread(() -> {
try {
// Find all test methods in all classes so we have a total count
Log.d(TAG, "START mapping");
status.set("Start mapping");
Map<Class, List<Method>> methodMap = new ConcurrentHashMap<>();
for (Class cl : classes) {
methodMap.put(cl, findMethodsInClass(cl));
}
// Run all test methods in all classes
for (Class cl : classes) {
status.set("Start " + cl.getSimpleName());
final IAltFuture<?, String> altFuture = addResult("+" + cl.getSimpleName());
boolean success = true;
for (Method method : methodMap.get(cl)) {
success &= startMethod(cl, method);
}
if (success) {
altFuture.then((IActionOne<String>) line -> listAdapter.removeAsync(line));
} else {
addResult("-" + cl.getSimpleName());
}
status.set("Error count: " + failed.get() + "/" + total.get());
}
} catch (Exception e) {
ee(this, origin, "Class mapping error", e);
} finally {
try {
final int fin = finished.get();
final int tot = total.get();
final int fail = failed.get();
if (fail == 0) {
addFirstResults(new String[]{
"",
"PASS: Passed " + fin + "/" + tot,
elapsedTimeMicroseconds(),
""});
} else {
addFirstResults(new String[]{
"",
"FAIL: " + fail + " test(s) failed. Passed " + fin + "/" + tot,
elapsedTimeMicroseconds(),
""});
}
status.set("Done");
} catch (Exception e) {
Log.e(TAG, "Problem starting SystemTestRunner", e);
}
}
}, "SystemTestsStartThread").start();
}
private List<Method> findMethodsInClass(@NonNull final Class cl) {
Log.v(TAG, "START findMethodsInClass methods of " + cl.getSimpleName());
//Get the methods
Method[] methods = cl.getDeclaredMethods();
ArrayList<Method> testMethods = new ArrayList<>(methods.length);
//Loop through the methods and findMethodsInClass the test methods
for (Method method : methods) {
if (method.isAnnotationPresent(Test.class)) {
testMethods.add(method);
}
}
total.addAndGet(testMethods.size());
if (cl.getSuperclass() != null) {
if (testMethods.size() == 0) {
// A ..Test class with no test... methods, try the parent also. See for example WorkerAspectTest
return findMethodsInClass(cl.getSuperclass());
}
} else {
throw new IllegalArgumentException("You passed in an test class with zero methods annotated with @Test in either the class or parent class: " + cl.getName());
}
return testMethods;
}
@CallOrigin
private boolean startMethod(@NonNull Class cl, @NonNull Method method) {
//Loop through the methods and call the test methods
String methodName = method.getName();
final long t = System.currentTimeMillis();
boolean success = false;
try {
method.invoke(cl.newInstance());
finished.incrementAndGet();
success = true;
final long t2 = System.currentTimeMillis() - t;
Log.v(TAG, "END invoke method " + method + " " + t2 + "ms");
addResult(cl.getSimpleName() + "." + methodName + " " + t2 + "ms");
} catch (IllegalAccessException e) {
failed.incrementAndGet();
addResult("Internal testing framework error: IllegalAccessException");
addResult(e.toString());
Log.e(TAG, "Can not invoke " + cl.getSimpleName() + "." + methodName, e);
addResult("");
} catch (InvocationTargetException e) {
failed.incrementAndGet();
String s = "TEST FAILURE: " + cl.getSimpleName() + "." + methodName;
Log.e(TAG, s, e.getCause());
addResult(s);
addResult(e.getCause().toString());
addResult("");
} catch (Throwable e) {
failed.incrementAndGet();
addResult("Internal testing framework error: InvocationTargetException");
addResult(e.toString());
Log.e(TAG, "Can not invoke " + cl.getSimpleName() + "." + methodName, e);
addResult("");
}
return success;
}
} |
package org.wordpress.android.analytics;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
import org.json.JSONException;
import org.json.JSONObject;
import org.wordpress.android.util.AppLog;
import java.util.EnumMap;
import java.util.Map;
public class AnalyticsTrackerMixpanel extends Tracker {
public static final String SESSION_COUNT = "sessionCount";
private MixpanelAPI mMixpanel;
private EnumMap<AnalyticsTracker.Stat, JSONObject> mAggregatedProperties;
private static final String MIXPANEL_PLATFORM = "platform";
private static final String MIXPANEL_SESSION_COUNT = "session_count";
private static final String DOTCOM_USER = "dotcom_user";
private static final String JETPACK_USER = "jetpack_user";
private static final String MIXPANEL_NUMBER_OF_BLOGS = "number_of_blogs";
private static final String VERSION_CODE = "version_code";
private static final String APP_LOCALE = "app_locale";
private static final String MIXPANEL_ANON_ID = "mixpanel_user_anon_id";
public AnalyticsTrackerMixpanel(Context context, String token) throws IllegalArgumentException {
super(context);
mAggregatedProperties = new EnumMap<>(AnalyticsTracker.Stat.class);
mMixpanel = MixpanelAPI.getInstance(context, token);
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static void showNotification(Context context, PendingIntent intent, int notificationIcon, CharSequence title,
CharSequence message) {
final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final Notification.Builder builder = new Notification.Builder(context).setSmallIcon(notificationIcon)
.setTicker(message).setWhen(System.currentTimeMillis()).setContentTitle(title).setContentText(message)
.setContentIntent(intent);
Notification notification;
notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(0, notification);
}
String getAnonIdPrefKey() {
return MIXPANEL_ANON_ID;
}
@Override
public void track(AnalyticsTracker.Stat stat) {
track(stat, null);
}
@Override
public void track(AnalyticsTracker.Stat stat, Map<String, ?> properties) {
AnalyticsTrackerMixpanelInstructionsForStat instructions = instructionsForStat(stat);
if (instructions == null) {
return;
}
trackMixpanelDataForInstructions(instructions, properties);
}
private void trackMixpanelDataForInstructions(AnalyticsTrackerMixpanelInstructionsForStat instructions,
Map<String, ?> properties) {
if (instructions.getDisableForSelfHosted()) {
return;
}
// Just a security check we're tracking the correct user
if (getWordPressComUserName() == null && getAnonID() == null) {
this.clearAllData();
generateNewAnonID();
mMixpanel.identify(getAnonID());
}
trackMixpanelEventForInstructions(instructions, properties);
trackMixpanelPropertiesForInstructions(instructions);
}
private void trackMixpanelPropertiesForInstructions(AnalyticsTrackerMixpanelInstructionsForStat instructions) {
if (instructions.getPeoplePropertyToIncrement() != null && !instructions.getPeoplePropertyToIncrement()
.isEmpty()) {
incrementPeopleProperty(instructions.getPeoplePropertyToIncrement());
}
if (instructions.getSuperPropertyToIncrement() != null && !instructions.getSuperPropertyToIncrement()
.isEmpty()) {
incrementSuperProperty(instructions.getSuperPropertyToIncrement());
}
if (instructions.getPropertyToIncrement() != null && !instructions.getPropertyToIncrement().isEmpty()) {
incrementProperty(instructions.getPropertyToIncrement(), instructions.getStatToAttachProperty());
}
if (instructions.getSuperPropertiesToFlag() != null && instructions.getSuperPropertiesToFlag().size() > 0) {
for (String superPropertyToFlag : instructions.getSuperPropertiesToFlag()) {
flagSuperProperty(superPropertyToFlag);
}
}
if (instructions.getPeoplePropertiesToAssign() != null
&& instructions.getPeoplePropertiesToAssign().size() > 0) {
for (Map.Entry<String, Object> entry: instructions.getPeoplePropertiesToAssign().entrySet()) {
setValueForPeopleProperty(entry.getKey(), entry.getValue());
}
}
}
private void setValueForPeopleProperty(String peopleProperty, Object value) {
try {
mMixpanel.getPeople().set(peopleProperty, value);
} catch (OutOfMemoryError outOfMemoryError) {
// ignore exception
}
}
private void trackMixpanelEventForInstructions(AnalyticsTrackerMixpanelInstructionsForStat instructions,
Map<String, ?> properties) {
String eventName = instructions.getMixpanelEventName();
if (eventName != null && !eventName.isEmpty()) {
JSONObject savedPropertiesForStat = propertiesForStat(instructions.getStat());
if (savedPropertiesForStat == null) {
savedPropertiesForStat = new JSONObject();
}
// Retrieve properties user has already passed in and combine them with the saved properties
if (properties != null) {
for (Object o : properties.entrySet()) {
Map.Entry pairs = (Map.Entry) o;
String key = (String) pairs.getKey();
try {
Object value = pairs.getValue();
savedPropertiesForStat.put(key, value);
} catch (JSONException e) {
AppLog.e(AppLog.T.UTILS, e);
}
}
}
mMixpanel.track(eventName, savedPropertiesForStat);
removePropertiesForStat(instructions.getStat());
}
}
@Override
public void registerPushNotificationToken(String regId) {
try {
mMixpanel.getPeople().setPushRegistrationId(regId);
} catch (OutOfMemoryError outOfMemoryError) {
// ignore exception
}
}
@Override
public void endSession() {
mAggregatedProperties.clear();
mMixpanel.flush();
}
@Override
public void flush() {
mMixpanel.flush();
}
@Override
public void refreshMetadata(boolean isUserConnected, boolean isWordPressComUser, boolean isJetpackUser,
int sessionCount, int numBlogs, int versionCode, String username, String email) {
// Register super properties
try {
JSONObject properties = new JSONObject();
properties.put(MIXPANEL_PLATFORM, "Android");
properties.put(MIXPANEL_SESSION_COUNT, sessionCount);
properties.put(DOTCOM_USER, isUserConnected);
properties.put(JETPACK_USER, isJetpackUser);
properties.put(MIXPANEL_NUMBER_OF_BLOGS, numBlogs);
properties.put(VERSION_CODE, versionCode);
properties.put(APP_LOCALE, mContext.getResources().getConfiguration().locale.toString());
mMixpanel.registerSuperProperties(properties);
} catch (JSONException e) {
AppLog.e(AppLog.T.UTILS, e);
}
if (isUserConnected && isWordPressComUser) {
setWordPressComUserName(username);
// Re-unify the user
if (getAnonID() != null) {
mMixpanel.alias(getWordPressComUserName(), getAnonID());
clearAnonID();
} else {
mMixpanel.identify(username);
}
} else {
// Not wpcom connected. Check if anonID is already present
setWordPressComUserName(null);
if (getAnonID() == null) {
generateNewAnonID();
}
mMixpanel.identify(getAnonID());
}
// Application opened and start.
if (isUserConnected) {
try {
String userID = getWordPressComUserName() != null ? getWordPressComUserName() : getAnonID();
if (userID == null) {
// This should not be an option here
return;
}
mMixpanel.getPeople().identify(userID);
JSONObject jsonObj = new JSONObject();
jsonObj.put("$username", userID);
if (email != null) {
jsonObj.put("$email", email);
}
jsonObj.put("$first_name", userID);
mMixpanel.getPeople().set(jsonObj);
} catch (JSONException e) {
AppLog.e(AppLog.T.UTILS, e);
} catch (OutOfMemoryError outOfMemoryError) {
// ignore exception
}
}
}
@Override
public void clearAllData() {
super.clearAllData();
mMixpanel.clearSuperProperties();
try {
mMixpanel.getPeople().clearPushRegistrationId();
} catch (OutOfMemoryError outOfMemoryError) {
// ignore exception
}
}
private AnalyticsTrackerMixpanelInstructionsForStat instructionsForStat(
AnalyticsTracker.Stat stat) {
AnalyticsTrackerMixpanelInstructionsForStat instructions;
switch (stat) {
case APPLICATION_OPENED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Application Opened");
instructions.setSuperPropertyToIncrement("Application Opened");
incrementSessionCount();
break;
case APPLICATION_CLOSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Application Closed");
break;
case APPLICATION_INSTALLED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Application Installed");
break;
case APPLICATION_UPGRADED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Application Upgraded");
break;
case READER_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_reader");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_reader");
break;
case READER_ARTICLE_COMMENTED_ON:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Commented on Article");
instructions.setSuperPropertyAndPeoplePropertyToIncrement(
"number_of_times_commented_on_reader_article");
instructions.setCurrentDateForPeopleProperty("last_time_commented_on_article");
break;
case READER_ARTICLE_LIKED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Liked Article");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_liked_article");
instructions.setCurrentDateForPeopleProperty("last_time_liked_reader_article");
break;
case READER_ARTICLE_OPENED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Opened Article");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_opened_article");
instructions.setCurrentDateForPeopleProperty("last_time_opened_reader_article");
break;
case READER_ARTICLE_UNLIKED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Unliked Article");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_unliked_article");
instructions.setCurrentDateForPeopleProperty("last_time_unliked_reader_article");
break;
case READER_BLOG_BLOCKED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Blocked Blog");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_blocked_a_blog");
instructions.setCurrentDateForPeopleProperty("last_time_blocked_a_blog");
break;
case READER_BLOG_FOLLOWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Followed Site");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_followed_site");
instructions.setCurrentDateForPeopleProperty("last_time_followed_site");
break;
case READER_BLOG_PREVIEWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Blog Preview");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_viewed_blog_preview");
instructions.setCurrentDateForPeopleProperty("last_time_viewed_blog_preview");
break;
case READER_BLOG_UNFOLLOWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Unfollowed Site");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_unfollowed_site");
instructions.setCurrentDateForPeopleProperty("last_time_unfollowed_site");
break;
case READER_DISCOVER_VIEWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Discover Content Viewed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement(
"number_of_times_discover_content_viewed");
instructions.setCurrentDateForPeopleProperty("last_time_discover_content_viewed");
break;
case READER_INFINITE_SCROLL:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Infinite Scroll");
instructions.setSuperPropertyAndPeoplePropertyToIncrement(
"number_of_times_reader_performed_infinite_scroll");
instructions.setCurrentDateForPeopleProperty("last_time_performed_reader_infinite_scroll");
break;
case READER_LIST_FOLLOWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Followed List");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_followed_list");
instructions.setCurrentDateForPeopleProperty("last_time_followed_list");
break;
case READER_LIST_LOADED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Loaded List");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_loaded_list");
instructions.setCurrentDateForPeopleProperty("last_time_loaded_list");
break;
case READER_LIST_PREVIEWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - List Preview");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_viewed_list_preview");
instructions.setCurrentDateForPeopleProperty("last_time_viewed_list_preview");
break;
case READER_LIST_UNFOLLOWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Unfollowed List");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_unfollowed_list");
instructions.setCurrentDateForPeopleProperty("last_time_unfollowed_list");
break;
case READER_TAG_FOLLOWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Followed Reader Tag");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_followed_reader_tag");
instructions.setCurrentDateForPeopleProperty("last_time_followed_reader_tag");
break;
case READER_TAG_LOADED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Loaded Tag");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_loaded_tag");
instructions.setCurrentDateForPeopleProperty("last_time_loaded_tag");
break;
case READER_TAG_PREVIEWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Tag Preview");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_viewed_tag_preview");
instructions.setCurrentDateForPeopleProperty("last_time_viewed_tag_preview");
break;
case READER_TAG_UNFOLLOWED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Reader - Unfollowed Reader Tag");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_unfollowed_reader_tag");
instructions.setCurrentDateForPeopleProperty("last_time_unfollowed_reader_tag");
break;
case EDITOR_CREATED_POST:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Created Post");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_created_post");
instructions.setCurrentDateForPeopleProperty("last_time_created_post_in_editor");
break;
case EDITOR_SAVED_DRAFT:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Saved Draft");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_saved_draft");
instructions.setCurrentDateForPeopleProperty("last_time_saved_draft");
break;
case EDITOR_DISCARDED_CHANGES:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Discarded Changes");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_discarded_changes");
instructions.setCurrentDateForPeopleProperty("last_time_discarded_changes");
break;
case EDITOR_EDITED_IMAGE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Edited Image");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_edited_image");
instructions.setCurrentDateForPeopleProperty("last_time_edited_image");
break;
case EDITOR_ENABLED_NEW_VERSION:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Enabled New Version");
instructions.addSuperPropertyToFlag("enabled_new_editor");
break;
case EDITOR_TOGGLED_ON:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Toggled New Editor On");
instructions.setPeoplePropertyToValue("enabled_new_editor", true);
break;
case EDITOR_TOGGLED_OFF:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Toggled New Editor Off");
instructions.setPeoplePropertyToValue("enabled_new_editor", false);
break;
case EDITOR_UPLOAD_MEDIA_FAILED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Upload Media Failed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_upload_media_failed");
instructions.setCurrentDateForPeopleProperty("last_time_editor_upload_media_failed");
break;
case EDITOR_UPLOAD_MEDIA_RETRIED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Retried Uploading Media");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_retried_uploading_media");
instructions.setCurrentDateForPeopleProperty("last_time_editor_retried_uploading_media");
break;
case EDITOR_CLOSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Closed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_closed");
break;
case EDITOR_ADDED_PHOTO_VIA_LOCAL_LIBRARY:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Added Photo via Local Library");
instructions.
setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_added_photo_via_local_library");
instructions.setCurrentDateForPeopleProperty("last_time_added_photo_via_local_library_to_post");
break;
case EDITOR_ADDED_PHOTO_VIA_WP_MEDIA_LIBRARY:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Added Photo via WP Media Library");
instructions.setSuperPropertyAndPeoplePropertyToIncrement(
"number_of_times_added_photo_via_wp_media_library");
instructions.setCurrentDateForPeopleProperty("last_time_added_photo_via_wp_media_library_to_post");
break;
case EDITOR_ADDED_VIDEO_VIA_LOCAL_LIBRARY:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Added Video via Local Library");
instructions.
setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_added_video_via_local_library");
instructions.setCurrentDateForPeopleProperty("last_time_added_video_via_local_library_to_post");
break;
case EDITOR_ADDED_VIDEO_VIA_WP_MEDIA_LIBRARY:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Added Video via WP Media Library");
instructions.setSuperPropertyAndPeoplePropertyToIncrement(
"number_of_times_added_video_via_wp_media_library");
instructions.setCurrentDateForPeopleProperty("last_time_added_video_via_wp_media_library_to_post");
break;
case EDITOR_PUBLISHED_POST:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Published Post");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_published_post");
instructions.setCurrentDateForPeopleProperty("last_time_published_post");
break;
case EDITOR_UPDATED_POST:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Updated Post");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_updated_post");
instructions.setCurrentDateForPeopleProperty("last_time_updated_post");
break;
case EDITOR_SCHEDULED_POST:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Scheduled Post");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_scheduled_post");
instructions.setCurrentDateForPeopleProperty("last_time_scheduled_post");
break;
case EDITOR_TAPPED_BLOCKQUOTE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Blockquote Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_blockquote");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_blockquote_in_editor");
break;
case EDITOR_TAPPED_BOLD:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Bold Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_bold");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_bold_in_editor");
break;
case EDITOR_TAPPED_IMAGE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Image Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_image");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_image_in_editor");
break;
case EDITOR_TAPPED_ITALIC:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Italics Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_italic");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_italic_in_editor");
break;
case EDITOR_TAPPED_LINK:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Link Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_link");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_link_in_editor");
break;
case EDITOR_TAPPED_MORE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped More Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_more");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_more_in_editor");
break;
case EDITOR_TAPPED_STRIKETHROUGH:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Strikethrough Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_strikethrough");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_strikethrough_in_editor");
break;
case EDITOR_TAPPED_UNDERLINE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Underline Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_underline");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_underline_in_editor");
break;
case EDITOR_TAPPED_HTML:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped HTML Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_html");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_html_in_editor");
break;
case EDITOR_TAPPED_ORDERED_LIST:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Ordered List Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_ordered_list");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_ordered_list_in_editor");
break;
case EDITOR_TAPPED_UNLINK:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Unlink Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_unlink");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_unlink_in_editor");
break;
case EDITOR_TAPPED_UNORDERED_LIST:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Editor - Tapped Unordered List Button");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_editor_tapped_unordered_list");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_unordered_list_in_editor");
break;
case NOTIFICATIONS_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Notifications - Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_notifications");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_notifications");
break;
case NOTIFICATIONS_OPENED_NOTIFICATION_DETAILS:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Notifications - Opened Notification Details");
instructions.
setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_opened_notification_details");
instructions.setCurrentDateForPeopleProperty("last_time_opened_notification_details");
break;
case NOTIFICATION_APPROVED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsWithSuperPropertyAndPeoplePropertyIncrementor(
"number_of_notifications_approved");
break;
case NOTIFICATION_UNAPPROVED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsWithSuperPropertyAndPeoplePropertyIncrementor(
"number_of_notifications_unapproved");
break;
case NOTIFICATION_REPLIED_TO:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsWithSuperPropertyAndPeoplePropertyIncrementor(
"number_of_notifications_replied_to");
break;
case NOTIFICATION_TRASHED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsWithSuperPropertyAndPeoplePropertyIncrementor(
"number_of_notifications_trashed");
break;
case NOTIFICATION_FLAGGED_AS_SPAM:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsWithSuperPropertyAndPeoplePropertyIncrementor(
"number_of_notifications_flagged_as_spam");
break;
case NOTIFICATION_LIKED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Notifications - Liked Comment");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_comment_likes_from_notification");
break;
case NOTIFICATION_UNLIKED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Notifications - Unliked Comment");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_comment_unlikes_from_notification");
break;
case OPENED_POSTS:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Site Menu - Opened Posts");
break;
case OPENED_PAGES:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Site Menu - Opened Pages");
break;
case OPENED_COMMENTS:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Site Menu - Opened Comments");
break;
case OPENED_VIEW_SITE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Site Menu - Opened View Site");
break;
case OPENED_VIEW_ADMIN:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Site Menu - Opened View Admin");
break;
case OPENED_MEDIA_LIBRARY:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Site Menu - Opened Media Library");
break;
case OPENED_BLOG_SETTINGS:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Site Menu - Opened Site Settings");
break;
case OPENED_ACCOUNT_SETTINGS:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Me - Opened Account Settings");
break;
case OPENED_APP_SETTINGS:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Me - Opened App Settings");
break;
case OPENED_MY_PROFILE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Me - Opened My Profile");
break;
case CREATED_ACCOUNT:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Created Account");
instructions.setCurrentDateForPeopleProperty("$created");
instructions.addSuperPropertyToFlag("created_account_on_mobile");
break;
case SHARED_ITEM:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsWithSuperPropertyAndPeoplePropertyIncrementor("number_of_items_shared");
break;
case ADDED_SELF_HOSTED_SITE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Added Self Hosted Site");
instructions.setCurrentDateForPeopleProperty("last_time_added_self_hosted_site");
break;
case SIGNED_IN:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Signed In");
break;
case SIGNED_INTO_JETPACK:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Signed into Jetpack");
instructions.addSuperPropertyToFlag("jetpack_user");
instructions.addSuperPropertyToFlag("dotcom_user");
break;
case ACCOUNT_LOGOUT:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Logged Out");
break;
case PERFORMED_JETPACK_SIGN_IN_FROM_STATS_SCREEN:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Signed into Jetpack from Stats Screen");
break;
case STATS_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_stats");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_stats");
break;
case STATS_INSIGHTS_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Insights Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_insights_screen_stats");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_insights_screen_stats");
break;
case STATS_PERIOD_DAYS_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Period Days Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_days_screen_stats");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_days_screen_stats");
break;
case STATS_PERIOD_WEEKS_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Period Weeks Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_weeks_screen_stats");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_weeks_screen_stats");
break;
case STATS_PERIOD_MONTHS_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Period Months Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_months_screen_stats");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_months_screen_stats");
break;
case STATS_PERIOD_YEARS_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Period Years Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_years_screen_stats");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_years_screen_stats");
break;
case STATS_VIEW_ALL_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - View All Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_view_all_screen_stats");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_view_all_screen_stats");
break;
case STATS_SINGLE_POST_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Single Post Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_single_post_screen_stats");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_single_post_screen_stats");
break;
case STATS_TAPPED_BAR_CHART:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Tapped Bar Chart");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_tapped_stats_bar_chart");
instructions.setCurrentDateForPeopleProperty("last_time_tapped_stats_bar_chart");
break;
case STATS_SCROLLED_TO_BOTTOM:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Scrolled to Bottom");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_scrolled_to_bottom_of_stats");
instructions.setCurrentDateForPeopleProperty("last_time_scrolled_to_bottom_of_stats");
break;
case STATS_SELECTED_INSTALL_JETPACK:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Selected Install Jetpack");
break;
case STATS_SELECTED_CONNECT_JETPACK:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Selected Connect Jetpack");
break;
case STATS_WIDGET_ADDED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Widget Added");
break;
case STATS_WIDGET_REMOVED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Widget Removed");
break;
case STATS_WIDGET_TAPPED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Stats - Widget Tapped");
break;
case PUSH_NOTIFICATION_RECEIVED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Push Notification - Received");
break;
case PUSH_NOTIFICATION_TAPPED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Push Notification - Alert Tapped");
break;
case SUPPORT_OPENED_HELPSHIFT_SCREEN:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Support - Opened Helpshift Screen");
instructions.addSuperPropertyToFlag("opened_helpshift_screen");
break;
case SUPPORT_SENT_REPLY_TO_SUPPORT_MESSAGE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Support - Replied to Helpshift");
instructions.addSuperPropertyToFlag("support_replied_to_helpshift");
break;
case LOGIN_MAGIC_LINK_EXITED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Magic Link exited");
break;
case LOGIN_MAGIC_LINK_FAILED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Magic Link failed");
break;
case LOGIN_MAGIC_LINK_OPENED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Magic Link opened");
break;
case LOGIN_MAGIC_LINK_REQUESTED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Magic Link requested");
break;
case LOGIN_MAGIC_LINK_SUCCEEDED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Magic Link succeeded");
break;
case LOGIN_FAILED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Failed Login");
break;
case LOGIN_FAILED_TO_GUESS_XMLRPC:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Failed To Guess XMLRPC");
break;
case LOGIN_INSERTED_INVALID_URL:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Inserted Invalid URL");
break;
case LOGIN_AUTOFILL_CREDENTIALS_FILLED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Auto Fill Credentials Filled");
break;
case LOGIN_AUTOFILL_CREDENTIALS_UPDATED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Login - Auto Fill Credentials Updated");
break;
case PUSH_AUTHENTICATION_APPROVED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Push Authentication - Approved");
break;
case PUSH_AUTHENTICATION_EXPIRED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Push Authentication - Expired");
break;
case PUSH_AUTHENTICATION_FAILED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Push Authentication - Failed");
break;
case PUSH_AUTHENTICATION_IGNORED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Push Authentication - Ignored");
break;
case NOTIFICATION_SETTINGS_LIST_OPENED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Notification Settings - Accessed List");
break;
case NOTIFICATION_SETTINGS_STREAMS_OPENED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Notification Settings - Accessed Stream");
break;
case NOTIFICATION_SETTINGS_DETAILS_OPENED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Notification Settings - Accessed Details");
break;
case ME_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Me Tab - Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_me_tab");
break;
case MY_SITE_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("My Site - Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_my_site");
break;
case THEMES_ACCESSED_THEMES_BROWSER:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Themes - Accessed Theme Browser");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_accessed_theme_browser");
instructions.setCurrentDateForPeopleProperty("last_time_accessed_theme_browser");
break;
case THEMES_ACCESSED_SEARCH:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Themes - Accessed Theme");
break;
case THEMES_CHANGED_THEME:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Themes - Changed Theme");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_changed_theme");
instructions.setCurrentDateForPeopleProperty("last_time_changed_theme");
break;
case THEMES_PREVIEWED_SITE:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Themes - Previewed Theme for Site");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_previewed_a_theme");
instructions.setCurrentDateForPeopleProperty("last_time_previewed_a_theme");
break;
case THEMES_DEMO_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Themes - Demo Accessed");
break;
case THEMES_CUSTOMIZE_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Themes - Customize Accessed");
break;
case THEMES_SUPPORT_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Themes - Support Accessed");
break;
case THEMES_DETAILS_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Themes - Details Accessed");
break;
case ACCOUNT_SETTINGS_LANGUAGE_CHANGED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Account Settings - Changed Language");
break;
case SITE_SETTINGS_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Settings - Site Settings Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_settings_accessed");
break;
case SITE_SETTINGS_ACCESSED_MORE_SETTINGS:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Settings - More Settings Accessed");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_more_settings_accessed");
break;
case SITE_SETTINGS_ADDED_LIST_ITEM:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Settings - Added List Item");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_list_items_added");
break;
case SITE_SETTINGS_DELETED_LIST_ITEMS:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Settings - Site Deleted List Items");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_list_items_were_deleted");
break;
case SITE_SETTINGS_HINT_TOAST_SHOWN:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Settings - Preference Hint Shown");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_preference_hints_viewed");
break;
case SITE_SETTINGS_LEARN_MORE_CLICKED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Settings - Learn More Clicked");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_learn_more_clicked");
break;
case SITE_SETTINGS_LEARN_MORE_LOADED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Settings - Learn More Loaded");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_learn_more_seen");
break;
case SITE_SETTINGS_SAVED_REMOTELY:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.
mixpanelInstructionsForEventName("Settings - Saved Remotely");
instructions.setSuperPropertyAndPeoplePropertyToIncrement("number_of_times_settings_updated_remotely");
break;
case SITE_SETTINGS_START_OVER_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Start Over Accessed");
break;
case SITE_SETTINGS_START_OVER_CONTACT_SUPPORT_CLICKED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Start Over Contact Support Clicked");
break;
case SITE_SETTINGS_EXPORT_SITE_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Export Site Accessed");
break;
case SITE_SETTINGS_EXPORT_SITE_REQUESTED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Export Site Requested");
break;
case SITE_SETTINGS_EXPORT_SITE_RESPONSE_OK:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Export Site Response OK");
break;
case SITE_SETTINGS_EXPORT_SITE_RESPONSE_ERROR:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Export Site Response Error");
break;
case SITE_SETTINGS_DELETE_SITE_ACCESSED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Delete Site Accessed");
break;
case SITE_SETTINGS_DELETE_SITE_PURCHASES_REQUESTED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Delete Site Purchases Requested");
break;
case SITE_SETTINGS_DELETE_SITE_PURCHASES_SHOWN:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Delete Site Purchases Shown");
break;
case SITE_SETTINGS_DELETE_SITE_PURCHASES_SHOW_CLICKED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Delete Site Show Purchases Clicked");
break;
case SITE_SETTINGS_DELETE_SITE_REQUESTED:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Delete Site Requested");
break;
case SITE_SETTINGS_DELETE_SITE_RESPONSE_OK:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Delete Site Response OK");
break;
case SITE_SETTINGS_DELETE_SITE_RESPONSE_ERROR:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("Settings - Delete Site Response Error");
break;
case ABTEST_START:
instructions = AnalyticsTrackerMixpanelInstructionsForStat.mixpanelInstructionsForEventName("AB Test - Started");
break;
default:
instructions = null;
break;
}
return instructions;
}
private void incrementPeopleProperty(String property) {
try {
mMixpanel.getPeople().increment(property, 1);
} catch (OutOfMemoryError outOfMemoryError) {
// ignore exception
}
}
@SuppressLint("CommitPrefEdits")
private void incrementSuperProperty(String property) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
int propertyCount = preferences.getInt(property, 0);
propertyCount++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(property, propertyCount);
editor.commit();
try {
JSONObject superProperties = mMixpanel.getSuperProperties();
superProperties.put(property, propertyCount);
mMixpanel.registerSuperProperties(superProperties);
} catch (JSONException e) {
AppLog.e(AppLog.T.UTILS, e);
}
}
private void flagSuperProperty(String property) {
try {
JSONObject superProperties = mMixpanel.getSuperProperties();
superProperties.put(property, true);
mMixpanel.registerSuperProperties(superProperties);
} catch (JSONException e) {
AppLog.e(AppLog.T.UTILS, e);
}
}
private void savePropertyValueForStat(String property, Object value, AnalyticsTracker.Stat stat) {
JSONObject properties = mAggregatedProperties.get(stat);
if (properties == null) {
properties = new JSONObject();
mAggregatedProperties.put(stat, properties);
}
try {
properties.put(property, value);
} catch (JSONException e) {
AppLog.e(AppLog.T.UTILS, e);
}
}
private JSONObject propertiesForStat(AnalyticsTracker.Stat stat) {
return mAggregatedProperties.get(stat);
}
private void removePropertiesForStat(AnalyticsTracker.Stat stat) {
mAggregatedProperties.remove(stat);
}
private Object propertyForStat(String property, AnalyticsTracker.Stat stat) {
JSONObject properties = mAggregatedProperties.get(stat);
if (properties == null) {
return null;
}
try {
return properties.get(property);
} catch (JSONException e) {
// We are okay with swallowing this exception as the next line will just return a null value
}
return null;
}
private void incrementProperty(String property, AnalyticsTracker.Stat stat) {
Object currentValueObj = propertyForStat(property, stat);
int currentValue = 1;
if (currentValueObj != null) {
currentValue = Integer.valueOf(currentValueObj.toString());
currentValue++;
}
savePropertyValueForStat(property, Integer.toString(currentValue), stat);
}
public void incrementSessionCount() {
// Tracking session count will help us isolate users who just installed the app
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
int sessionCount = preferences.getInt(SESSION_COUNT, 0);
sessionCount++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(SESSION_COUNT, sessionCount);
editor.apply();
}
} |
package org.alien4cloud.tosca.catalog.index;
import static alien4cloud.dao.FilterUtil.fromKeyValueCouples;
import static alien4cloud.dao.FilterUtil.singleKeyFilter;
import java.util.*;
import javax.annotation.Resource;
import org.alien4cloud.tosca.model.CSARDependency;
import org.alien4cloud.tosca.model.Csar;
import org.alien4cloud.tosca.model.types.AbstractToscaType;
import org.alien4cloud.tosca.model.types.NodeType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import alien4cloud.dao.IGenericSearchDAO;
import alien4cloud.dao.model.FacetedSearchResult;
import alien4cloud.exception.NotFoundException;
import alien4cloud.utils.VersionUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
@Primary
public class ToscaTypeSearchService extends AbstractToscaIndexSearchService<AbstractToscaType> implements IToscaTypeSearchService {
@Resource(name = "alien-es-dao")
private IGenericSearchDAO searchDAO;
@Value("${components.search.boost.name_query_similitude:100}")
private Integer nameQuerySimilitudeBoost;
@Override
public Csar getArchive(String archiveName, String archiveVersion) {
return searchDAO.findById(Csar.class, Csar.createId(archiveName, archiveVersion));
}
@Override
public boolean hasTypes(String archiveName, String archiveVersion) {
return searchDAO.buildQuery(AbstractToscaType.class).setFilters(fromKeyValueCouples("archiveName", archiveName, "archiveVersion", archiveVersion))
.count() > 0;
}
@Override
public AbstractToscaType[] getArchiveTypes(String archiveName, String archiveVersion) {
return searchDAO.buildQuery(AbstractToscaType.class).setFilters(fromKeyValueCouples("archiveName", archiveName, "archiveVersion", archiveVersion))
.prepareSearch().search(0, Integer.MAX_VALUE).getData();
}
@Override
public <T extends AbstractToscaType> T find(Class<T> elementType, String elementId, String version) {
return searchDAO.buildQuery(elementType).setFilters(fromKeyValueCouples("rawElementId", elementId, "archiveVersion", version)).prepareSearch().find();
}
public <T extends AbstractToscaType> T findByIdOrFail(Class<T> elementType, String toscaTypeId) {
T type = searchDAO.findById(elementType, toscaTypeId);
if (type == null) {
throw new NotFoundException(String.format("[%s] [%s] does not exists.", elementType.getSimpleName(), toscaTypeId));
}
return type;
}
@Override
public <T extends AbstractToscaType> T findOrFail(Class<T> elementType, String elementId, String version) {
T type = find(elementType, elementId, version);
if (type == null) {
throw new NotFoundException(String.format("[%s] [%s] does not exists with version [%s].", elementType.getSimpleName(), elementId, version));
}
return type;
}
@Override
public <T extends AbstractToscaType> T findMostRecent(Class<T> elementType, String elementId) {
return searchDAO.buildQuery(elementType).setFilters(fromKeyValueCouples("rawElementId", elementId)).prepareSearch()
.alterSearchRequestBuilder(
searchRequestBuilder -> searchRequestBuilder.addSort(new FieldSortBuilder("nestedVersion.majorVersion").order(SortOrder.DESC))
.addSort(new FieldSortBuilder("nestedVersion.minorVersion").order(SortOrder.DESC))
.addSort(new FieldSortBuilder("nestedVersion.incrementalVersion").order(SortOrder.DESC))
.addSort(new FieldSortBuilder("nestedVersion.qualifier").order(SortOrder.DESC).missing("_first")))
.find();
}
@Override
public <T extends AbstractToscaType> T[] findAll(Class<T> elementType, String elementId) {
return searchDAO.buildQuery(elementType).setFilters(singleKeyFilter("rawElementId", elementId)).prepareSearch().search(0, Integer.MAX_VALUE).getData();
}
/**
* Build an elasticsearch query to get data tosca elements based on a set of dependencies.
*
* @param dependencies The set of dependencies.
* @param keyValueFilters List of key1, value1, key2, value2 to add term filters to the query for each dependency.
* @return
*/
private BoolQueryBuilder getDependencyQuery(Set<CSARDependency> dependencies, String... keyValueFilters) {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
for (CSARDependency dependency : dependencies) {
BoolQueryBuilder dependencyQuery = QueryBuilders.boolQuery();
dependencyQuery.must(QueryBuilders.termQuery("archiveName", dependency.getName()))
.must(QueryBuilders.termQuery("archiveVersion", dependency.getVersion()));
if (keyValueFilters != null) {
for (int i = 0; i < keyValueFilters.length; i += 2) {
dependencyQuery.must(QueryBuilders.termQuery(keyValueFilters[i], keyValueFilters[i + 1]));
}
}
boolQueryBuilder.should(dependencyQuery);
}
return boolQueryBuilder;
}
@Override
public boolean isElementExistInDependencies(@NonNull Class<? extends AbstractToscaType> elementClass, @NonNull String elementId,
Set<CSARDependency> dependencies) {
if (dependencies == null || dependencies.isEmpty()) {
return false;
}
return searchDAO.count(elementClass, getDependencyQuery(dependencies, "rawElementId", elementId)) > 0;
}
private <T extends AbstractToscaType> T getLatestVersionOfElement(Class<T> elementClass, QueryBuilder queryBuilder) {
List<T> elements = searchDAO.customFindAll(elementClass, queryBuilder);
if (elements != null && !elements.isEmpty()) {
Collections.sort(elements,
(left, right) -> VersionUtil.parseVersion(left.getArchiveVersion()).compareTo(VersionUtil.parseVersion(right.getArchiveVersion())));
return elements.get(elements.size() - 1);
} else {
return null;
}
}
@Override
public <T extends AbstractToscaType> T getElementInDependencies(Class<T> elementClass, Set<CSARDependency> dependencies, String... keyValues) {
if (dependencies == null || dependencies.isEmpty()) {
return null;
}
BoolQueryBuilder boolQueryBuilder = getDependencyQuery(dependencies, keyValues);
return getLatestVersionOfElement(elementClass, boolQueryBuilder);
}
@Override
public <T extends AbstractToscaType> T getElementInDependencies(Class<T> elementClass, String elementId, Set<CSARDependency> dependencies) {
if (dependencies == null || dependencies.isEmpty()) {
return null;
}
BoolQueryBuilder boolQueryBuilder = getDependencyQuery(dependencies, "rawElementId", elementId);
return getLatestVersionOfElement(elementClass, boolQueryBuilder);
}
@Override
public <T extends AbstractToscaType> T getRequiredElementInDependencies(Class<T> elementClass, String elementId, Set<CSARDependency> dependencies)
throws NotFoundException {
T element = getElementInDependencies(elementClass, elementId, dependencies);
if (element == null) {
throw new NotFoundException(
"Element elementId: [" + elementId + "] of type [" + elementClass.getSimpleName() + "] cannot be found in dependencies " + dependencies);
}
return element;
}
// we need to override for aspect purpose
@Override
public FacetedSearchResult search(Class<? extends AbstractToscaType> clazz, String query, Integer size, Map<String, String[]> filters) {
FacetedSearchResult result = super.search(clazz, query, size, filters);
reorderIfNodeType(clazz, query, result);
return result;
}
private void reorderIfNodeType(Class<? extends AbstractToscaType> clazz, String query, FacetedSearchResult result) {
if(NodeType.class.isAssignableFrom(clazz)){
Arrays.sort(result.getData(), Comparator.comparingLong(value -> {
NodeType nodeType = (NodeType)value;
if(query != null && nodeType.getElementId().toLowerCase().contains(query.toLowerCase())){
return nameQuerySimilitudeBoost * nodeType.getAlienScore();
}else{
return nodeType.getAlienScore();
}
}).reversed());
}
}
@Override
protected AbstractToscaType[] getArray(int size) {
return new AbstractToscaType[size];
}
@Override
protected String getAggregationField() {
return "rawElementId";
}
} |
package com.noveogroup.android.task;
import java.util.Collection;
import java.util.List;
public interface TaskExecutor {
/**
* Returns synchronization object of this {@link TaskExecutor}.
* <p/>
* Any access to this {@link TaskExecutor} should be synchronized using
* this object.
* <p/>
* The same object should be returned from method {@link Pack#lock()} by
* all of collections of arguments associated with tasks belonging to
* this {@link TaskExecutor}.
*
* @return the synchronization object.
*/
public Object lock();
public <Input, Output> Pack<Input, Output> newPack();
public <Input, Output> Pack<Input, Output> newPack(Pack pack);
public Pack<Void, Void> args();
public TaskSet queue(String... tags);
public TaskSet queue(Collection<String> tags);
public TaskSet queue(Collection<String> tags, Collection<TaskHandler.State> states);
public ErrorHandler getErrorHandler();
public void setErrorHandler(ErrorHandler errorHandler);
public void addTaskListener(TaskListener<Object, Object> taskListener);
public void removeTaskListener(TaskListener<Object, Object> taskListener);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, String... tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Collection<String> tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, TaskListener<Input, Output> taskListener, String... tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, TaskListener<Input, Output> taskListener, Collection<String> tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, List<TaskListener<Input, Output>> taskListeners, String... tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, List<TaskListener<Input, Output>> taskListeners, Collection<String> tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Input input, String... tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Input input, Collection<String> tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Input input, TaskListener<Input, Output> taskListener, String... tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Input input, TaskListener<Input, Output> taskListener, Collection<String> tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Input input, List<TaskListener<Input, Output>> taskListeners, String... tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Input input, List<TaskListener<Input, Output>> taskListeners, Collection<String> tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Pack<Input, Output> vars, String... tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Pack<Input, Output> vars, Collection<String> tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Pack<Input, Output> vars, TaskListener<Input, Output> taskListener, String... tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Pack<Input, Output> vars, TaskListener<Input, Output> taskListener, Collection<String> tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Pack<Input, Output> vars, List<TaskListener<Input, Output>> taskListeners, String... tags);
public <Input, Output> TaskHandler<Input, Output> execute(Task<Input, Output> task, Pack<Input, Output> vars, List<TaskListener<Input, Output>> taskListeners, Collection<String> tags);
public void shutdown();
public boolean isShutdown();
} |
package com.nestedworld.nestedworld.network.socket.implementation;
import android.support.annotation.NonNull;
import com.nestedworld.nestedworld.helpers.log.LogHelper;
import com.nestedworld.nestedworld.network.socket.listener.SocketListener;
import org.msgpack.core.MessageInsufficientBufferException;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePacker;
import org.msgpack.core.MessageUnpacker;
import org.msgpack.value.ImmutableValue;
import org.msgpack.value.MapValue;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.LinkedList;
public final class SocketManager {
private final String TAG = getClass().getSimpleName();
private final String hostname;
private final int port;
private final LinkedList<SocketListener> listeners = new LinkedList<>(); /* Stores the list of SocketListeners to notify whenever an onEvent occurs. */
private int timeOut;
private Socket socket = new Socket();
private MessagePacker messagePacker;/*input stream reader.*/
private MessageUnpacker messageUnpacker;/*output stream writer.*/
/*
** Constructor (Creates a new unconnected socket).
*/
public SocketManager(@NonNull final String hostname, final int port) {
this(hostname, port, 0);
}
public SocketManager(@NonNull final String hostname, final int port, final int timeOut) {
LogHelper.d(TAG, "init SocketManager: hostname=" + hostname + " port=" + port + " timeOut=" + timeOut);
this.hostname = hostname;
this.port = port;
this.timeOut = timeOut;
this.messagePacker = null;
this.messageUnpacker = null;
}
/*
** Setter
*/
public synchronized void setTimeOut(final int timeOut) {
this.timeOut = timeOut;
}
/*
** Public method
*/
public synchronized void addSocketListener(@NonNull final SocketListener socketListener) {
listeners.add(socketListener);
}
public synchronized void removeSocketListener(@NonNull final SocketListener socketListener) {
listeners.remove(socketListener);
}
//Connects the socket to the given remote host address and port specified in the constructor
//connecting method will block until the connection is established or an error occurred.
public synchronized void connect() {
LogHelper.d(TAG, "Trying to connect...");
try {
/*Init socket*/
if (socket == null) {
throw new IllegalArgumentException("Can't connect if socket is null");
}
socket.connect(new InetSocketAddress(hostname, port), timeOut);
/*Init serializer / deserializer */
messagePacker = new MessagePack.PackerConfig().newPacker(socket.getOutputStream());
messageUnpacker = new MessagePack.UnpackerConfig().newUnpacker(socket.getInputStream());
/*Display some log*/
LogHelper.d(TAG, "Connection Success");
/*Send notification*/
notifySocketConnected();
/*Init a listeningThread*/
startListeningTask();
} catch (IOException | IllegalArgumentException e) {
socket = null;
messagePacker = null;
messageUnpacker = null;
/*Display some log*/
LogHelper.e(TAG, "Connection failed");
e.printStackTrace();
/*Send notification*/
notifySocketDisconnected();
}
}
// Closes the socket.
// It is not possible to reconnect or rebind to the socket
// which means a new socket instance has to be created.
public synchronized void disconnect() {
try {
if (socket != null) {
socket.close();
socket = null;
}
if (messagePacker != null) {
messagePacker.close();
messagePacker = null;
}
if (messageUnpacker != null) {
messageUnpacker.close();
messageUnpacker = null;
}
} catch (IOException e) {
e.printStackTrace();
}
notifySocketDisconnected();
}
/*
** Runnable implementation
* Listens for messages while the socket is connected.
* use the connect() method before.
*/
public synchronized void send(@NonNull final MapValue message) {
LogHelper.d(TAG, "Sending: " + message);
startSendingTask(message);
}
/*
** Internal method
*/
private void startSendingTask(@NonNull final MapValue message) {
new Thread(new Runnable() {
@Override
public void run() {
try {
messagePacker.packValue(message);
messagePacker.flush();
} catch (IOException e) {
LogHelper.d(TAG, "Can't send message");
e.printStackTrace();
}
}
}).start();
}
private void startListeningTask() {
new Thread(new Runnable() {
@Override
public void run() {
try {
if (socket == null || !socket.isConnected()) {
throw new UnsupportedOperationException("You should call connect() before");
}
/*Send notification*/
notifySocketListening();
LogHelper.d(TAG, "Listening on socket...");
while (true) {
if (messageUnpacker != null) {
ImmutableValue message = messageUnpacker.unpackValue();
notifyMessageReceived(message);
}
}
} catch (IOException | MessageInsufficientBufferException | UnsupportedOperationException e) {
LogHelper.d(TAG, "Connection close by server");
notifySocketDisconnected();
}
}
}).start();
}
/*
** Utils
*/
private void notifySocketConnected() {
LogHelper.d(TAG, "notifySocketConnected");
for (final SocketListener listener : listeners) {
listener.onSocketConnected();
}
}
private void notifySocketListening() {
LogHelper.d(TAG, "notifySocketListening");
for (final SocketListener listener : listeners) {
listener.onSocketListening();
}
}
private void notifySocketDisconnected() {
LogHelper.d(TAG, "notifySocketDisconnected");
for (final SocketListener listener : listeners) {
listener.onSocketDisconnected();
}
}
private void notifyMessageReceived(@NonNull final ImmutableValue message) {
LogHelper.d(TAG, "Message receive: " + message.toString());
for (final SocketListener listener : listeners) {
listener.onMessageReceived(message);
}
}
} |
package org.herac.tuxguitar.player.base;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.herac.tuxguitar.song.managers.TGSongManager;
import org.herac.tuxguitar.song.models.TGBeat;
import org.herac.tuxguitar.song.models.TGChannel;
import org.herac.tuxguitar.song.models.TGDuration;
import org.herac.tuxguitar.song.models.TGMeasureHeader;
import org.herac.tuxguitar.song.models.TGNote;
import org.herac.tuxguitar.song.models.TGString;
import org.herac.tuxguitar.song.models.TGTrack;
import org.herac.tuxguitar.util.TGLock;
public class MidiPlayer{
private static final int MAX_CHANNELS = 16;
public static final int MAX_VOLUME = 10;
private static final int TIMER_DELAY = 10;
private TGSongManager songManager;
private MidiSequencer sequencer;
private MidiTransmitter outputTransmitter;
private MidiOutputPort outputPort;
private MidiPlayerMode mode;
private MidiPlayerCountDown countDown;
private String sequencerKey;
private String outputPortKey;
private List outputPortProviders;
private List sequencerProviders;
private List listeners;
private int volume;
private boolean running;
private boolean paused;
private boolean changeTickPosition;
private boolean metronomeEnabled;
private int metronomeTrack;
private int infoTrack;
private int loopSHeader;
private int loopEHeader;
private long loopSPosition;
private boolean anySolo;
protected long tickLength;
protected long tickPosition;
protected TGLock lock = new TGLock();
public MidiPlayer() {
this.lock = new TGLock();
this.volume = MAX_VOLUME;
}
public void init(TGSongManager songManager) {
this.songManager = songManager;
this.outputPortProviders = new ArrayList();
this.sequencerProviders = new ArrayList();
this.listeners = new ArrayList();
this.getSequencer();
this.getMode();
this.reset();
}
public MidiInstrument[] getInstruments(){
return MidiInstrument.INSTRUMENT_LIST;
}
public MidiPercussion[] getPercussions(){
return MidiPercussion.PERCUSSION_LIST;
}
public void reset(){
this.stop();
this.lock.lock();
this.tickPosition = TGDuration.QUARTER_TIME;
this.setChangeTickPosition(false);
this.lock.unlock();
}
public void close(){
try {
this.closeSequencer();
this.closeOutputPort();
} catch (MidiPlayerException e) {
e.printStackTrace();
}
}
public void stopSequencer() {
try{
if( this.getSequencer().isRunning() ){
this.getSequencer().stop();
}
}catch (MidiPlayerException e) {
e.printStackTrace();
}
}
public void stop(boolean paused) {
this.setPaused(paused);
this.stopSequencer();
this.setRunning(false);
}
public void stop() {
this.stop(false);
}
public void pause(){
this.stop(true);
}
public synchronized void play() throws MidiPlayerException{
try {
this.lock.lock();
final boolean notifyStarted = (!this.isRunning());
this.setRunning(true);
this.stopSequencer();
this.checkDevices();
this.updateLoop(true);
this.addSequence();
this.updateTracks();
this.updatePrograms();
this.updateControllers();
this.updateDefaultControllers();
this.setMetronomeEnabled(isMetronomeEnabled());
this.changeTickPosition();
new Thread(new Runnable() {
public synchronized void run() {
try {
MidiPlayer.this.lock.lock();
if( notifyStarted ){
MidiPlayer.this.notifyStarted();
}
if( MidiPlayer.this.getCountDown().isEnabled() ){
MidiPlayer.this.notifyCountDownStarted();
MidiPlayer.this.getCountDown().start();
MidiPlayer.this.notifyCountDownStopped();
}
if( MidiPlayer.this.isRunning() ){
if( MidiPlayer.this.isChangeTickPosition() ){
MidiPlayer.this.changeTickPosition();
}
MidiPlayer.this.getSequencer().start();
}
MidiPlayer.this.tickLength = getSequencer().getTickLength();
MidiPlayer.this.tickPosition = getSequencer().getTickPosition();
Object sequencerLock = new Object();
while (getSequencer().isRunning() && isRunning()) {
synchronized(sequencerLock) {
if (isChangeTickPosition()) {
changeTickPosition();
}
MidiPlayer.this.tickPosition = getSequencer().getTickPosition();
sequencerLock.wait( TIMER_DELAY );
}
}
//FINISH
if(isRunning()){
if(MidiPlayer.this.tickPosition >= (MidiPlayer.this.tickLength - (TGDuration.QUARTER_TIME / 2) )){
finish();
}else {
stop(isPaused());
}
}
if( !isRunning() ){
MidiPlayer.this.notifyStopped();
}
}catch (Throwable throwable) {
reset();
throwable.printStackTrace();
}finally{
MidiPlayer.this.lock.unlock();
}
}
}).start();
}catch (Throwable throwable) {
this.reset();
throw new MidiPlayerException(throwable.getMessage(),throwable);
}finally{
this.lock.unlock();
}
}
protected void finish(){
try {
if(this.getMode().isLoop()){
this.stopSequencer();
this.setTickPosition(TGDuration.QUARTER_TIME);
this.getMode().notifyLoop();
this.notifyLoop();
this.play();
return;
}
this.reset();
} catch (MidiPlayerException e) {
e.printStackTrace();
}
}
public void updateLoop( boolean force ){
if( force || !this.isRunning() ){
this.loopSHeader = -1;
this.loopEHeader = -1;
this.loopSPosition = TGDuration.QUARTER_TIME;
if( getMode().isLoop() ){
int hCount = this.songManager.getSong().countMeasureHeaders();
this.loopSHeader = ( getMode().getLoopSHeader() <= hCount ? getMode().getLoopSHeader() : -1 ) ;
this.loopEHeader = ( getMode().getLoopEHeader() <= hCount ? getMode().getLoopEHeader() : -1 ) ;
if( this.loopSHeader > 0 && this.loopSHeader <= hCount ){
TGMeasureHeader header = this.songManager.getMeasureHeader( this.loopSHeader );
if( header != null ){
this.loopSPosition = header.getStart();
}
}
}
}
}
public int getLoopSHeader() {
return this.loopSHeader;
}
public int getLoopEHeader() {
return this.loopEHeader;
}
public long getLoopSPosition() {
return this.loopSPosition;
}
public void checkDevices() throws Throwable {
this.getSequencer().check();
if( this.getOutputPort() != null ){
this.getOutputPort().check();
}
}
public int getVolume() {
return this.volume;
}
public void setVolume(int volume) {
this.volume = volume;
if (this.isRunning()) {
this.updateControllers();
}
}
public void setRunning(boolean running) {
this.running = running;
}
public boolean isRunning() {
try {
return (this.running || this.getSequencer().isRunning());
} catch (MidiPlayerException e) {
e.printStackTrace();
}
return false;
}
public boolean isPaused() {
return this.paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
protected boolean isChangeTickPosition() {
return this.changeTickPosition;
}
private void setChangeTickPosition(boolean changeTickPosition) {
this.changeTickPosition = changeTickPosition;
}
public void setTickPosition(long position) {
this.tickPosition = position;
this.setChangeTickPosition(true);
}
public long getTickPosition() {
return this.tickPosition;
}
protected void changeTickPosition(){
try{
if(isRunning()){
if( this.tickPosition < this.getLoopSPosition() ){
this.tickPosition = this.getLoopSPosition();
}
this.getSequencer().setTickPosition(this.tickPosition);
}
setChangeTickPosition(false);
} catch (MidiPlayerException e) {
e.printStackTrace();
}
}
public void addSequence() {
try{
MidiSequenceParser parser = new MidiSequenceParser(this.songManager,MidiSequenceParser.DEFAULT_PLAY_FLAGS,getMode().getCurrentPercent(),0);
MidiSequenceHandler sequence = getSequencer().createSequence(this.songManager.getSong().countTracks() + 2);
parser.setSHeader( getLoopSHeader() );
parser.setEHeader( getLoopEHeader() );
parser.parse(sequence);
this.infoTrack = parser.getInfoTrack();
this.metronomeTrack = parser.getMetronomeTrack();
} catch (MidiPlayerException e) {
e.printStackTrace();
}
}
private void updateDefaultControllers(){
try{
for(int channel = 0; channel < MAX_CHANNELS;channel ++){
getOutputTransmitter().sendControlChange(channel,MidiControllers.RPN_MSB,0);
getOutputTransmitter().sendControlChange(channel,MidiControllers.RPN_LSB,0);
getOutputTransmitter().sendControlChange(channel,MidiControllers.DATA_ENTRY_MSB,12);
getOutputTransmitter().sendControlChange(channel,MidiControllers.DATA_ENTRY_LSB, 0);
}
}
catch (MidiPlayerException e) {
e.printStackTrace();
}
}
public void updatePrograms() {
try{
Iterator it = this.songManager.getSong().getChannels();
while(it.hasNext()){
TGChannel channel = (TGChannel)it.next();
getOutputTransmitter().sendControlChange(channel.getChannel(),MidiControllers.BANK_SELECT,channel.getBank());
getOutputTransmitter().sendProgramChange(channel.getChannel(),channel.getProgram());
if( channel.getChannel() != channel.getEffectChannel()){
getOutputTransmitter().sendControlChange(channel.getEffectChannel(), MidiControllers.BANK_SELECT,channel.getBank());
getOutputTransmitter().sendProgramChange(channel.getEffectChannel(), channel.getProgram());
}
}
}catch (MidiPlayerException e) {
e.printStackTrace();
}
}
public void updateControllers() {
boolean percussionUpdated = false;
Iterator channelsIt = this.songManager.getSong().getChannels();
while( channelsIt.hasNext() ){
TGChannel channel = (TGChannel) channelsIt.next();
this.updateController(channel);
percussionUpdated = (percussionUpdated || channel.isPercussionChannel());
}
if(!percussionUpdated && isMetronomeEnabled()){
int volume = (int)((this.getVolume() / 10.00) * TGChannel.DEFAULT_VOLUME);
int balance = TGChannel.DEFAULT_BALANCE;
int chorus = TGChannel.DEFAULT_CHORUS;
int reverb = TGChannel.DEFAULT_REVERB;
int phaser = TGChannel.DEFAULT_PHASER;
int tremolo = TGChannel.DEFAULT_TREMOLO;
updateController(9,volume,balance,chorus,reverb,phaser,tremolo,127);
}
this.afterUpdate();
}
private void updateController(TGChannel channel) {
int volume = (int)((this.getVolume() / 10.00) * channel.getVolume());
int balance = channel.getBalance();
int chorus = channel.getChorus();
int reverb = channel.getReverb();
int phaser = channel.getPhaser();
int tremolo = channel.getTremolo();
updateController(channel.getChannel(),volume,balance,chorus,reverb,phaser,tremolo,127);
if(channel.getChannel() != channel.getEffectChannel()){
updateController(channel.getEffectChannel(),volume,balance,chorus,reverb,phaser,tremolo,127);
}
}
private void updateController(int channel,int volume,int balance,int chorus, int reverb,int phaser, int tremolo, int expression) {
try{
getOutputTransmitter().sendControlChange(channel,MidiControllers.VOLUME,volume);
getOutputTransmitter().sendControlChange(channel,MidiControllers.BALANCE,balance);
getOutputTransmitter().sendControlChange(channel,MidiControllers.CHORUS,chorus);
getOutputTransmitter().sendControlChange(channel,MidiControllers.REVERB,reverb);
getOutputTransmitter().sendControlChange(channel,MidiControllers.PHASER,phaser);
getOutputTransmitter().sendControlChange(channel,MidiControllers.TREMOLO,tremolo);
getOutputTransmitter().sendControlChange(channel,MidiControllers.EXPRESSION,expression);
}catch (MidiPlayerException e) {
e.printStackTrace();
}
}
public void updateTracks() {
this.anySolo = false;
Iterator tracksIt = this.songManager.getSong().getTracks();
while( tracksIt.hasNext() ){
TGTrack track = (TGTrack)tracksIt.next();
this.updateTrack(track);
this.anySolo = ((!this.anySolo)?track.isSolo():this.anySolo);
}
this.afterUpdate();
}
private void updateTrack(TGTrack track) {
try{
getSequencer().setMute(track.getNumber(),track.isMute());
getSequencer().setSolo(track.getNumber(),track.isSolo());
}catch (MidiPlayerException e) {
e.printStackTrace();
}
}
private void afterUpdate(){
try{
getSequencer().setSolo(this.infoTrack,this.anySolo);
getSequencer().setSolo(this.metronomeTrack,(isMetronomeEnabled() && this.anySolo));
}catch (MidiPlayerException e) {
e.printStackTrace();
}
}
public boolean isMetronomeEnabled() {
return this.metronomeEnabled;
}
public void setMetronomeEnabled(boolean metronomeEnabled) {
try{
this.metronomeEnabled = metronomeEnabled;
this.getSequencer().setMute(this.metronomeTrack,!isMetronomeEnabled());
this.getSequencer().setSolo(this.metronomeTrack,(isMetronomeEnabled() && this.anySolo));
}catch (MidiPlayerException e) {
e.printStackTrace();
}
}
public void playBeat(TGBeat beat) {
List notes = new ArrayList();
for( int v = 0; v < beat.countVoices(); v ++){
notes.addAll( beat.getVoice(v).getNotes() );
}
playBeat(beat.getMeasure().getTrack(), notes);
}
public void playBeat(TGTrack track,final List notes) {
TGChannel tgChannel = this.songManager.getChannel(track.getChannelId());
if( tgChannel != null ){
int channel = tgChannel.getChannel();
int bank = tgChannel.getBank();
int program = tgChannel.getProgram();
int volume = (int)((this.getVolume() / 10.00) * tgChannel.getVolume());
int balance = tgChannel.getBalance();
int chorus = tgChannel.getChorus();
int reverb = tgChannel.getReverb();
int phaser = tgChannel.getPhaser();
int tremolo = tgChannel.getTremolo();
int size = notes.size();
int[][] beat = new int[size][2];
for(int i = 0; i < size; i ++){
TGNote note = (TGNote)notes.get(i);
beat[i][0] = track.getOffset() + (note.getValue() + ((TGString)track.getStrings().get(note.getString() - 1)).getValue());
beat[i][1] = note.getVelocity();
}
playBeat(channel,bank,program,volume,balance,chorus,reverb,phaser,tremolo,beat);
}
}
public void playBeat(int channel,int bank,int program,int volume,int balance,int chorus, int reverb,int phaser,int tremolo,int[][] beat) {
playBeat(channel, bank, program, volume, balance, chorus, reverb, phaser, tremolo, beat,500,0);
}
public void playBeat(int channel,int bank,int program,int volume,int balance,int chorus, int reverb,int phaser,int tremolo,int[][] beat,long duration,int interval) {
try {
getOutputTransmitter().sendControlChange(channel,MidiControllers.BANK_SELECT,bank);
getOutputTransmitter().sendControlChange(channel,MidiControllers.VOLUME,volume);
getOutputTransmitter().sendControlChange(channel,MidiControllers.BALANCE,balance);
getOutputTransmitter().sendControlChange(channel,MidiControllers.CHORUS,chorus);
getOutputTransmitter().sendControlChange(channel,MidiControllers.REVERB,reverb);
getOutputTransmitter().sendControlChange(channel,MidiControllers.PHASER,phaser);
getOutputTransmitter().sendControlChange(channel,MidiControllers.TREMOLO,tremolo);
getOutputTransmitter().sendProgramChange(channel,program);
for(int i = 0; i < beat.length; i ++){
getOutputTransmitter().sendNoteOn(channel,beat[i][0], beat[i][1]);
if(interval > 0){
Thread.sleep(interval);
}
}
Thread.sleep(duration);
for(int i = 0; i < beat.length; i ++){
getOutputTransmitter().sendNoteOff(channel,beat[i][0], beat[i][1]);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
public TGSongManager getSongManager(){
return this.songManager;
}
public MidiPlayerMode getMode(){
if(this.mode == null){
this.mode = new MidiPlayerMode();
}
return this.mode;
}
public MidiPlayerCountDown getCountDown(){
if( this.countDown == null ){
this.countDown = new MidiPlayerCountDown(this);
}
return this.countDown;
}
public MidiTransmitter getOutputTransmitter(){
if (this.outputTransmitter == null) {
this.outputTransmitter = new MidiTransmitter();
}
return this.outputTransmitter;
}
public MidiOutputPort getOutputPort(){
return this.outputPort;
}
public MidiSequencer getSequencer(){
if (this.sequencer == null) {
this.sequencer = new MidiSequencerEmpty();
}
return this.sequencer;
}
public boolean loadSequencer(MidiSequencer sequencer){
try{
this.closeSequencer();
this.sequencer = sequencer;
this.sequencer.open();
this.sequencer.setTransmitter( getOutputTransmitter() );
}catch(Throwable throwable){
this.sequencer = null;
return false;
}
return true;
}
public boolean loadOutputPort(MidiOutputPort port){
try{
this.closeOutputPort();
this.outputPort = port;
this.outputPort.open();
this.getOutputTransmitter().addReceiver(this.outputPort.getKey(), this.outputPort.getReceiver() );
}catch(Throwable throwable){
this.outputPort = null;
return false;
}
return true;
}
public void openOutputPort(String key) {
this.openOutputPort(key, false);
}
public void openOutputPort(String key, boolean tryFirst) {
this.outputPortKey = key;
this.openOutputPort(listOutputPorts(),tryFirst);
}
public void openOutputPort(List ports, boolean tryFirst) {
try{
if(this.outputPortKey != null && !this.isOutputPortOpen(this.outputPortKey)){
this.closeOutputPort();
for(int i = 0; i < ports.size(); i ++){
MidiOutputPort port = (MidiOutputPort)ports.get(i);
if(port.getKey().equals(this.outputPortKey)){
if(this.loadOutputPort(port)){
return;
}
}
}
}
if(getOutputPort() == null && !ports.isEmpty() && tryFirst){
this.loadOutputPort( (MidiOutputPort)ports.get(0) );
}
}catch(Throwable throwable){
throwable.printStackTrace();
}
}
public void openSequencer(String key) {
this.openSequencer(key, false);
}
public void openSequencer(String key, boolean tryFirst) {
try{
this.sequencerKey = key;
this.openSequencer(listSequencers(),tryFirst);
}catch(Throwable throwable){
throwable.printStackTrace();
}
}
public void openSequencer(List sequencers ,boolean tryFirst) throws MidiPlayerException {
try{
if(this.sequencerKey != null && !this.isSequencerOpen(this.sequencerKey)){
this.closeSequencer();
for(int i = 0; i < sequencers.size(); i ++){
MidiSequencer sequencer = (MidiSequencer)sequencers.get(i);
if(sequencer.getKey().equals(this.sequencerKey)){
if(this.loadSequencer(sequencer)){
return;
}
}
}
}
if(getSequencer() instanceof MidiSequencerEmpty && !sequencers.isEmpty() && tryFirst){
this.loadSequencer( (MidiSequencer) sequencers.get(0));
}
}catch(Throwable throwable){
throw new MidiPlayerException(throwable.getMessage(),throwable);
}
}
public List listOutputPorts() {
List ports = new ArrayList();
Iterator it = this.outputPortProviders.iterator();
while(it.hasNext()){
try{
MidiOutputPortProvider provider = (MidiOutputPortProvider)it.next();
ports.addAll(provider.listPorts());
}catch(Throwable throwable){
throwable.printStackTrace();
}
}
return ports;
}
public List listSequencers(){
List sequencers = new ArrayList();
Iterator it = this.sequencerProviders.iterator();
while(it.hasNext()){
try{
MidiSequencerProvider provider = (MidiSequencerProvider)it.next();
sequencers.addAll(provider.listSequencers());
}catch(Throwable throwable){
throwable.printStackTrace();
}
}
return sequencers;
}
public void closeSequencer() throws MidiPlayerException{
try{
if(this.isRunning()){
this.stop();
}
this.lock.lock();
if (this.sequencer != null) {
this.sequencer.close();
this.sequencer = null;
}
this.lock.unlock();
}catch(Throwable throwable){
throw new MidiPlayerException(throwable.getMessage(),throwable);
}
}
public void closeOutputPort(){
try{
if(this.isRunning()){
this.stop();
}
this.lock.lock();
if (this.outputPort != null) {
this.getOutputTransmitter().removeReceiver(this.outputPort.getKey());
this.outputPort.close();
this.outputPort = null;
}
this.lock.unlock();
}catch(Throwable throwable){
throwable.printStackTrace();
}
}
public boolean isSequencerOpen(String key){
if(key != null){
String currentKey = getSequencer().getKey();
if(currentKey == null){
return false;
}
return currentKey.equals(key);
}
return false;
}
public boolean isOutputPortOpen(String key){
if(key != null && getOutputPort() != null ){
String currentKey = getOutputPort().getKey();
if(currentKey == null){
return false;
}
return currentKey.equals(key);
}
return false;
}
public void addOutputPortProvider(MidiOutputPortProvider provider) throws MidiPlayerException {
this.addOutputPortProvider(provider, false);
}
public void addOutputPortProvider(MidiOutputPortProvider provider, boolean tryFirst) throws MidiPlayerException {
this.outputPortProviders.add(provider);
this.openOutputPort(provider.listPorts(),tryFirst);
}
public void addSequencerProvider(MidiSequencerProvider provider) throws MidiPlayerException {
this.addSequencerProvider(provider, false);
}
public void addSequencerProvider(MidiSequencerProvider provider, boolean tryFirst) throws MidiPlayerException {
this.sequencerProviders.add(provider);
this.openSequencer(provider.listSequencers(), tryFirst);
}
public void removeOutputPortProvider(MidiOutputPortProvider provider) throws MidiPlayerException {
this.outputPortProviders.remove(provider);
MidiOutputPort current = getOutputPort();
if( current != null ){
Iterator it = provider.listPorts().iterator();
while(it.hasNext()){
MidiOutputPort port = (MidiOutputPort)it.next();
if(port.getKey().equals(current.getKey())){
closeOutputPort();
break;
}
}
}
}
public void removeSequencerProvider(MidiSequencerProvider provider) throws MidiPlayerException {
this.sequencerProviders.remove(provider);
MidiSequencer current = getSequencer();
if(!(current instanceof MidiSequencerEmpty) && current != null){
Iterator it = provider.listSequencers().iterator();
while(it.hasNext()){
MidiSequencer sequencer = (MidiSequencer)it.next();
if(current.getKey().equals(sequencer.getKey())){
closeSequencer();
break;
}
}
}
}
public void addListener( MidiPlayerListener listener ){
if( !this.listeners.contains( listener ) ){
this.listeners.add( listener );
}
}
public void removeListener( MidiPlayerListener listener ){
if( this.listeners.contains( listener ) ){
this.listeners.remove( listener );
}
}
public void notifyStarted(){
Iterator it = this.listeners.iterator();
while( it.hasNext() ){
MidiPlayerListener listener = (MidiPlayerListener) it.next();
listener.notifyStarted();
}
}
public void notifyStopped(){
Iterator it = this.listeners.iterator();
while( it.hasNext() ){
MidiPlayerListener listener = (MidiPlayerListener) it.next();
listener.notifyStopped();
}
}
public void notifyCountDownStarted(){
Iterator it = this.listeners.iterator();
while( it.hasNext() ){
MidiPlayerListener listener = (MidiPlayerListener) it.next();
listener.notifyCountDownStarted();
}
}
public void notifyCountDownStopped(){
Iterator it = this.listeners.iterator();
while( it.hasNext() ){
MidiPlayerListener listener = (MidiPlayerListener) it.next();
listener.notifyCountDownStopped();
}
}
public void notifyLoop(){
Iterator it = this.listeners.iterator();
while( it.hasNext() ){
MidiPlayerListener listener = (MidiPlayerListener) it.next();
listener.notifyLoop();
}
}
} |
package me.rei_m.hyakuninisshu.presentation.utilitty;
import android.content.Context;
import android.databinding.BindingAdapter;
import android.databinding.ObservableField;
import android.graphics.Color;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import me.rei_m.hyakuninisshu.R;
import me.rei_m.hyakuninisshu.presentation.karuta.constant.QuizState;
import me.rei_m.hyakuninisshu.presentation.karuta.widget.view.KarutaExamResultView;
import me.rei_m.hyakuninisshu.presentation.karuta.widget.view.VerticalSingleLineTextView;
import static me.rei_m.hyakuninisshu.presentation.karuta.constant.KarutaConstant.SPACE;
public class DataBindingAttributeBinder {
private DataBindingAttributeBinder() {
}
@BindingAdapter({"textForQuiz", "textPosition"})
public static void setTextForQuiz(@NonNull TextView view,
@Nullable String text,
int textPosition) {
if (text == null || text.length() < textPosition) {
return;
}
view.setText(text.substring(textPosition - 1, textPosition));
}
@BindingAdapter({"textSizeByPx"})
public static void setTextSizeByPx(@NonNull TextView view,
int textSize) {
view.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
@BindingAdapter({"verticalText"})
public static void setVerticalText(@NonNull VerticalSingleLineTextView view,
@NonNull String text) {
view.drawText(text);
}
@BindingAdapter({"verticalTextSize"})
public static void setVerticalTextSize(@NonNull VerticalSingleLineTextView view,
@DimenRes int dimenId) {
view.setTextSize(dimenId);
}
@BindingAdapter({"verticalTextSizeByPx"})
public static void setVerticalTextSizeByPx(@NonNull VerticalSingleLineTextView view,
int textSize) {
view.setTextSizeByPx(textSize);
}
@BindingAdapter({"stringDrawableId"})
public static void setStringDrawableId(@NonNull ImageView view,
@Nullable String drawableId) {
if (drawableId == null) {
return;
}
int resId = view.getResources().getIdentifier(drawableId, "drawable", view.getContext().getApplicationContext().getPackageName());
Glide.with(view.getContext()).load(resId).into(view);
}
@BindingAdapter({"visibilityByQuizState"})
public static void setVisibilityByQuizState(@NonNull ImageView imageView,
@Nullable ObservableField<QuizState> quizState) {
if (quizState == null) {
imageView.setVisibility(View.GONE);
return;
}
switch (quizState.get()) {
case UNANSWERED:
imageView.setVisibility(View.GONE);
break;
case ANSWERED_COLLECT:
Glide.with(imageView.getContext()).load(R.drawable.check_correct).dontAnimate().into(imageView);
imageView.setVisibility(View.VISIBLE);
break;
case ANSWERED_INCORRECT:
Glide.with(imageView.getContext()).load(R.drawable.check_incorrect).dontAnimate().into(imageView);
imageView.setVisibility(View.VISIBLE);
break;
}
}
@BindingAdapter({"examResultList"})
public static void setKarutaExamResult(@NonNull KarutaExamResultView view,
@Nullable boolean[] karutaQuizResultList) {
if (karutaQuizResultList == null) {
return;
}
view.setResult(karutaQuizResultList);
}
@BindingAdapter({"elevation"})
public static void setElevation(@NonNull View view,
@DimenRes int elevation) {
ViewCompat.setElevation(view, view.getContext().getResources().getDimension(elevation));
}
@BindingAdapter({"karutaSrc"})
public static void setKarutaSrc(@NonNull ImageView view,
@Nullable String resIdString) {
if (resIdString == null) {
return;
}
Context context = view.getContext().getApplicationContext();
int resId = context.getResources().getIdentifier("karuta_" + resIdString, "drawable", context.getPackageName());
Glide.with(view.getContext())
.load(resId)
.crossFade()
.into(view);
}
@BindingAdapter({"textTopPhraseKana", "kimariji"})
public static void setTextTopPhraseKana(@NonNull TextView view,
@Nullable String topPhrase,
int kimariji) {
if (topPhrase == null) {
return;
}
int finallyKimariji = 0;
for (int i = 0; i < topPhrase.length() - 1; i++) {
if (topPhrase.substring(i, i + 1).equals(SPACE)) {
finallyKimariji++;
} else {
if (kimariji < i) {
break;
}
}
finallyKimariji++;
}
SpannableStringBuilder ssb = new SpannableStringBuilder().append(topPhrase);
ssb.setSpan(new ForegroundColorSpan(Color.RED), 0, finallyKimariji - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
view.setText(ssb);
}
} |
package br.usp.each.saeg.badua.test.validation;
import org.junit.Assert;
import org.junit.Test;
public class MaxException1SourceTest extends AbstractMaxSourceTest {
private Throwable exception;
@Override
public int[] input() {
return new int[] { };
}
@Override
protected void handle(final Throwable e) throws Exception {
// Ignore exception, but assert was thrown
exception = e;
}
@Test
public void exceptionWasThrown() {
Assert.assertNotNull(exception);
}
@Test
public void verifyTotal() {
assertTotal(true, 0);
assertTotal(false, 23);
}
} |
package org.ovirt.engine.core.bll;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.profiles.DiskProfileHelper;
import org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter;
import org.ovirt.engine.core.bll.quota.QuotaStorageConsumptionParameter;
import org.ovirt.engine.core.bll.quota.QuotaStorageDependent;
import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.bll.validator.storage.DiskValidator;
import org.ovirt.engine.core.bll.validator.storage.StorageDomainValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.LockProperties;
import org.ovirt.engine.core.common.action.LockProperties.Scope;
import org.ovirt.engine.core.common.action.MoveOrCopyImageGroupParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.storage.CopyVolumeType;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.ImageDbOperationScope;
import org.ovirt.engine.core.common.businessentities.storage.ImageOperation;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.common.businessentities.storage.StorageType;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.VmDeviceDao;
@DisableInPrepareMode
@NonTransactiveCommandAttribute
public class MoveOrCopyDiskCommand<T extends MoveOrCopyImageGroupParameters> extends CopyImageGroupCommand<T>
implements QuotaStorageDependent {
private List<PermissionSubject> cachedPermsList;
private List<Pair<VM, VmDevice>> cachedVmsDeviceInfo;
private String cachedDiskIsBeingMigratedMessage;
public MoveOrCopyDiskCommand(T parameters) {
this(parameters, null);
}
public MoveOrCopyDiskCommand(T parameters, CommandContext commandContext) {
super(parameters, commandContext);
defineVmTemplate();
}
@Override
protected LockProperties applyLockProperties(LockProperties lockProperties) {
return lockProperties.withScope(Scope.Command);
}
protected void defineVmTemplate() {
if (getParameters().getOperation() == ImageOperation.Copy) {
setVmTemplate(getTemplateForImage());
}
}
protected VmTemplate getTemplateForImage() {
if (getImage() == null) {
return null;
}
Collection<VmTemplate> templates = getVmTemplateDao().getAllForImage(getImage().getImageId()).values();
return !templates.isEmpty() ? templates.iterator().next() : null;
}
@Override
protected void setActionMessageParameters() {
addCanDoActionMessage(getParameters().getOperation() == ImageOperation.Copy ?
EngineMessage.VAR__ACTION__COPY
: EngineMessage.VAR__ACTION__MOVE);
addCanDoActionMessage(EngineMessage.VAR__TYPE__VM_DISK);
}
@Override
protected boolean canDoAction() {
return super.canDoAction()
&& isImageExist()
&& checkOperationIsCorrect()
&& isDiskUsedAsOvfStore()
&& isImageNotLocked()
&& isSourceAndDestTheSame()
&& validateSourceStorageDomain()
&& validateDestStorage()
&& checkTemplateInDestStorageDomain()
&& validateSpaceRequirements()
&& validateVmSnapshotStatus()
&& checkCanBeMoveInVm()
&& checkIfNeedToBeOverride()
&& setAndValidateDiskProfiles();
}
protected boolean isSourceAndDestTheSame() {
if (getParameters().getOperation() == ImageOperation.Move
&& getParameters().getSourceDomainId().equals(getParameters().getStorageDomainId())) {
return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_SOURCE_AND_TARGET_SAME);
}
return true;
}
protected boolean isImageExist() {
if (getImage() == null) {
return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_DISK_NOT_EXIST);
}
return true;
}
protected boolean isImageNotLocked() {
DiskImage diskImage = getImage();
if (diskImage.getImageStatus() == ImageStatus.LOCKED) {
if (getParameters().getOperation() == ImageOperation.Move) {
return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_DISKS_LOCKED,
String.format("$%1$s %2$s", "diskAliases", diskImage.getDiskAlias()));
} else {
return failCanDoAction(EngineMessage.VM_TEMPLATE_IMAGE_IS_LOCKED);
}
}
return true;
}
protected boolean isDiskUsedAsOvfStore() {
return validate(new DiskValidator(getImage()).isDiskUsedAsOvfStore());
}
/**
* The following method will perform a check for correctness of operation
* It is allow to move only if it is image of template
* @return
*/
protected boolean checkOperationIsCorrect() {
if (getParameters().getOperation() == ImageOperation.Move
&& getImage().getVmEntityType() != null && getImage().getVmEntityType().isTemplateType()) {
return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_DISK_IS_NOT_VM_DISK);
}
return true;
}
protected boolean validateDestStorage() {
StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain());
if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) {
return false;
}
// Validate shareable disks moving/copying
boolean moveOrCopy = getParameters().getOperation() == ImageOperation.Move || getParameters().getOperation() == ImageOperation.Copy;
if (moveOrCopy && getImage().isShareable() && getStorageDomain().getStorageType() == StorageType.GLUSTERFS ) {
return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_CANT_MOVE_SHAREABLE_DISK_TO_GLUSTERFS,
String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias()));
}
return true;
}
/**
* Check if destination storage has enough space
* @return
*/
protected boolean validateSpaceRequirements() {
StorageDomainValidator storageDomainValidator = createStorageDomainValidator();
if (validate(storageDomainValidator.isDomainWithinThresholds())) {
getImage().getSnapshots().addAll(getAllImageSnapshots());
return validate(storageDomainValidator.hasSpaceForDiskWithSnapshots(getImage()));
}
return false;
}
private boolean validateVmSnapshotStatus() {
SnapshotsValidator snapshotsValidator = getSnapshotsValidator();
for (Pair<VM, VmDevice> pair : getVmsWithVmDeviceInfoForDiskId()) {
VmDevice vmDevice = pair.getSecond();
if (vmDevice.getSnapshotId() == null) { // Skip check for VMs with connected snapshot
VM vm = pair.getFirst();
if (!validate(snapshotsValidator.vmNotInPreview(vm.getId()))) {
return false;
}
}
}
return true;
}
protected SnapshotsValidator getSnapshotsValidator() {
return new SnapshotsValidator();
}
protected List<DiskImage> getAllImageSnapshots() {
return ImagesHandler.getAllImageSnapshots(getImage().getImageId());
}
protected boolean checkIfNeedToBeOverride() {
if (isTemplate() &&
getParameters().getOperation() == ImageOperation.Copy &&
!getParameters().getForceOverride() &&
getImage().getStorageIds().contains(getStorageDomain().getId())) {
return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_IMAGE_ALREADY_EXISTS);
}
return true;
}
/**
* Validate a source storage domain of image, when a source storage domain is not provided
* any of the domains image will be used
*/
protected boolean validateSourceStorageDomain() {
Guid sourceDomainId = getParameters().getSourceDomainId();
if (sourceDomainId == null || Guid.Empty.equals(sourceDomainId)) {
sourceDomainId = getImage().getStorageIds().get(0);
getParameters().setSourceDomainId(sourceDomainId);
}
StorageDomainValidator validator =
new StorageDomainValidator(getStorageDomainDao().getForStoragePool(sourceDomainId,
getImage().getStoragePoolId()));
return validate(validator.isDomainExistAndActive());
}
/**
* If a disk is attached to VM it can be moved when it is unplugged or at case that disk is plugged
* vm should be down
* @return
*/
protected boolean checkCanBeMoveInVm() {
return validate(createDiskValidator().isDiskPluggedToVmsThatAreNotDown(false, getVmsWithVmDeviceInfoForDiskId()));
}
/**
* Cache method to retrieve all the VMs with the device info related to the image
*/
protected List<Pair<VM, VmDevice>> getVmsWithVmDeviceInfoForDiskId() {
if (cachedVmsDeviceInfo == null) {
cachedVmsDeviceInfo = getVmDao().getVmsWithPlugInfo(getImage().getId());
}
return cachedVmsDeviceInfo;
}
/**
* The following method will check, if we can move disk to destination storage domain, when
* it is based on template
* @return
*/
protected boolean checkTemplateInDestStorageDomain() {
if (getParameters().getOperation() == ImageOperation.Move
&& !Guid.Empty.equals(getImage().getImageTemplateId())) {
DiskImage templateImage = getDiskImageDao().get(getImage().getImageTemplateId());
if (!templateImage.getStorageIds().contains(getParameters().getStorageDomainId())) {
return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_TEMPLATE_NOT_FOUND_ON_DESTINATION_DOMAIN);
}
}
return true;
}
protected VmDeviceDao getVmDeviceDao() {
return getDbFacade().getVmDeviceDao();
}
protected VdcActionType getImagesActionType() {
if (getParameters().getOperation() == ImageOperation.Move) {
return VdcActionType.MoveImageGroup;
}
return VdcActionType.CopyImageGroup;
}
@Override
protected void executeCommand() {
MoveOrCopyImageGroupParameters p = prepareChildParameters();
VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext(
getImagesActionType(),
p);
if (!vdcRetValue.getSucceeded()) {
setSucceeded(false);
getReturnValue().setFault(vdcRetValue.getFault());
} else {
setSucceeded(true);
if (getParameters().getOperation() == ImageOperation.Copy && !isTemplate()) {
ImagesHandler.addDiskImageWithNoVmDevice(getImage());
}
getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList());
}
}
private void endCommandActions() {
if (!getParameters().getImagesParameters().isEmpty()) {
getBackend().endAction(getImagesActionType(),
getParameters().getImagesParameters().get(0),
getContext().clone().withoutCompensationContext().withoutLock());
}
setSucceeded(true);
}
@Override
protected void endSuccessfully() {
endCommandActions();
incrementDbGenerationForRelatedEntities();
}
private void incrementDbGenerationForRelatedEntities() {
if (getParameters().getOperation() == ImageOperation.Copy) {
// When copying a non template disk the copy is to a new
// floating disk, so no need to increment any generations.
if (!isTemplate()) {
return;
}
getVmStaticDao().incrementDbGeneration(getVmTemplateId());
} else {
List<Pair<VM, VmDevice>> vmsForDisk = getVmsWithVmDeviceInfoForDiskId();
for (Pair<VM, VmDevice> pair : vmsForDisk) {
getVmStaticDao().incrementDbGeneration(pair.getFirst().getId());
}
}
}
@Override
protected void endWithFailure() {
endCommandActions();
}
@Override
public AuditLogType getAuditLogTypeValue() {
switch (getActionState()) {
case EXECUTE:
return getSucceeded() ? (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_VM_DISK
: AuditLogType.USER_COPIED_DISK
: (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_FAILED_MOVED_VM_DISK
: AuditLogType.USER_FAILED_COPY_DISK;
case END_SUCCESS:
return getSucceeded() ? (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_VM_DISK_FINISHED_SUCCESS
: AuditLogType.USER_COPIED_DISK_FINISHED_SUCCESS
: (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_VM_DISK_FINISHED_FAILURE
: AuditLogType.USER_COPIED_DISK_FINISHED_FAILURE;
default:
return (getParameters().getOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_VM_DISK_FINISHED_FAILURE
: AuditLogType.USER_COPIED_DISK_FINISHED_FAILURE;
}
}
@Override
public List<PermissionSubject> getPermissionCheckSubjects() {
if (cachedPermsList == null) {
cachedPermsList = new ArrayList<>();
DiskImage image = getImage();
Guid diskId = image == null ? Guid.Empty : image.getId();
cachedPermsList.add(new PermissionSubject(diskId, VdcObjectType.Disk, ActionGroup.CONFIGURE_DISK_STORAGE));
cachedPermsList.add(new PermissionSubject(getParameters().getStorageDomainId(),
VdcObjectType.Storage, ActionGroup.CREATE_DISK));
}
return cachedPermsList;
}
private MoveOrCopyImageGroupParameters prepareChildParameters() {
MoveOrCopyImageGroupParameters parameters = new MoveOrCopyImageGroupParameters(getParameters());
if (parameters.getOperation() == ImageOperation.Copy) {
parameters.setUseCopyCollapse(true);
parameters.setAddImageDomainMapping(true);
parameters.setShouldLockImageOnRevert(false);
if (!isTemplate()) {
prepareCopyNotTemplate(parameters);
parameters.setShouldLockImageOnRevert(true);
parameters.setRevertDbOperationScope(ImageDbOperationScope.IMAGE);
}
} else {
parameters.setUseCopyCollapse(false);
}
if (parameters.getOperation() == ImageOperation.Move || isTemplate()) {
parameters.setDestinationImageId(getImageId());
parameters.setImageGroupID(getImageGroupId());
parameters.setDestImageGroupId(getImageGroupId());
}
parameters.setVolumeFormat(getDiskImage().getVolumeFormat());
parameters.setVolumeType(getDiskImage().getVolumeType());
if (isTemplate()) {
parameters.setCopyVolumeType(CopyVolumeType.SharedVol);
}
else {
parameters.setCopyVolumeType(CopyVolumeType.LeafVol);
}
parameters.setParentCommand(getActionType());
parameters.setParentParameters(getParameters());
parameters.setDiskProfileId(getImage().getDiskProfileId());
return parameters;
}
/**
* Prepares the copy of the VM disks and floating disks
*/
private void prepareCopyNotTemplate(MoveOrCopyImageGroupParameters parameters) {
parameters.setAddImageDomainMapping(false);
Guid newImageId = Guid.newGuid();
Guid newId = Guid.newGuid();
DiskImage image = getImage();
image.setId(newId);
image.setImageId(newImageId);
image.setDiskAlias(getDiskAlias());
image.setStorageIds(new ArrayList<Guid>());
image.getStorageIds().add(getParameters().getStorageDomainId());
image.setQuotaId(getParameters().getQuotaId());
image.setDiskProfileId(getParameters().getDiskProfileId());
image.setImageStatus(ImageStatus.LOCKED);
image.setVmSnapshotId(null);
image.setParentId(Guid.Empty);
image.setImageTemplateId(Guid.Empty);
parameters.setDestinationImageId(newImageId);
parameters.setDestImageGroupId(newId);
}
private boolean isTemplate() {
return !(getImage().getVmEntityType() == null || !getImage().getVmEntityType().isTemplateType());
}
@Override
protected Map<String, Pair<String, String>> getSharedLocks() {
if (getParameters().getOperation() == ImageOperation.Copy) {
if (!Guid.Empty.equals(getVmTemplateId())) {
return Collections.singletonMap(getVmTemplateId().toString(),
LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, getDiskIsBeingMigratedMessage()));
}
} else {
List<Pair<VM, VmDevice>> vmsForDisk = getVmsWithVmDeviceInfoForDiskId();
if (!vmsForDisk.isEmpty()) {
Map<String, Pair<String, String>> lockMap = new HashMap<>();
for (Pair<VM, VmDevice> pair : vmsForDisk) {
lockMap.put(pair.getFirst().getId().toString(),
LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, getDiskIsBeingMigratedMessage()));
}
return lockMap;
}
}
return null;
}
@Override
protected Map<String, Pair<String, String>> getExclusiveLocks() {
return Collections.singletonMap(
(getImage() != null ? getImage().getId() : Guid.Empty).toString(),
LockMessagesMatchUtil.makeLockingPair(LockingGroup.DISK, getDiskIsBeingMigratedMessage()));
}
private String getDiskIsBeingMigratedMessage() {
if (cachedDiskIsBeingMigratedMessage == null) {
StringBuilder builder = new StringBuilder(EngineMessage.ACTION_TYPE_FAILED_DISK_IS_BEING_MIGRATED.name());
if (getImage() != null) {
builder.append(String.format("$DiskName %1$s", getDiskAlias()));
}
cachedDiskIsBeingMigratedMessage = builder.toString();
}
return cachedDiskIsBeingMigratedMessage;
}
public String getDiskAlias() {
return StringUtils.isEmpty(getParameters().getNewAlias()) ? getImage().getDiskAlias() : getParameters().getNewAlias();
}
protected boolean setAndValidateDiskProfiles() {
getImage().setDiskProfileId(getParameters().getDiskProfileId());
return validate(DiskProfileHelper.setAndValidateDiskProfiles(Collections.singletonMap(getImage(),
getParameters().getStorageDomainId()), getStoragePool().getCompatibilityVersion(), getCurrentUser()));
}
@Override
public List<QuotaConsumptionParameter> getQuotaStorageConsumptionParameters() {
List<QuotaConsumptionParameter> list = new ArrayList<>();
list.add(new QuotaStorageConsumptionParameter(
getDestinationQuotaId(),
null,
QuotaConsumptionParameter.QuotaAction.CONSUME,
getParameters().getStorageDomainId(),
(double)getImage().getSizeInGigabytes()));
if (ImageOperation.Move == getParameters().getOperation()) {
if (getImage().getQuotaId() != null && !Guid.Empty.equals(getImage().getQuotaId())) {
list.add(new QuotaStorageConsumptionParameter(
getImage().getQuotaId(),
null,
QuotaConsumptionParameter.QuotaAction.RELEASE,
getParameters().getSourceDomainId(),
(double)getImage().getSizeInGigabytes()));
}
}
return list;
}
private Guid getDestinationQuotaId() {
return getParameters().getQuotaId();
}
@Override
public Map<String, String> getJobMessageProperties() {
List<StorageDomain> storageDomains = getStorageDomainDao().getAllForStorageDomain(getParameters().getSourceDomainId());
String sourceSDName = StringUtils.EMPTY;
if (storageDomains.size() > 0) {
sourceSDName = storageDomains.get(0).getStorageName();
}
if (jobProperties == null) {
jobProperties = super.getJobMessageProperties();
jobProperties.put("sourcesd", sourceSDName);
jobProperties.put("targetsd", getStorageDomainName());
jobProperties.put("diskalias", getDiskAlias());
if (ImageOperation.Move == getParameters().getOperation()) {
jobProperties.put("action", "Moving");
} else {
jobProperties.put("action", "Copying");
}
}
return jobProperties;
}
protected StorageDomainValidator createStorageDomainValidator() {
return new StorageDomainValidator(getStorageDomain());
}
protected DiskValidator createDiskValidator() {
return new DiskValidator(getImage());
}
} |
package ch.elexis.core.data.service.internal;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.AgeFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang.time.DateUtils;
import org.osgi.service.component.annotations.Component;
import org.slf4j.LoggerFactory;
import ch.elexis.core.data.activator.CoreHub;
import ch.elexis.core.data.service.LocalLockServiceHolder;
import ch.elexis.core.lock.types.LockResponse;
import ch.elexis.core.services.IConflictHandler;
import ch.elexis.core.services.IConflictHandler.Result;
import ch.elexis.core.services.ILocalDocumentService;
import ch.elexis.core.utils.FileUtil;
import ch.rgw.tools.MimeTool;
@Component
public class LocalDocumentService implements ILocalDocumentService {
private HashMap<Object, File> managedFiles = new HashMap<>();
private HashMap<Object, LockResponse> managedLocks = new HashMap<>();
private HashMap<Class<?>, ISaveHandler> registeredSaveHandler = new HashMap<>();
private HashMap<Class<?>, ILoadHandler> registeredLoadHandler = new HashMap<>();
@Override
public Optional<File> add(Object documentSource, IConflictHandler conflictHandler)
throws IllegalStateException{
boolean readOnly = false;
if (documentSource != null) {
LockResponse result =
LocalLockServiceHolder.get().acquireLock(documentSource);
if (result.isOk()) {
managedLocks.put(documentSource, result);
} else {
readOnly = true;
}
}
ILoadHandler loadHandler = getRegisteredLoadHandler(documentSource.getClass());
if (loadHandler == null) {
throw new IllegalStateException("No load handler for [" + documentSource + "]");
}
String fileName = getFileName(documentSource);
InputStream in = loadHandler.load(documentSource);
if (in != null) {
Optional<File> ret = writeLocalFile(fileName, in,
conflictHandler, readOnly);
ret.ifPresent(file -> {
managedFiles.put(documentSource, file);
});
return ret;
}
return Optional.empty();
}
private ILoadHandler getRegisteredLoadHandler(Class<? extends Object> clazz){
ILoadHandler matchingHandler = registeredLoadHandler.get(clazz);
if (matchingHandler == null) {
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> interfaze : interfaces) {
matchingHandler = registeredLoadHandler.get(interfaze);
if(matchingHandler != null) {
break;
}
}
}
return matchingHandler;
}
@Override
public void remove(Object documentSource, IConflictHandler conflictHandler){
// try to delete the file
File file = managedFiles.get(documentSource);
if (file != null && file.exists()) {
Path path = Paths.get(file.getAbsolutePath());
boolean deleted = false;
while (!(deleted = tryDelete(path))) {
Result result = conflictHandler.getResult();
if (result == Result.OVERWRITE) {
// try again
} else {
break;
}
}
if (deleted) {
removeManaged(documentSource);
}
} else {
removeManaged(documentSource);
}
}
@Override
public void remove(Object documentSource){
File file = managedFiles.get(documentSource);
if (file != null && file.exists()) {
tryDelete(Paths.get(file.getAbsolutePath()));
}
removeManaged(documentSource);
}
private void removeManaged(Object documentSource){
LockResponse lock = managedLocks.get(documentSource);
if (lock != null) {
LocalLockServiceHolder.get().releaseLock(documentSource);
managedLocks.remove(documentSource);
}
managedFiles.remove(documentSource);
}
private boolean tryDelete(Path path){
try {
if (tryBackup(path)) {
Files.delete(path);
return true;
}
} catch (IOException e) {
}
return false;
}
private boolean tryBackup(Path path){
try {
File src = path.toFile();
File backupDir = new File(getDocumentCachePath() + File.separator + "backup");
deleteBackupFilesOlderThen(backupDir, 90);
FileUtils.copyFile(src,
new File(backupDir, "bak_" + System.currentTimeMillis() + "_" + src.getName()));
return true;
} catch (IOException e) {
LoggerFactory.getLogger(getClass()).warn("Cannot create backup for file.", e);
return false;
}
}
private void deleteBackupFilesOlderThen(File backupDir, int days){
try {
if (backupDir.isDirectory()) {
Collection<File> filesToDelete = FileUtils.listFiles(backupDir,
new AgeFileFilter(DateUtils.addDays(new Date(), days * -1)),
TrueFileFilter.TRUE);
for (File file : filesToDelete) {
boolean success = FileUtils.deleteQuietly(file);
if (!success) {
LoggerFactory.getLogger(getClass())
.warn("Cannot delete old backup file at: " + file.getAbsolutePath());
}
}
}
} catch (Exception e) {
LoggerFactory.getLogger(getClass()).warn("Cannot delete old backup files.", e);
}
}
@Override
public boolean contains(Object documentSource){
return managedFiles.containsKey(documentSource);
}
@Override
public Optional<InputStream> getContent(Object documentSource){
File file = managedFiles.get(documentSource);
if (file != null) {
try {
return Optional.of(new ByteArrayInputStream(
Files.readAllBytes(Paths.get(file.getAbsolutePath()))));
} catch (IOException e) {
LoggerFactory.getLogger(getClass()).error("Error reading file", e);
}
}
return Optional.empty();
}
/**
* Write a local file using the filename and the content.
*
* @param content
* @param fileName
* @param conflictHandler
*
* @return
*/
private Optional<File> writeLocalFile(String fileName, InputStream content,
IConflictHandler conflictHandler, boolean readOnly){
Path dirPath = Paths.get(getDocumentCachePath());
if (!Files.exists(dirPath, new LinkOption[0])) {
try {
Files.createDirectories(dirPath);
} catch (IOException e) {
LoggerFactory.getLogger(getClass()).error("Could not create directory", e);
return Optional.empty();
}
}
Path filePath = Paths.get(getDocumentCachePath() + File.separator, fileName);
if (Files.exists(filePath)) {
Result result = conflictHandler.getResult();
if (result == Result.ABORT) {
return Optional.empty();
} else if (result == Result.KEEP) {
return Optional.of(filePath.toFile());
} else if (result == Result.OVERWRITE) {
return Optional.ofNullable(writeFile(filePath, content, readOnly));
}
} else {
return Optional.ofNullable(writeFile(filePath, content, readOnly));
}
return Optional.empty();
}
@Override
public String getDocumentCachePath(){
return CoreHub.getWritableUserDir().getAbsolutePath() + File.separator + ".localdoc";
}
private File writeFile(Path path, InputStream content, boolean readOnly){
try {
Files.deleteIfExists(path);
Path newFile = Files.createFile(path);
Files.copy(content, newFile, StandardCopyOption.REPLACE_EXISTING);
File ret = newFile.toFile();
ret.setWritable(!readOnly);
return ret;
} catch (IOException e) {
LoggerFactory.getLogger(getClass()).error("Error writing file", e);
}
return null;
}
/**
* User reflection to determine a meaningful name.
*
* @param documentSource
* @return
*/
private String getFileName(Object documentSource){
StringBuilder sb = new StringBuilder("_");
try {
Method nameMethod = null;
Method[] methods = documentSource.getClass().getMethods();
for (Method method : methods) {
if (isGetNameMethod(method)) {
nameMethod = method;
break;
}
}
if (nameMethod != null) {
sb.append(nameMethod.invoke(documentSource, new Object[0]));
} else {
sb.append(getDefaultFileName());
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// default
sb.append(getDefaultFileName());
}
try {
Method idMethod = null;
Method[] methods = documentSource.getClass().getMethods();
for (Method method : methods) {
if (isGetIdMethod(method)) {
idMethod = method;
break;
}
}
if (idMethod != null) {
sb.append("[" + idMethod.invoke(documentSource, new Object[0]) + "]");
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// ignore
}
sb.append("_");
try {
Method mimeMethod = null;
Method[] methods = documentSource.getClass().getMethods();
for (Method method : methods) {
if (method.getName().toLowerCase().contains("mime")
&& method.getReturnType() == String.class) {
mimeMethod = method;
break;
}
}
if (mimeMethod != null) {
sb.append(
"." + getFileEnding((String) mimeMethod.invoke(documentSource, new Object[0])));
} else {
sb.append(getDefaultFileEnding());
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// default
sb.append(getDefaultFileEnding());
}
return FileUtil.removeInvalidChars(sb.toString());
}
private boolean isGetIdMethod(Method method){
if (method.getParameterTypes().length > 0) {
return false;
}
String lowerName = method.getName().toLowerCase();
if (lowerName.equals("getid")) {
return true;
}
return false;
}
private boolean isGetNameMethod(Method method){
if (method.getParameterTypes().length > 0) {
return false;
}
String lowerName = method.getName().toLowerCase();
if (lowerName.contains("betreff") || lowerName.contains("titel")
|| lowerName.contains("title")) {
return true;
}
return false;
}
private String getFileEnding(String mime){
if (mime != null) {
if (mime.length() < 5) {
return mime;
} else {
String ret = MimeTool.getExtension(mime);
if (ret.length() > 5) {
return getDefaultFileEnding();
} else if (ret.isEmpty()) {
return FilenameUtils.getExtension(mime);
} else {
return ret;
}
}
}
return getDefaultFileEnding();
}
private String getDefaultFileEnding(){
return ".tmp";
}
private Object getDefaultFileName(){
return "localFile" + System.currentTimeMillis();
}
@Override
public List<Object> getAll(){
return new ArrayList<>(managedFiles.keySet());
}
@Override
public void registerSaveHandler(Class<?> clazz, ISaveHandler saveHandler){
registeredSaveHandler.put(clazz, saveHandler);
}
@Override
public void registerLoadHandler(Class<?> clazz, ILoadHandler saveHandler){
registeredLoadHandler.put(clazz, saveHandler);
}
private ISaveHandler getRegisteredSaveHandler(Class<? extends Object> clazz){
ISaveHandler matchingHandler = registeredSaveHandler.get(clazz);
if (matchingHandler == null) {
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> interfaze : interfaces) {
matchingHandler = registeredSaveHandler.get(interfaze);
if (matchingHandler != null) {
break;
}
}
}
return matchingHandler;
}
@Override
public boolean save(Object documentSource) throws IllegalStateException{
ISaveHandler saveHandler = getRegisteredSaveHandler(documentSource.getClass());
if(saveHandler != null) {
return saveHandler.save(documentSource, this);
}
throw new IllegalStateException("No save handler for [" + documentSource + "]");
}
} |
package org.switchyard.quickstarts.camel.sql;
import static org.junit.Assert.assertEquals;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.switchyard.Exchange;
import org.switchyard.component.bean.config.model.BeanSwitchYardScanner;
import org.switchyard.component.test.mixins.cdi.CDIMixIn;
import org.switchyard.metadata.ServiceInterface;
import org.switchyard.metadata.java.JavaService;
import org.switchyard.quickstarts.camel.sql.binding.Greeting;
import org.switchyard.quickstarts.camel.sql.binding.GreetingService;
import org.switchyard.test.MockHandler;
import org.switchyard.test.SwitchYardTestCaseConfig;
import org.switchyard.test.SwitchYardTestKit;
import org.switchyard.transform.config.model.TransformSwitchYardScanner;
@SwitchYardTestCaseConfig(
config = SwitchYardTestCaseConfig.SWITCHYARD_XML,
mixins = {CDIMixIn.class},
scanners = {BeanSwitchYardScanner.class, TransformSwitchYardScanner.class}
)
public class CamelSqlRetrieveTest extends CamelSqlBindingTest {
private SwitchYardTestKit _testKit;
@Test
public void shouldRetrieveGreetings() throws Exception {
_testKit.removeService("GreetingService");
MockHandler handler = new MockHandler();
ServiceInterface metadata = JavaService.fromClass(GreetingService.class);
_testKit.getServiceDomain().registerService(_testKit.createQName("GreetingService"), metadata, handler);
PreparedStatement statement = connection.prepareStatement("INSERT INTO greetings (receiver, sender) VALUES (?,?)");
statement.setString(1, RECEIVER);
statement.setString(2, SENDER);
assertEquals(1, statement.executeUpdate());
List<Greeting> content = getContents(handler);
assertEquals(1, content.size());
assertEquals(SENDER, content.get(0).getSender());
assertEquals(RECEIVER, content.get(0).getReceiver());
}
// method which is capable to hold execution of test until some records pulled from database
private List<Greeting> getContents(MockHandler handler) {
handler.waitForOKMessage(); // first execution of poll done
List<Greeting> greetings = new ArrayList<Greeting>();
while (greetings.isEmpty()) {
for (Exchange exchange : handler.getMessages()) {
Greeting[] content = exchange.getMessage().getContent(Greeting[].class);
if (content != null) {
greetings.addAll(Arrays.asList(content));
}
}
}
return greetings;
}
} |
package edu.wustl.catissuecore.util.global;
import java.util.HashMap;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants
{
//Constants used for authentication module.
public static final String LOGIN = "login";
public static final String SESSION_DATA = "sessionData";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
public static final String DATE_PATTERN = "yyyy-MM-dd HH:mm aa";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
public static final String DATE_PATTERN_MM_DD_YYYY = "MM-dd-yyyy";
//Database constants.
public static final String MYSQL_DATE_PATTERN = "%m-%d-%Y";
//DAO Constants.
public static final int HIBERNATE_DAO = 1;
public static final int JDBC_DAO = 2;
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String VIEW = "view";
public static final String SEARCH = "search";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String ACCESS_DENIED = "access_denied";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String IDENTIFIER = "systemIdentifier";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String ERROR_DETAIL = "Error Detail";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String OPERATION = "operation";
public static final String ACTIVITY_STATUS = "activityStatus";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
//Simple Query Interface Lists
public static final String OBJECT_NAME_LIST = "objectNameList";
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String ATTRIBUTE_NAME_LIST = "attributeNameList";
public static final String ATTRIBUTE_CONDITION_LIST = "attributeConditionList";
//Constants for Storage Container.
public static final String STORAGE_CONTAINER_TYPE = "storageType";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers";
//event parameters lists
public static final String METHODLIST = "methodList";
public static final String HOURLIST = "hourList";
public static final String MINUTESLIST = "minutesList";
public static final String EMBEDDINGMEDIUMLIST = "embeddingMediumList";
public static final String PROCEDURELIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINERLIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATIONLIST = "fixationList";
public static final String FROMSITELIST="fromsiteList";
public static final String TOSITELIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGESTATUSLIST="storageStatusList";
public static final String CLINICALDIAGNOSISLIST="clinicalDiagnosisList";
public static final String HISTOLOGICALQUALITYLIST="histologicalQualityList";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String SHOW_STORAGE_CONTAINER_GRID_VIEW_ACTION = "/catissuecore/ShowStorageGridView.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "ReceivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "ReceivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
};
//Frame names in Query Results page.
public static final String DATA_VIEW_FRAME = "myframe1";
public static final String APPLET_VIEW_FRAME = "appletViewFrame";
//NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view).
public static final String DATA_VIEW_ACTION = "/catissuecore/DataView.do?nodeName=";
public static final String VIEW_TYPE = "viewType";
//TissueSite Tree View Constants.
public static final String PROPERTY_NAME = "propertyName";
//Constants for type of query results view.
public static final String SPREADSHEET_VIEW = "Spreadsheet View";
public static final String OBJECT_VIEW = "Object View";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
//Individual view Constants in DataViewAction.
public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList";
public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList";
public static final String SELECT_COLUMN_LIST = "selectColumnList";
//Tree Data Action
public static final String TREE_DATA_ACTION = "/catissuecore/Data.do";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTEDPROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int SIMPLE_QUERY_INTERFACE_ID = 40;
//Misc
public static final String SEPARATOR = " : ";
//Status message key Constants
public static final String STATUS_MESSAGE_KEY = "statusMessageKey";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_ACTIVE = "Active";
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
public static final String ACTIVITY_STATUS_CLOSED = "Closed";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Tree View Constants.
public static final String ROOT = "Root";
public static final String CATISSUE_CORE = "caTISSUE Core";
public static final String TISSUE_SITE = "Tissue Site";
public static final int TISSUE_SITE_TREE_ID = 1;
public static final int STORAGE_CONTAINER_TREE_ID = 2;
public static final int QUERY_RESULTS_TREE_ID = 3;
//Edit Object Constants.
public static final String TABLE_ALIAS_NAME = "aliasName";
public static final String FIELD_TYPE_VARCHAR = "varchar";
public static final String FIELD_TYPE_DATE = "date";
//Query Interface Results View Constants
public static final String PAGEOF = "pageOf";
public static final String QUERY = "query";
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
//For Tree Applet
public static final String PAGEOF_QUERY_RESULTS = "pageOfQueryResults";
public static final String PAGEOF_STORAGE_LOCATION = "pageOfStorageLocation";
public static final String PAGEOF_SPECIMEN = "pageOfSpecimen";
public static final String PAGEOF_TISSUE_SITE = "pageOfTissueSite";
//For Simple Query Interface and Edit.
public static final String PAGEOF_SIMPLE_QUERY_INTERFACE = "pageOfSimpleQueryInterface";
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table name.
public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "QueryTree.class";
public static final String APPLET_CODEBASE = "Applet";
public static final String TREE_APPLET_NAME = "treeApplet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
public static final String SELECT_OPTION = "-- Select --";
// public static final String[] TISSUE_SITE_ARRAY = {
// SELECT_OPTION,"Sex","male","female",
// "Tissue","kidney","Left kidney","Right kidney"
public static final String[] ATTRIBUTE_NAME_ARRAY = {
SELECT_OPTION
};
public static final String[] ATTRIBUTE_CONDITION_ARRAY = {
"=","<",">"
};
public static final String [] RECEIVEDMODEARRAY = {
SELECT_OPTION,
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENDER_ARRAY = {
SELECT_OPTION,
"Male",
"Female"
};
public static final String [] GENOTYPE_ARRAY = {
SELECT_OPTION,
"XX",
"XY"
};
public static final String [] RACEARRAY = {
SELECT_OPTION,
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
SELECT_OPTION,
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
public static final String [] STATEARRAY =
{
SELECT_OPTION,
"Alabama",//Alabama
"Alaska",//Alaska
"Arizona",//Arizona
"Arkansas",//Arkansas
"California",//California
"Colorado",//Colorado
"Connecticut",//Connecticut
"Delaware",//Delaware
"D.C.",
"Florida",//Florida
"Georgia",//Georgia
"Hawaii",//Hawaii
"Idaho",//Idaho
"Illinois",//Illinois
"Indiana",//Indiana
"Iowa",//Iowa
"Kansas",//Kansas
"Kentucky",//Kentucky
"Louisiana",//Louisiana
"Maine",//Maine
"Maryland",//Maryland
"Massachusetts",//Massachusetts
"Michigan",//Michigan
"Minnesota",//Minnesota
"Mississippi",//Mississippi
"Missouri",//Missouri
"Montana",//Montana
"Nebraska",//Nebraska
"Nevada",//Nevada
"New Hampshire",//New Hampshire
"New Jersey",//New Jersey
"New Mexico",//New Mexico
"New York",//New York
"North Carolina",//North Carolina
"North Dakota",//North Dakota
"Ohio",//Ohio
"Oklahoma",//Oklahoma
"Oregon",//Oregon
"Pennsylvania",//Pennsylvania
"Rhode Island",//Rhode Island
"South Carolina",//South Carolina
"South Dakota",//South Dakota
"Tennessee",//Tennessee
"Texas",//Texas
"Utah",//Utah
"Vermont",//Vermont
"Virginia",//Virginia
"Washington",//Washington
"West Virginia",//West Virginia
"Wisconsin",//Wisconsin
"Wyoming",//Wyoming
"Other",//Other
};
public static final String [] COUNTRYARRAY =
{
SELECT_OPTION,
"United States",
"Canada",
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island",
"Brazil",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",//Cameroon
"Cape Verde",//Cape Verde
"Cayman Islands",//Cayman Islands
"Central African Republic",//Central African Republic
"Chad",//Chad
"Chile",//Chile
"China",//China
"Christmas Island",//Christmas Island
"Cocos Islands",//Cocos Islands
"Colombia",//Colombia
"Comoros",//Comoros
"Congo",//Congo
"Cook Islands",//Cook Islands
"Costa Rica",//Costa Rica
"Cote D ivoire",//Cote D ivoire
"Croatia",//Croatia
"Cyprus",//Cyprus
"Czech Republic",//Czech Republic
"Denmark",//Denmark
"Djibouti",//Djibouti
"Dominica",//Dominica
"Dominican Republic",//Dominican Republic
"East Timor",//East Timor
"Ecuador",//Ecuador
"Egypt",//Egypt
"El Salvador",//El Salvador
"Equatorial Guinea",//Equatorial Guinea
"Eritrea",//Eritrea
"Estonia",//Estonia
"Ethiopia",//Ethiopia
"Falkland Islands",//Falkland Islands
"Faroe Islands",//Faroe Islands
"Fiji",//Fiji
"Finland",//Finland
"France",//France
"French Guiana",//French Guiana
"French Polynesia",//French Polynesia
"French S. Territories",//French S. Territories
"Gabon",//Gabon
"Gambia",//Gambia
"Georgia",//Georgia
"Germany",//Germany
"Ghana",//Ghana
"Gibraltar",//Gibraltar
"Greece",//Greece
"Greenland",//Greenland
"Grenada",//Grenada
"Guadeloupe",//Guadeloupe
"Guam",//Guam
"Guatemala",//Guatemala
"Guinea",//Guinea
"Guinea-Bissau",//Guinea-Bissau
"Guyana",//Guyana
"Haiti",//Haiti
"Honduras",//Honduras
"Hong Kong",//Hong Kong
"Hungary",//Hungary
"Iceland",//Iceland
"India",//India
"Indonesia",//Indonesia
"Iran",//Iran
"Iraq",//Iraq
"Ireland",//Ireland
"Israel",//Israel
"Italy",//Italy
"Jamaica",//Jamaica
"Japan",//Japan
"Jordan",//Jordan
"Kazakhstan",//Kazakhstan
"Kenya",//Kenya
"Kiribati",//Kiribati
"Korea",//Korea
"Kuwait",//Kuwait
"Kyrgyzstan",//Kyrgyzstan
"Laos",//Laos
"Latvia",//Latvia
"Lebanon",//Lebanon
"Lesotho",//Lesotho
"Liberia",//Liberia
"Liechtenstein",//Liechtenstein
"Lithuania",//Lithuania
"Luxembourg",//Luxembourg
"Macau",//Macau
"Macedonia",//Macedonia
"Madagascar",//Madagascar
"Malawi",//Malawi
"Malaysia",//Malaysia
"Maldives",//Maldives
"Mali",//Mali
"Malta",//Malta
"Marshall Islands",//Marshall Islands
"Martinique",//Martinique
"Mauritania",//Mauritania
"Mauritius",//Mauritius
"Mayotte",//Mayotte
"Mexico",//Mexico
"Micronesia",//Micronesia
"Moldova",//Moldova
"Monaco",//Monaco
"Mongolia",//Mongolia
"Montserrat",//Montserrat
"Morocco",//Morocco
"Mozambique",//Mozambique
"Myanmar",//Myanmar
"Namibia",//Namibia
"Nauru",//Nauru
"Nepal",//Nepal
"Netherlands",//Netherlands
"Netherlands Antilles",//Netherlands Antilles
"New Caledonia",//New Caledonia
"New Zealand",//New Zealand
"Nicaragua",//Nicaragua
"Niger",//Niger
"Nigeria",//Nigeria
"Niue",//Niue
"Norfolk Island",//Norfolk Island
"Norway",//Norway
"Oman",//Oman
"Pakistan",//Pakistan
"Palau",//Palau
"Panama",//Panama
"Papua New Guinea",//Papua New Guinea
"Paraguay",//Paraguay
"Peru",//Peru
"Philippines",//Philippines
"Pitcairn",//Pitcairn
"Poland",//Poland
"Portugal",//Portugal
"Puerto Rico",//Puerto Rico
"Qatar",//Qatar
"Reunion",//Reunion
"Romania",//Romania
"Russian Federation",//Russian Federation
"Rwanda",//Rwanda
"Saint Helena",//Saint Helena
"Saint Kitts and Nevis",//Saint Kitts and Nevis
"Saint Lucia",//Saint Lucia
"Saint Pierre",//Saint Pierre
"Saint Vincent",//Saint Vincent
"Samoa",//Samoa
"San Marino",//San Marino
"Sao Tome and Principe",//Sao Tome and Principe
"Saudi Arabia",//Saudi Arabia
"Senegal",//Senegal
"Seychelles",//Seychelles
"Sierra Leone",//Sierra Leone
"Singapore",//Singapore
"Slovakia",//Slovakia
"Slovenia",//Slovenia
"Solomon Islands",//Solomon Islands
"Somalia",//Somalia
"South Africa",//South Africa
"Spain",//Spain
"Sri Lanka",//Sri Lanka
"Sudan",//Sudan
"Suriname",//Suriname
"Swaziland",//Swaziland
"Sweden",//Sweden
"Switzerland",//Switzerland
"Syrian Arab Republic",//Syrian Arab Republic
"Taiwan",//Taiwan
"Tajikistan",//Tajikistan
"Tanzania",//Tanzania
"Thailand",//Thailand
"Togo",//Togo
"Tokelau",//Tokelau
"Tonga",//Tonga
"Trinidad and Tobago",//Trinidad and Tobago
"Tunisia",//Tunisia
"Turkey",//Turkey
"Turkmenistan",//Turkmenistan
"Turks and Caicos Islands",//Turks and Caicos Islands
"Tuvalu",//Tuvalu
"Uganda",//Uganda
"Ukraine",//Ukraine
"United Arab Emirates",//United Arab Emirates
"United Kingdom",//United Kingdom
"Uruguay",//Uruguay
"Uzbekistan",//Uzbekistan
"Vanuatu",//Vanuatu
"Vatican City State",//Vatican City State
"Venezuela",//Venezuela
"Vietnam",//Vietnam
"Virgin Islands",//Virgin Islands
"Wallis And Futuna Islands",//Wallis And Futuna Islands
"Western Sahara",//Western Sahara
"Yemen",//Yemen
"Yugoslavia",//Yugoslavia
"Zaire",//Zaire
"Zambia",//Zambia
"Zimbabwe",//Zimbabwe
};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] CANCER_RESEARCH_GROUP_VALUES = {
SELECT_OPTION,
"Siteman Cancer Center",
"Washington University"
};
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Disabled",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
//Only for showing UI.
public static final String [] INSTITUTE_VALUES = {
SELECT_OPTION,
"Washington University"
};
public static final String [] DEPARTMENT_VALUES = {
SELECT_OPTION,
"Cardiology",
"Pathology"
};
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
"Tissue",
"Fluid",
"Cell",
"Molecular"
};
public static final String [] SPECIMEN_SUB_TYPE_VALUES = {
SELECT_OPTION,
"Blood",
"Serum",
"Plasma",
};
public static final String [] TISSUE_SIDE_VALUES = {
SELECT_OPTION,
"Lavage",
"Metastatic Lesion",
};
public static final String [] PATHOLOGICAL_STATUS_VALUES = {
SELECT_OPTION,
"Primary Tumor",
"Metastatic Node",
"Non-Maglignant Tissue",
};
// public static final String [] BIOHAZARD_NAME_VALUES = {
// SELECT_OPTION,
public static final String [] BIOHAZARD_TYPE_VALUES = {
SELECT_OPTION,
"Radioactive"
};
public static final String [] ETHNICITY_VALUES = {
SELECT_OPTION,
"Ethnicity1",
"Ethnicity2",
"Ethnicity3",
};
public static final String [] PARTICIPANT_MEDICAL_RECORD_SOURCE_VALUES = {
SELECT_OPTION
};
public static final String [] STUDY_CALENDAR_EVENT_POINT_ARRAY = {
SELECT_OPTION,
"30","60","90"
};
public static final String [] CLINICAL_STATUS_ARRAY = {
SELECT_OPTION,
"Pre-Opt",
"Post-Opt"
};
public static final String [] SITE_TYPE_ARRAY = {
SELECT_OPTION,
"Collection",
"Laboratory",
"Repository", "Hospital"
};
public static final String [] BIOHAZARD_TYPE_ARRAY = {
SELECT_OPTION,
"Carcinogen",
"Infectious",
"Mutagen",
"Radioactive",
"Toxic"
};
public static final String [] HOURARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTESARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String [] METHODARRAY = {
SELECT_OPTION,
"LN2",
"Dry Ice",
"Iso pentane"
};
public static final String [] EMBEDDINGMEDIUMARRAY = {
SELECT_OPTION,
"Plastic",
"Glass",
};
public static final String [] ITEMARRAY = {
SELECT_OPTION,
"Item1",
"Item2",
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "mg";
public static final String [] PROCEDUREARRAY = {
SELECT_OPTION,
"Procedure 1",
"Procedure 2",
"Procedure 3"
};
public static final String [] CONTAINERARRAY = {
SELECT_OPTION,
"Container 1",
"Container 2",
"Container 3"
};
public static final String [] FIXATIONARRAY = {
SELECT_OPTION,
"FIXATION 1",
"FIXATION 2",
"FIXATION 3"
};
public static final HashMap STATIC_PROTECTION_GROUPS_FOR_OBJECT_TYPES = new HashMap();
public static final String CDE_CONF_FILE = "CDEConfig.xml";
public static final String CDE_NAME_TISSUE_SITE = "Tissue Site";
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String [] STORAGESTATUSARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
public static final String [] CLINICALDIAGNOSISARRAY = {
SELECT_OPTION,
"CLINICALDIAGNOSIS 1",
"CLINICALDIAGNOSIS 2",
"CLINICALDIAGNOSIS 3"
};
public static final String [] HISTOLOGICALQUALITYARRAY = {
SELECT_OPTION,
"GOOD",
"OK",
"DAMAGED"
};
// constants for Data required in query
private static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
} |
package us.blauha.wmsdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
public class MainActivity extends android.support.v4.app.FragmentActivity {
/* GOAL:
* Display a WMS overlay from OSGEO on top of a google base map.
* (The data is a white map with state boundaries.)
*
* Create a debugging Maps API Key and add it to the manifest.
*
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
TileProvider wmsTileProvider = TileProviderFactory.getOsgeoWmsTileProvider();
googleMap.addTileOverlay(new TileOverlayOptions().tileProvider(wmsTileProvider));
}
});
}
} |
package org.voovan.http.server;
import org.voovan.Global;
import org.voovan.http.HttpSessionParam;
import org.voovan.http.HttpRequestType;
import org.voovan.http.message.HttpParser;
import org.voovan.http.message.HttpStatic;
import org.voovan.http.message.Request;
import org.voovan.http.message.Response;
import org.voovan.http.server.context.WebContext;
import org.voovan.http.server.exception.RequestTooLarge;
import org.voovan.http.websocket.WebSocketFrame;
import org.voovan.network.IoFilter;
import org.voovan.network.IoSession;
import org.voovan.network.aio.AioSocket;
import org.voovan.tools.ByteBufferChannel;
import org.voovan.tools.TByteBuffer;
import org.voovan.tools.hashwheeltimer.HashWheelTask;
import org.voovan.tools.log.Logger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentSkipListMap;
public class WebServerFilter implements IoFilter {
private static ThreadLocal<ByteBufferChannel> THREAD_BUFFER_CHANNEL = ThreadLocal.withInitial(()->new ByteBufferChannel(TByteBuffer.EMPTY_BYTE_BUFFER));
private static ConcurrentSkipListMap<String, byte[]> RESPONSE_CACHE = new ConcurrentSkipListMap<String, byte[]>();
static {
Global.getHashWheelTimer().addTask(new HashWheelTask() {
@Override
public void run() {
RESPONSE_CACHE.clear();
}
}, 1000);
}
/**
* HttpResponseByteBuffer
*/
@Override
public Object encode(IoSession session, Object object) {
session.enabledMessageSpliter(true);
// Websocket
if (object instanceof HttpResponse) {
HttpResponse httpResponse = (HttpResponse)object;
try{
if(httpResponse.isAutoSend()) {
byte[] cacheBytes = null;
String cacheMark = httpResponse.getCacheMark();
if(cacheMark!=null) {
cacheBytes = RESPONSE_CACHE.get(cacheMark);
}
if(cacheBytes==null) {
httpResponse.send();
if(cacheMark!=null) {
ByteBufferChannel sendByteBufferChannel = session.getSendByteBufferChannel();
cacheBytes = new byte[session.getSendByteBufferChannel().size()];
sendByteBufferChannel.get(cacheBytes);
RESPONSE_CACHE.put(cacheMark, cacheBytes);
}
} else {
session.sendByBuffer(ByteBuffer.wrap(cacheBytes));
httpResponse.clear();
}
}
}catch(Exception e){
Logger.error(e);
}
return null;
} else if(object instanceof WebSocketFrame){
WebSocketFrame webSocketFrame = (WebSocketFrame)object;
return webSocketFrame.toByteBuffer();
}
return null;
}
/**
* ByteBuffer HttpRequest
*/
@Override
public Object decode(IoSession session, Object object) {
if(!session.isConnected()){
return null;
}
ByteBuffer byteBuffer = (ByteBuffer)object;
ByteBufferChannel byteBufferChannel = null;
if(byteBuffer.limit()==0){
session.enabledMessageSpliter(false);
byteBufferChannel = session.getReadByteBufferChannel();
} else {
// http pipeline , GET
byteBufferChannel = THREAD_BUFFER_CHANNEL.get();
byteBufferChannel.init(byteBuffer);
}
if (HttpRequestType.HTTP.equals(WebServerHandler.getAttribute(session, HttpSessionParam.TYPE))) {
Request request = null;
try {
if (object instanceof ByteBuffer) {
request = HttpParser.parseRequest(byteBufferChannel, session.socketContext().getReadTimeout(), WebContext.getWebServerConfig().getMaxRequestSize());
if(request!=null){
return request;
}else{
session.close();
}
} else {
return null;
}
} catch (IOException e) {
Response response = new Response();
response.protocol().setStatus(500);
if(e instanceof RequestTooLarge){
response.protocol().setStatus(413);
response.body().write("false");
}
try {
response.send(session);
((AioSocket)session.socketContext()).socketChannel().shutdownInput();
} catch (IOException e1) {
e1.printStackTrace();
}
session.close();
Logger.error("ParseRequest failed",e);
return null;
}
}
//Type WebSocket WebSocket , WebSocketFrame
else if(HttpRequestType.WEBSOCKET.equals(WebServerHandler.getAttribute(session, HttpSessionParam.TYPE))){
if (object instanceof ByteBuffer && byteBuffer.limit()!=0) {
WebSocketFrame webSocketFrame = WebSocketFrame.parse(byteBuffer);
if(webSocketFrame.getErrorCode()==0){
return webSocketFrame;
}else{
session.close();
}
} else {
return null;
}
} else {
session.close();
}
return null;
}
} |
package aima.gui.framework;
/**
* In this framework a graphical agent application consists at least of three
* parts: An {@link AgentAppEnvironmentView}, an {@link AgentAppFrame}, and an
* {@link AgentAppController}. This class plugs the three parts together. Note
* that no support for model creation is included here. Environments are used as
* models and may depend on current selector settings. So typically, the
* controller will be responsible for creating them (in method
* {@link AgentAppController#prepare(String)}) and making the view know them
* (by calling method
* {@link AgentAppEnvironmentView#setEnvironment(aima.core.agent.Environment)}).
* <p>
* The easiest way to create a new graphical agent application is to create
* subclasses of the three parts as needed, and then to create a subclass of
* this class and override the three factory methods.
* </p>
*
* @author Ruediger Lunde
*/
public class SimpleAgentApp {
/**
* Constructs an agent application and sets the application frame visible.
*/
public void startApplication() {
AgentAppFrame frame = constructApplicationFrame();
frame.centerPane.setDividerLocation(frame.centerPane.getResizeWeight());
frame.setVisible(true);
}
/**
* Creates all parts of an agent application and makes the parts know each
* other. Part construction is delegated to factory methods.
*/
public AgentAppFrame constructApplicationFrame() {
AgentAppEnvironmentView envView = createEnvironmentView();
AgentAppFrame frame = createFrame();
AgentAppController controller = createController();
frame.setEnvView(envView);
envView.setMessageLogger(frame.getMessageLogger());
frame.setController(controller);
controller.setFrame(frame);
frame.setDefaultSelection();
return frame;
}
/** Factory method, responsible for creating the environment view. */
public AgentAppEnvironmentView createEnvironmentView() {
return new EmptyEnvironmentView();
}
/**
* Factory method, responsible for creating the frame. This implementation
* shows how the {@code AgentAppFrame} can be configured with respect to the
* needs of the application even without creating a subclass.
*/
public AgentAppFrame createFrame() {
AgentAppFrame result = new AgentAppFrame();
result.setSelectors(new String[] { "XSelect", "YSelect" },
new String[] { "Select X", "Select Y" });
result.setSelectorItems("XSelect", new String[] { "X1 (Small)",
"X2 (Large)" }, 1);
result.setSelectorItems("YSelect",
new String[] { "Y=1", "Y=2", "Y=3" }, 0);
result.setTitle("Demo Agent Application");
result.setSplitPaneResizeWeight(0.5); // puts split bar in center
result.setSize(600, 400);
return result;
}
/** Factory method, responsible for creating the controller. */
public AgentAppController createController() {
return new DemoController();
}
// main method for testing
/**
* Starts a simple test frame application.
*/
public static void main(String args[]) {
new SimpleAgentApp().startApplication();
}
} |
package ch.epfl.sweng.project;
import android.support.test.espresso.UiController;
import android.support.test.espresso.ViewAction;
import android.support.test.espresso.contrib.DrawerActions;
import android.support.test.espresso.contrib.NavigationViewActions;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import com.example.android.multidex.ch.epfl.sweng.project.AppRunnest.R;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import ch.epfl.sweng.project.Activities.LoginActivity;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.contrib.DrawerMatchers.isOpen;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
@RunWith(AndroidJUnit4.class)
@LargeTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LoginTest {
@Rule
public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule<>(
LoginActivity.class);
/*
@Test
public void loginAndLogout() {
onView(withId(R.id.sign_in_button))
.perform(click());
onView(withId(R.id.fragment_container))
.check(matches(isDisplayed()));
onView(withId(R.id.drawer_layout))
.perform(DrawerActions.open());
onView(withId(R.id.drawer_layout)).check(matches(isOpen()));
onView(withId(R.id.nav_view)).perform(NavigationViewActions.navigateTo(R.id.nav_logout));
onView(withText("OK"))
.perform(click());
onView(withId(R.id.sign_in_button))
.check(matches(isDisplayed()));
}
*/
/*@Test
public void a() {
onView(withId(R.id.sign_in_button))
.perform(click());
onView(withId(R.id.fragment_container))
.check(matches(isDisplayed()));
}
@Test
public void b() {
onView(withId(R.id.drawer_layout))
.perform(DrawerActions.open());
onView(withId(R.id.drawer_layout)).check(matches(isOpen()));
}*/
} |
package com.allengarvey.annuncified;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.Settings;
import java.util.ArrayList;
import java.util.HashSet;
public class NotifyUtil{
// constants
public static final int receiverDefaultState = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
public static final int callReceiverDefaultState = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
public static final String contactNotificationsInfoSharedPreferencesName = "Annuncified contact notifications info shared preferences name";
public static final String groupNotificationsInfoSharedPreferencesName = "Annuncified group notifications info shared preferences name";
public static final String NOT_FOUND = "This is the string you receive if for some reason the value is not stored in shared preferences.";
// get shared preferences object helper methods
public static SharedPreferences getSharedPreferences(Context app){
return PreferenceManager.getDefaultSharedPreferences(app);
}
public static SharedPreferences getContactNotificationsInfoSharedPreferences(Context app){
return app.getSharedPreferences(contactNotificationsInfoSharedPreferencesName, Context.MODE_PRIVATE);
}
public static SharedPreferences getGroupNotificationsInfoSharedPreferences(Context app){
return app.getSharedPreferences(groupNotificationsInfoSharedPreferencesName, Context.MODE_PRIVATE);
}
// initialize app broadcast receivers based on settings
public static void startBroadcastReceiversBasedOnSettings(Context app){
NotifyUtil.setSMSReceiverState(app, NotifyUtil.getSMSReceiverStatePreferences(app));
NotifyUtil.setCallReceiverState(app, NotifyUtil.getCallReceiverStatePreferences(app));
}
// get and set methods for stored shared preferences values
//receiverState is PackageManager.COMPONENT_ENABLED_STATE_ENABLED
//or PackageManager.COMPONENT_ENABLED_STATE_DISABLED
public static void setSMSReceiverState(Context app, int receiverState){
ComponentName receiver = new ComponentName(app, SMSReceiver.class);
PackageManager pm = app.getPackageManager();
pm.setComponentEnabledSetting(receiver,
receiverState,
PackageManager.DONT_KILL_APP);
}
public static void setCallReceiverState(Context app, int receiverState){
ComponentName receiver = new ComponentName(app, CallReceiver.class);
PackageManager pm = app.getPackageManager();
pm.setComponentEnabledSetting(receiver,
receiverState,
PackageManager.DONT_KILL_APP);
}
public static boolean getIgnoreCallsFromNonContactsSetting(Context app){
return NotifyUtil.getSharedPreferences(app).getBoolean(app.getString(R.string.ignore_calls_from_non_contacts_key),false);
}
public static void setIgnoreCallsFromNonContactsSetting(Context app, boolean newSetting){
NotifyUtil.getSharedPreferences(app).edit().putBoolean(app.getString(R.string.ignore_calls_from_non_contacts_key), newSetting).apply();
}
public static boolean getIgnoreTextsFromNonContactsSetting(Context app){
return NotifyUtil.getSharedPreferences(app).getBoolean(app.getString(R.string.ignore_texts_from_non_contacts_key),false);
}
public static void setIgnoreTextsFromNonContactsSetting(Context app, boolean newSetting){
NotifyUtil.getSharedPreferences(app).edit().putBoolean(app.getString(R.string.ignore_texts_from_non_contacts_key), newSetting).apply();
}
public static boolean getStartAppOnBootSetting(Context app){
return NotifyUtil.getSharedPreferences(app).getBoolean(app.getString(R.string.boot_receiver_key),false);
}
public static void setStartAppOnBootSetting(Context app, boolean newSetting){
NotifyUtil.getSharedPreferences(app).edit().putBoolean(app.getString(R.string.boot_receiver_key), newSetting).apply();
}
public static int getSMSReceiverStatePreferences(Context app){
return getSharedPreferences(app).getInt(app.getString(R.string.receiver_state_shared_preferences_key), receiverDefaultState);
}
public static void setSMSReceiverStatePreferences(Context app, int newReceiverState){
getSharedPreferences(app).edit().putInt(app.getString(R.string.receiver_state_shared_preferences_key), newReceiverState).apply();
}
public static int getCallReceiverStatePreferences(Context app){
return getSharedPreferences(app).getInt(app.getString(R.string.call_receiver_key), callReceiverDefaultState);
}
public static void setCallReceiverStatePreferences(Context app, int newReceiverState){
getSharedPreferences(app).edit().putInt(app.getString(R.string.call_receiver_key), newReceiverState).apply();
}
// Get Ringtone Uris and ringtone name string helper methods
public static Uri getDefaultNotificationSound(Context app){
String defaultURIPath = getSharedPreferences(app).getString(app.getString(R.string.default_notification_sound_uri_shared_preferences_key), NOT_FOUND);
if(!defaultURIPath.equals(NOT_FOUND)){
return uriFromPath(defaultURIPath);
}
return Settings.System.DEFAULT_NOTIFICATION_URI;
}
public static void resetOriginalDefaultRingtonePath(Context app){
Uri originalUri = NotifyUtil.uriFromPath(getSharedPreferences(app).getString(app.getString(R.string.old_default_ringtone_uri_shared_preferences_key), Settings.System.DEFAULT_RINGTONE_URI.toString()));
RingtoneManager.setActualDefaultRingtoneUri(app, RingtoneManager.TYPE_RINGTONE, originalUri);
}
public static void saveOriginalDefaultRingtonePath(Context app){
String currentUriPath = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString();
if(currentUriPath != null){
getSharedPreferences(app).edit().putString(app.getString(R.string.old_default_ringtone_uri_shared_preferences_key), currentUriPath).apply();
}
}
public static String ringtoneNameFromUri(Context app, Uri ringtoneUri){
Ringtone ringtone = RingtoneManager.getRingtone(app, ringtoneUri);
return ringtone.getTitle(app);
}
public static Uri uriFromPath(String path){
return Uri.parse(path);
}
public static String notificationSoundPathFromContactsID(Context app, String contactID){
return getContactNotificationsInfoSharedPreferences(app).getString(contactID, NOT_FOUND);
}
public static void setNotificationSoundPathForContact(Context app, String contactID, String path){
getContactNotificationsInfoSharedPreferences(app).edit().putString(contactID, path).apply();
}
public static String notificationSoundPathFromGroupID(Context app, String groupID){
return getGroupNotificationsInfoSharedPreferences(app).getString(groupID, NOT_FOUND);
}
public static void setNotificationSoundPathForGroup(Context app, String groupID, String path){
getGroupNotificationsInfoSharedPreferences(app).edit().putString(groupID, path).apply();
}
public static String ringtoneSoundPathFromContactsID(Context app, String contactID){
Cursor c = app.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[] {ContactsContract.Data.CUSTOM_RINGTONE},
ContactsContract.Data.CONTACT_ID + "=?",
new String[] {contactID}, null);
if(c.moveToFirst()){
return c.getString(c.getColumnIndex(ContactsContract.Data.CUSTOM_RINGTONE));
}
return NOT_FOUND;
}
public static String getContactIdFromPhoneNumber(Context context, String number) {
String contactId = NOT_FOUND;
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup._ID};
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if (cursor.moveToFirst()) {
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
}
cursor.close();
return contactId;
}
public static ArrayList<String> getGroupIdsFromContactId(Context app, String contactId){
ArrayList<String> groupList = new ArrayList<>();
HashSet<String> visibleGroupIds = new HashSet<>();
Cursor groups = NotifyUtil.getGroupsDataCursor(app);
while(groups.moveToNext()){
String groupID = groups.getString(groups.getColumnIndex(ContactsContract.Groups._ID));
visibleGroupIds.add(groupID);
}
Cursor c = app.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[]{
ContactsContract.Data.CONTACT_ID,
ContactsContract.Data.DATA1
},
ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.Data.CONTACT_ID + " = " + contactId,
new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE}, null);
while (c.moveToNext()){
String groupId = c.getString(c.getColumnIndex(ContactsContract.Data.DATA1));
if(visibleGroupIds.contains(groupId)){
groupList.add(groupId);
}
}
c.close();
return groupList;
}
//Cursors
public static Cursor getGroupsDataCursor(Context app){
//confusingly 0 means that the group is visible
return app.getContentResolver().query(ContactsContract.Groups.CONTENT_URI, null,ContactsContract.Groups.GROUP_VISIBLE + " = 0",null, ContactsContract.Groups.TITLE + " ASC");
}
} |
package com.bigkoo.pickerviewdemo;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerviewdemo.bean.CardBean;
import com.bigkoo.pickerviewdemo.bean.ProvinceBean;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ArrayList<ProvinceBean> options1Items = new ArrayList<>();
private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
/* private ArrayList<ArrayList<ArrayList<IPickerViewData>>> options3Items = new ArrayList<>();*/
private Button btn_Time, btn_Options,btn_CustomOptions,btn_CustomTime,btn_no_linkage;
private TimePickerView pvTime,pvCustomTime;
private OptionsPickerView pvOptions,pvCustomOptions, pvNoLinkOptions;
private ArrayList<CardBean> cardItem = new ArrayList<>();
private ArrayList<String> food = new ArrayList<>();
private ArrayList<String> clothes = new ArrayList<>();
private ArrayList<String> computer = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//APP
initTimePicker();
initCustomTimePicker();
initOptionData();
initOptionPicker();
initCustomOptionPicker();
initNoLinkOptionsPicker();
btn_Time = (Button) findViewById(R.id.btn_Time);
btn_Options = (Button) findViewById(R.id.btn_Options);
btn_CustomOptions = (Button) findViewById(R.id.btn_CustomOptions);
btn_CustomTime = (Button) findViewById(R.id.btn_CustomTime);
btn_no_linkage = (Button) findViewById(R.id.btn_no_linkage);
btn_Time.setOnClickListener(this);
btn_Options.setOnClickListener(this);
btn_CustomOptions.setOnClickListener(this);
btn_CustomTime.setOnClickListener(this);
btn_no_linkage.setOnClickListener(this);
findViewById(R.id.btn_GotoJsonData).setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_Time && pvTime != null) {
// pvTime.setDate(Calendar.getInstance());
/* pvTime.show(); //show timePicker*/
pvTime.show(v);//view
} else if (v.getId() == R.id.btn_Options && pvOptions != null) {
pvOptions.show();
} else if (v.getId() == R.id.btn_CustomOptions && pvCustomOptions != null) {
pvCustomOptions.show();
}else if (v.getId() == R.id.btn_CustomTime && pvCustomTime != null) {
pvCustomTime.show();
}else if (v.getId() == R.id.btn_no_linkage&& pvNoLinkOptions !=null){
pvNoLinkOptions.show();
}else if (v.getId() == R.id.btn_GotoJsonData){
startActivity(new Intent(MainActivity.this,JsonDataActivity.class));
}
}
private void initNoLinkOptionsPicker() {
pvNoLinkOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int options2, int options3, View v) {
String str = "food:"+food.get(options1)
+"\nclothes:"+clothes.get(options2)
+"\ncomputer:"+computer.get(options3);
Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
}
}).build();
pvNoLinkOptions.setNPicker(food,clothes,computer);
}
private void initTimePicker() {
//(1900-2100)
//Calendar0-11,Calendarset,0-11
Calendar selectedDate = Calendar.getInstance();
Calendar startDate = Calendar.getInstance();
startDate.set(2013,0,23);
Calendar endDate = Calendar.getInstance();
endDate.set(2019,11,28);
pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {
// v,show() View showvnull
/*btn_Time.setText(getTime(date));*/
Button btn = (Button) v;
btn.setText(getTime(date));
}
})
.setType(TimePickerView.Type.YEAR_MONTH_DAY)
.setLabel("", "", "", "", "", "") // hide label
.setDividerColor(Color.DKGRAY)
.setContentSize(20)
.setDate(selectedDate)
.setRangDate(startDate,endDate)
.build();
}
private void initCustomTimePicker() {
/**
* @deprecated ()
*
* 1.id optionspicker timepicker
* demo
* 2.Calendar0-11,Calendarset,0-11
* (1900-2100)
*/
Calendar selectedDate = Calendar.getInstance();
Calendar startDate = Calendar.getInstance();
startDate.set(2014,1,23);
Calendar endDate = Calendar.getInstance();
endDate.set(2027,2,28);
pvCustomTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {
btn_CustomTime.setText(getTime(date));
}
})
/*.setDividerColor(Color.WHITE)//
.setTextColorCenter(Color.LTGRAY)//
.setLineSpacingMultiplier(1.6f)//
.setTitleBgColor(Color.DKGRAY)// Night mode
.setBgColor(Color.BLACK)// Night mode
.setSubmitColor(Color.WHITE)
.setCancelColor(Color.WHITE)*/
/*.gravity(Gravity.RIGHT)// default is center*/
.setDate(selectedDate)
.setRangDate(startDate,endDate)
.setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {
@Override
public void customLayout(View v) {
final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
tvSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomTime.returnData();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomTime.dismiss();
}
});
}
})
.setType(TimePickerView.Type.YEAR_MONTH_DAY)
.isCenterLabel(false) //labelfalseitemlabel
.setDividerColor(Color.RED)
.build();
}
private String getTime(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(date);
}
private void initOptionData() {
/**
* JavaBean IPickerViewData
* PickerViewgetPickerViewText
*/
getCardData();
getNoLinkData();
options1Items.add(new ProvinceBean(0,"","",""));
options1Items.add(new ProvinceBean(1,"","",""));
options1Items.add(new ProvinceBean(2,"","",""));
ArrayList<String> options2Items_01 = new ArrayList<>();
options2Items_01.add("");
options2Items_01.add("");
options2Items_01.add("");
options2Items_01.add("");
ArrayList<String> options2Items_02 = new ArrayList<>();
options2Items_02.add("");
options2Items_02.add("");
options2Items_02.add("");
options2Items_02.add("");
ArrayList<String> options2Items_03 = new ArrayList<>();
options2Items_03.add("");
options2Items_03.add("");
options2Items.add(options2Items_01);
options2Items.add(options2Items_02);
options2Items.add(options2Items_03);
}
private void initOptionPicker() {
// JsonDataActivity
pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int options2, int options3, View v) {
String tx = options1Items.get(options1).getPickerViewText()
+ options2Items.get(options1).get(options2)
/* + options3Items.get(options1).get(options2).get(options3).getPickerViewText()*/;
btn_Options.setText(tx);
}
})
.setTitleText("")
.setContentTextSize(20)
.setDividerColor(Color.GREEN)
.setSelectOptions(0,1)
.setBgColor(Color.BLACK)
.setTitleBgColor(Color.DKGRAY)
.setTitleColor(Color.LTGRAY)
.setCancelColor(Color.YELLOW)
.setSubmitColor(Color.YELLOW)
.setTextColorCenter(Color.LTGRAY)
.isCenterLabel(false) //labelfalseitemlabel
.setLabels("","","")
.build();
//pvOptions.setSelectOptions(1,1);
/*pvOptions.setPicker(options1Items);//*/
pvOptions.setPicker(options1Items, options2Items);
/*pvOptions.setPicker(options1Items, options2Items,options3Items);//*/
}
private void initCustomOptionPicker() {
// id optionspicker timepicker
// demo
pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int option2, int options3, View v) {
String tx = cardItem.get(options1).getPickerViewText();
btn_CustomOptions.setText(tx);
}
})
.setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
@Override
public void customLayout(View v) {
final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
final TextView tvAdd = (TextView) v.findViewById(R.id.tv_add);
ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
tvSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomOptions.returnData();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomOptions.dismiss();
}
});
tvAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getCardData();
pvCustomOptions.setPicker(cardItem);
}
});
}
})
.isDialog(true)
.build();
pvCustomOptions.setPicker(cardItem);
}
private void getCardData() {
for (int i = 0; i < 5; i++) {
cardItem.add(new CardBean(i, "No.ABC12345 " + i));
}
}
private void getNoLinkData() {
food.add("KFC");
food.add("MacDonald");
food.add("Pizza hut");
clothes.add("Nike");
clothes.add("Adidas");
clothes.add("Anima");
computer.add("ASUS");
computer.add("Lenovo");
computer.add("Apple");
computer.add("HP");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.