diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/powercrystals/minefactoryreloaded/gui/GuiFactoryPowered.java b/src/powercrystals/minefactoryreloaded/gui/GuiFactoryPowered.java index 5877dd41..0b96d8e6 100644 --- a/src/powercrystals/minefactoryreloaded/gui/GuiFactoryPowered.java +++ b/src/powercrystals/minefactoryreloaded/gui/GuiFactoryPowered.java @@ -1,123 +1,125 @@ package powercrystals.minefactoryreloaded.gui; import org.lwjgl.opengl.GL11; import powercrystals.minefactoryreloaded.MineFactoryReloadedCore; import powercrystals.minefactoryreloaded.core.TileEntityFactoryPowered; import net.minecraft.block.Block; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.item.Item; import net.minecraft.util.StatCollector; import net.minecraftforge.client.ForgeHooksClient; public class GuiFactoryPowered extends GuiContainer { protected TileEntityFactoryPowered _tePowered; private static final int _barSizeMax = 60; private static final int _barColorEnergy = (0) | (0) | (255 << 16) | (255 << 24); private static final int _barColorWork = (0) | (255 << 8) | (0 << 16) | (255 << 24); private static final int _barColorIdle = (255) | (0 << 8) | (0 << 16) | (255 << 24); public GuiFactoryPowered(ContainerFactoryPowered container, TileEntityFactoryPowered te) { super(container); _tePowered = te; } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { fontRenderer.drawString(_tePowered.getInvName(), 8, 6, 4210752); fontRenderer.drawString(StatCollector.translateToLocal("container.inventory"), 8, ySize - 96 + 2, 4210752); drawBars(); } @Override protected void drawGuiContainerBackgroundLayer(float gameTicks, int mouseX, int mouseY) { int texture; if(_tePowered.getTank() == null) { texture = mc.renderEngine.getTexture(MineFactoryReloadedCore.guiFolder + "noinv.png"); } else { texture = mc.renderEngine.getTexture(MineFactoryReloadedCore.guiFolder + "noinvtank.png"); } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.mc.renderEngine.bindTexture(texture); int x = (width - xSize) / 2; int y = (height - ySize) / 2; this.drawTexturedModalRect(x, y, 0, 0, xSize, ySize); } protected void drawBars() { int energySize = _tePowered.getEnergyStoredMax() > 0 ? _tePowered.getEnergyStored() * _barSizeMax / _tePowered.getEnergyStoredMax() : 0; int workSize = _tePowered.getWorkMax() > 0 ? _tePowered.getWorkDone() * _barSizeMax / _tePowered.getWorkMax() : 0; int idleSize = _tePowered.getIdleTicksMax() > 0 ? _tePowered.getIdleTicks() * _barSizeMax / _tePowered.getIdleTicksMax() : 0; drawRect(142, 75 - energySize, 150, 75, _barColorEnergy); drawRect(152, 75 - workSize, 160, 75, _barColorWork); drawRect(162, 75 - idleSize, 170, 75, _barColorIdle); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); if(_tePowered.getTank() != null && _tePowered.getTank().getLiquid() != null) { int tankSize = _tePowered.getTank().getLiquid().amount * _barSizeMax / _tePowered.getTank().getCapacity(); drawTank(_tePowered.getTank().getLiquid().itemID, _tePowered.getTank().getLiquid().itemMeta, tankSize); } } private void drawTank(int liquidId, int liquidMeta, int level) { int liquidTexture = 0; + int gaugeTexture = mc.renderEngine.getTexture(MineFactoryReloadedCore.guiFolder + "noinvtank.png"); if (liquidId <= 0) { return; } if (liquidId < Block.blocksList.length && Block.blocksList[liquidId] != null) { ForgeHooksClient.bindTexture(Block.blocksList[liquidId].getTextureFile(), 0); liquidTexture = Block.blocksList[liquidId].blockIndexInTexture; } else if (Item.itemsList[liquidId] != null) { ForgeHooksClient.bindTexture(Item.itemsList[liquidId].getTextureFile(), 0); liquidTexture = Item.itemsList[liquidId].getIconFromDamage(liquidMeta); } else { return; } int liquidTexY = liquidTexture / 16; int liquidTexX = liquidTexture - liquidTexY * 16; int vertOffset = 0; while(level > 0) { int x = 0; if (level > 16) { x = 16; level -= 16; } else { x = level; level = 0; } drawTexturedModalRect(124, 75 - x - vertOffset, liquidTexX * 16, liquidTexY * 16 + (16 - x), 16, 16 - (16 - x)); vertOffset = vertOffset + 16; + this.mc.renderEngine.bindTexture(gaugeTexture); this.drawTexturedModalRect(124, 15, 176, 0, 16, 60); } } }
false
true
private void drawTank(int liquidId, int liquidMeta, int level) { int liquidTexture = 0; if (liquidId <= 0) { return; } if (liquidId < Block.blocksList.length && Block.blocksList[liquidId] != null) { ForgeHooksClient.bindTexture(Block.blocksList[liquidId].getTextureFile(), 0); liquidTexture = Block.blocksList[liquidId].blockIndexInTexture; } else if (Item.itemsList[liquidId] != null) { ForgeHooksClient.bindTexture(Item.itemsList[liquidId].getTextureFile(), 0); liquidTexture = Item.itemsList[liquidId].getIconFromDamage(liquidMeta); } else { return; } int liquidTexY = liquidTexture / 16; int liquidTexX = liquidTexture - liquidTexY * 16; int vertOffset = 0; while(level > 0) { int x = 0; if (level > 16) { x = 16; level -= 16; } else { x = level; level = 0; } drawTexturedModalRect(124, 75 - x - vertOffset, liquidTexX * 16, liquidTexY * 16 + (16 - x), 16, 16 - (16 - x)); vertOffset = vertOffset + 16; this.drawTexturedModalRect(124, 15, 176, 0, 16, 60); } }
private void drawTank(int liquidId, int liquidMeta, int level) { int liquidTexture = 0; int gaugeTexture = mc.renderEngine.getTexture(MineFactoryReloadedCore.guiFolder + "noinvtank.png"); if (liquidId <= 0) { return; } if (liquidId < Block.blocksList.length && Block.blocksList[liquidId] != null) { ForgeHooksClient.bindTexture(Block.blocksList[liquidId].getTextureFile(), 0); liquidTexture = Block.blocksList[liquidId].blockIndexInTexture; } else if (Item.itemsList[liquidId] != null) { ForgeHooksClient.bindTexture(Item.itemsList[liquidId].getTextureFile(), 0); liquidTexture = Item.itemsList[liquidId].getIconFromDamage(liquidMeta); } else { return; } int liquidTexY = liquidTexture / 16; int liquidTexX = liquidTexture - liquidTexY * 16; int vertOffset = 0; while(level > 0) { int x = 0; if (level > 16) { x = 16; level -= 16; } else { x = level; level = 0; } drawTexturedModalRect(124, 75 - x - vertOffset, liquidTexX * 16, liquidTexY * 16 + (16 - x), 16, 16 - (16 - x)); vertOffset = vertOffset + 16; this.mc.renderEngine.bindTexture(gaugeTexture); this.drawTexturedModalRect(124, 15, 176, 0, 16, 60); } }
diff --git a/sub/source/net/sourceforge/texlipse/builder/LatexRunner.java b/sub/source/net/sourceforge/texlipse/builder/LatexRunner.java index 9ec3f09..75f3ff8 100644 --- a/sub/source/net/sourceforge/texlipse/builder/LatexRunner.java +++ b/sub/source/net/sourceforge/texlipse/builder/LatexRunner.java @@ -1,348 +1,364 @@ /* * $Id$ * * Copyright (c) 2004-2005 by the TeXlapse Team. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package net.sourceforge.texlipse.builder; import java.util.Stack; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.properties.TexlipseProperties; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; /** * Run the external latex program. * * @author Kimmo Karlsson * @author Oskar Ojala * @author Boris von Loesch */ public class LatexRunner extends AbstractProgramRunner { private Stack parsingStack; /** * Create a new ProgramRunner. */ public LatexRunner() { super(); this.parsingStack = new Stack(); } protected String getWindowsProgramName() { return "latex.exe"; } protected String getUnixProgramName() { return "latex"; } public String getDescription() { return "Latex program"; } public String getDefaultArguments() { return "-interaction=scrollmode --src-specials %input"; } public String getInputFormat() { return TexlipseProperties.INPUT_FORMAT_TEX; } /** * Used by the DviBuilder to figure out what the latex program produces. * * @return output file format (dvi) */ public String getOutputFormat() { return TexlipseProperties.OUTPUT_FORMAT_DVI; } protected String[] getQueryString() { return new String[] { "\nPlease type another input file name:" , "\nEnter file name:" }; } /** * Adds a problem marker * * @param error The error or warning string * @param causingSourceFile name of the sourcefile * @param linenr where the error occurs * @param severity * @param resource * @param layout true, if this is a layout warning */ private void addProblemMarker(String error, String causingSourceFile, int linenr, int severity, IResource resource, boolean layout) { IProject project = resource.getProject(); IContainer sourceDir = TexlipseProperties.getProjectSourceDir(project); IResource extResource = null; if (causingSourceFile != null) extResource = sourceDir.findMember(causingSourceFile); if (extResource == null) createMarker(resource, null, error + (causingSourceFile != null ? " (Occurance: " + causingSourceFile + ")" : ""), severity); else { if (linenr >= 0) { if (layout) createLayoutMarker(extResource, new Integer(linenr), error); else createMarker(extResource, new Integer(linenr), error, severity); } else createMarker(extResource, null, error, severity); } } /** * Parse the output of the LaTeX program. * * @param resource the input file that was processed * @param output the output of the external program * @return true, if error messages were found in the output, false otherwise */ protected boolean parseErrors(IResource resource, String output) { TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, null); TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, null); parsingStack.clear(); boolean errorsFound = false; boolean citeNotfound = false; StringTokenizer st = new StringTokenizer(output, "\r\n"); final Pattern LATEXERROR = Pattern.compile("^! LaTeX Error: (.*)$"); final Pattern TEXERROR = Pattern.compile("^!\\s+(.*)$"); final Pattern FULLBOX = Pattern.compile("^(?:Over|Under)full \\\\[hv]box .* at lines? (\\d+)-?-?(\\d+)?"); final Pattern WARNING = Pattern.compile("^.+[Ww]arning.*: (.*)$"); final Pattern ATLINE = Pattern.compile("^l\\.(\\d+)(.*)$"); final Pattern ATLINE2 = Pattern.compile(".* line (\\d+).*"); + final Pattern NOBIBFILE = Pattern.compile("^No file .+\\.bbl\\.$"); + final Pattern NOTOCFILE = Pattern.compile("^No file .+\\.toc\\.$"); String line; boolean hasProblem = false; String error = null; int severity = IMarker.SEVERITY_WARNING; int linenr = -1; String occurance = null; while (st.hasMoreTokens()) { line = st.nextToken(); line = line.replaceAll(" {2,}", " ").trim(); Matcher m = TEXERROR.matcher(line); if (m.matches() && line.toLowerCase().indexOf("warning") == -1) { if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; } hasProblem = true; errorsFound = true; severity = IMarker.SEVERITY_ERROR; occurance = determineSourceFile(); Matcher m2 = LATEXERROR.matcher(line); if (m2.matches()) { // LaTex error error = m2.group(1); String part2 = st.nextToken().trim(); if (Character.isLowerCase(part2.charAt(0))) { error += ' ' + part2; } updateParsedFile(part2); continue; } if (line.startsWith("! Undefined control sequence.")){ // Undefined Control Sequence error = "Undefined control sequence: "; continue; } m2 = WARNING.matcher(line); if (m2.matches()) severity = IMarker.SEVERITY_WARNING; error = m.group(1); continue; } m = WARNING.matcher(line); if (m.matches()){ if (hasProblem){ // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; } if (line.indexOf("Label(s) may have changed.") > -1) { // prepare to re-run latex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, "true"); continue; } else if (line.indexOf("There were undefined") > -1) { if (citeNotfound) { // prepare to run bibtex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, "true"); } continue; } // Ignore undefined references or citations because they are // found by the parser if (line.indexOf("Warning: Reference `") > -1) continue; if (line.indexOf("Warning: Citation `") > -1) { citeNotfound = true; continue; } severity = IMarker.SEVERITY_WARNING; occurance = determineSourceFile(); hasProblem = true; if (line.startsWith("LaTeX Warning: ") || line.indexOf("pdfTeX warning") != -1) { error = m.group(1); //Try to get the line number Matcher pM = ATLINE2.matcher(line); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } String nextLine = st.nextToken().replaceAll(" {2,}", " "); pM = ATLINE2.matcher(nextLine); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } updateParsedFile(nextLine); error += nextLine; if (linenr != -1) { addProblemMarker(line, occurance, linenr, severity, resource, false); hasProblem = false; linenr = -1; } continue; } else { error = m.group(1); //Try to get the line number Matcher pM = ATLINE2.matcher(line); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } continue; } } m = FULLBOX.matcher(line); if (m.matches()) { if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; } severity = IMarker.SEVERITY_WARNING; occurance = determineSourceFile(); error = line; linenr = Integer.parseInt(m.group(1)); addProblemMarker(line, occurance, linenr, severity, resource, true); hasProblem = false; linenr = -1; continue; } + m = NOBIBFILE.matcher(line); + if (m.matches()){ + // prepare to run bibtex + TexlipseProperties.setSessionProperty(resource.getProject(), + TexlipseProperties.SESSION_BIBTEX_RERUN, "true"); + continue; + } + m = NOTOCFILE.matcher(line); + if (m.matches()){ + // prepare to re-run latex + TexlipseProperties.setSessionProperty(resource.getProject(), + TexlipseProperties.SESSION_LATEX_RERUN, "true"); + continue; + } m = ATLINE.matcher(line); if (hasProblem && m.matches()) { linenr = Integer.parseInt(m.group(1)); String part2 = st.nextToken(); int index = line.indexOf(' '); if (index > -1) { error += " " + line.substring(index).trim() + " (followed by: " + part2.trim() + ")"; addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; continue; } } m = ATLINE2.matcher(line); if (hasProblem && m.matches()) { linenr = Integer.parseInt(m.group(1)); addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; continue; } updateParsedFile(line); } if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); } return errorsFound; } /** * Updates the stack that determines which file we are currently * parsing, so that errors can be annotated in the correct file. * * @param logLine A line from latex' output containing which file we are in */ private void updateParsedFile(String logLine) { if (logLine.indexOf('(') == -1 && logLine.indexOf(')') == -1) return; for (int i = 0; i < logLine.length(); i++) { if (logLine.charAt(i) == '(') { int j; for (j = i + 1; j < logLine.length() && isAllowedinName(logLine.charAt(j)); j++) ; parsingStack.push(logLine.substring(i, j).trim()); i = j - 1; } else if (logLine.charAt(i) == ')' && !parsingStack.isEmpty()) { parsingStack.pop(); } else if (logLine.charAt(i) == ')') { // There was a parsing error, this is very rare TexlipsePlugin.log("Error while parsing the LaTeX output. " + "Please consult the console output", null); } } } /** * Check if the character is allowed in a filename * @param c the character * @return true if the character is legal */ private boolean isAllowedinName(char c) { if (c == '(' || c == ')' || c == '[') return false; else return true; } /** * Determines the source file we are currently parsing. * * @return The filename or null if no file could be determined */ private String determineSourceFile() { if (!parsingStack.empty()) return ((String) parsingStack.peek()).substring(1); else return null; } }
false
true
protected boolean parseErrors(IResource resource, String output) { TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, null); TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, null); parsingStack.clear(); boolean errorsFound = false; boolean citeNotfound = false; StringTokenizer st = new StringTokenizer(output, "\r\n"); final Pattern LATEXERROR = Pattern.compile("^! LaTeX Error: (.*)$"); final Pattern TEXERROR = Pattern.compile("^!\\s+(.*)$"); final Pattern FULLBOX = Pattern.compile("^(?:Over|Under)full \\\\[hv]box .* at lines? (\\d+)-?-?(\\d+)?"); final Pattern WARNING = Pattern.compile("^.+[Ww]arning.*: (.*)$"); final Pattern ATLINE = Pattern.compile("^l\\.(\\d+)(.*)$"); final Pattern ATLINE2 = Pattern.compile(".* line (\\d+).*"); String line; boolean hasProblem = false; String error = null; int severity = IMarker.SEVERITY_WARNING; int linenr = -1; String occurance = null; while (st.hasMoreTokens()) { line = st.nextToken(); line = line.replaceAll(" {2,}", " ").trim(); Matcher m = TEXERROR.matcher(line); if (m.matches() && line.toLowerCase().indexOf("warning") == -1) { if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; } hasProblem = true; errorsFound = true; severity = IMarker.SEVERITY_ERROR; occurance = determineSourceFile(); Matcher m2 = LATEXERROR.matcher(line); if (m2.matches()) { // LaTex error error = m2.group(1); String part2 = st.nextToken().trim(); if (Character.isLowerCase(part2.charAt(0))) { error += ' ' + part2; } updateParsedFile(part2); continue; } if (line.startsWith("! Undefined control sequence.")){ // Undefined Control Sequence error = "Undefined control sequence: "; continue; } m2 = WARNING.matcher(line); if (m2.matches()) severity = IMarker.SEVERITY_WARNING; error = m.group(1); continue; } m = WARNING.matcher(line); if (m.matches()){ if (hasProblem){ // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; } if (line.indexOf("Label(s) may have changed.") > -1) { // prepare to re-run latex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, "true"); continue; } else if (line.indexOf("There were undefined") > -1) { if (citeNotfound) { // prepare to run bibtex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, "true"); } continue; } // Ignore undefined references or citations because they are // found by the parser if (line.indexOf("Warning: Reference `") > -1) continue; if (line.indexOf("Warning: Citation `") > -1) { citeNotfound = true; continue; } severity = IMarker.SEVERITY_WARNING; occurance = determineSourceFile(); hasProblem = true; if (line.startsWith("LaTeX Warning: ") || line.indexOf("pdfTeX warning") != -1) { error = m.group(1); //Try to get the line number Matcher pM = ATLINE2.matcher(line); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } String nextLine = st.nextToken().replaceAll(" {2,}", " "); pM = ATLINE2.matcher(nextLine); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } updateParsedFile(nextLine); error += nextLine; if (linenr != -1) { addProblemMarker(line, occurance, linenr, severity, resource, false); hasProblem = false; linenr = -1; } continue; } else { error = m.group(1); //Try to get the line number Matcher pM = ATLINE2.matcher(line); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } continue; } } m = FULLBOX.matcher(line); if (m.matches()) { if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; } severity = IMarker.SEVERITY_WARNING; occurance = determineSourceFile(); error = line; linenr = Integer.parseInt(m.group(1)); addProblemMarker(line, occurance, linenr, severity, resource, true); hasProblem = false; linenr = -1; continue; } m = ATLINE.matcher(line); if (hasProblem && m.matches()) { linenr = Integer.parseInt(m.group(1)); String part2 = st.nextToken(); int index = line.indexOf(' '); if (index > -1) { error += " " + line.substring(index).trim() + " (followed by: " + part2.trim() + ")"; addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; continue; } } m = ATLINE2.matcher(line); if (hasProblem && m.matches()) { linenr = Integer.parseInt(m.group(1)); addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; continue; } updateParsedFile(line); } if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); } return errorsFound; }
protected boolean parseErrors(IResource resource, String output) { TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, null); TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, null); parsingStack.clear(); boolean errorsFound = false; boolean citeNotfound = false; StringTokenizer st = new StringTokenizer(output, "\r\n"); final Pattern LATEXERROR = Pattern.compile("^! LaTeX Error: (.*)$"); final Pattern TEXERROR = Pattern.compile("^!\\s+(.*)$"); final Pattern FULLBOX = Pattern.compile("^(?:Over|Under)full \\\\[hv]box .* at lines? (\\d+)-?-?(\\d+)?"); final Pattern WARNING = Pattern.compile("^.+[Ww]arning.*: (.*)$"); final Pattern ATLINE = Pattern.compile("^l\\.(\\d+)(.*)$"); final Pattern ATLINE2 = Pattern.compile(".* line (\\d+).*"); final Pattern NOBIBFILE = Pattern.compile("^No file .+\\.bbl\\.$"); final Pattern NOTOCFILE = Pattern.compile("^No file .+\\.toc\\.$"); String line; boolean hasProblem = false; String error = null; int severity = IMarker.SEVERITY_WARNING; int linenr = -1; String occurance = null; while (st.hasMoreTokens()) { line = st.nextToken(); line = line.replaceAll(" {2,}", " ").trim(); Matcher m = TEXERROR.matcher(line); if (m.matches() && line.toLowerCase().indexOf("warning") == -1) { if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; } hasProblem = true; errorsFound = true; severity = IMarker.SEVERITY_ERROR; occurance = determineSourceFile(); Matcher m2 = LATEXERROR.matcher(line); if (m2.matches()) { // LaTex error error = m2.group(1); String part2 = st.nextToken().trim(); if (Character.isLowerCase(part2.charAt(0))) { error += ' ' + part2; } updateParsedFile(part2); continue; } if (line.startsWith("! Undefined control sequence.")){ // Undefined Control Sequence error = "Undefined control sequence: "; continue; } m2 = WARNING.matcher(line); if (m2.matches()) severity = IMarker.SEVERITY_WARNING; error = m.group(1); continue; } m = WARNING.matcher(line); if (m.matches()){ if (hasProblem){ // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; } if (line.indexOf("Label(s) may have changed.") > -1) { // prepare to re-run latex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, "true"); continue; } else if (line.indexOf("There were undefined") > -1) { if (citeNotfound) { // prepare to run bibtex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, "true"); } continue; } // Ignore undefined references or citations because they are // found by the parser if (line.indexOf("Warning: Reference `") > -1) continue; if (line.indexOf("Warning: Citation `") > -1) { citeNotfound = true; continue; } severity = IMarker.SEVERITY_WARNING; occurance = determineSourceFile(); hasProblem = true; if (line.startsWith("LaTeX Warning: ") || line.indexOf("pdfTeX warning") != -1) { error = m.group(1); //Try to get the line number Matcher pM = ATLINE2.matcher(line); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } String nextLine = st.nextToken().replaceAll(" {2,}", " "); pM = ATLINE2.matcher(nextLine); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } updateParsedFile(nextLine); error += nextLine; if (linenr != -1) { addProblemMarker(line, occurance, linenr, severity, resource, false); hasProblem = false; linenr = -1; } continue; } else { error = m.group(1); //Try to get the line number Matcher pM = ATLINE2.matcher(line); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } continue; } } m = FULLBOX.matcher(line); if (m.matches()) { if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; } severity = IMarker.SEVERITY_WARNING; occurance = determineSourceFile(); error = line; linenr = Integer.parseInt(m.group(1)); addProblemMarker(line, occurance, linenr, severity, resource, true); hasProblem = false; linenr = -1; continue; } m = NOBIBFILE.matcher(line); if (m.matches()){ // prepare to run bibtex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, "true"); continue; } m = NOTOCFILE.matcher(line); if (m.matches()){ // prepare to re-run latex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, "true"); continue; } m = ATLINE.matcher(line); if (hasProblem && m.matches()) { linenr = Integer.parseInt(m.group(1)); String part2 = st.nextToken(); int index = line.indexOf(' '); if (index > -1) { error += " " + line.substring(index).trim() + " (followed by: " + part2.trim() + ")"; addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; continue; } } m = ATLINE2.matcher(line); if (hasProblem && m.matches()) { linenr = Integer.parseInt(m.group(1)); addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; continue; } updateParsedFile(line); } if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); } return errorsFound; }
diff --git a/gnu/testlet/java/text/RuleBasedCollator/jdk11.java b/gnu/testlet/java/text/RuleBasedCollator/jdk11.java index c3692364..c7d5bab6 100644 --- a/gnu/testlet/java/text/RuleBasedCollator/jdk11.java +++ b/gnu/testlet/java/text/RuleBasedCollator/jdk11.java @@ -1,539 +1,539 @@ /************************************************************************* /* Tests for java.text.RuleBasedCollator /* /* Copyright (c) 2003 Stephen C. Crawley ([email protected]) /* /* This program is free software; you can redistribute it and/or modify /* it under the terms of the GNU General Public License as published /* by the Free Software Foundation, either version 2 of the License, or /* (at your option) any later version. /* /* This program is distributed in the hope that it will be useful, but /* WITHOUT ANY WARRANTY; without even the implied warranty of /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /* GNU General Public License for more details. /* /* You should have received a copy of the GNU General Public License /* along with this program; if not, write to the Free Software Foundation /* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 USA /*************************************************************************/ // Tags: JDK1.1 package gnu.testlet.java.text.RuleBasedCollator; import gnu.testlet.Testlet; import gnu.testlet.TestHarness; import java.text.RuleBasedCollator; import java.text.Collator; import java.text.ParseException; public class jdk11 implements Testlet { // These are the rule strings returned by calling getRules() on the // collators for various JDK 1.4.0 Locales private final String EN_US_RULES = "='\u200b'=\u200c=\u200d=\u200e=\u200f=\u0000=\u0001=\u0002=\u0003" + "=\u0004=\u0005=\u0006=\u0007=\u0008='\t'='\u000b'=\u000e" + "=\u000f='\u0010'=\u0011=\u0012=\u0013=\u0014=\u0015=\u0016" + "=\u0017=\u0018=\u0019=\u001a=\u001b=\u001c=\u001d=\u001e=\u001f" + "=\u007f=\u0080=\u0081=\u0082=\u0083=\u0084=\u0085=\u0086=\u0087" + "=\u0088=\u0089=\u008a=\u008b=\u008c=\u008d=\u008e=\u008f=\u0090" + "=\u0091=\u0092=\u0093=\u0094=\u0095=\u0096=\u0097=\u0098=\u0099" + "=\u009a=\u009b=\u009c=\u009d=\u009e=\u009f;' ';'\u00a0';'\u2000'" + ";'\u2001';'\u2002';'\u2003';'\u2004';'\u2005';'\u2006';'\u2007'" + ";'\u2008';'\u2009';'\u200a';'\u3000';'\ufeff';'\r';'\t'" + ";'\n';'\f';'\u000b';\u0301;\u0300;\u0306;\u0302;\u030c;\u030a" + ";\u030d;\u0308;\u030b;\u0303;\u0307;\u0304;\u0337;\u0327;\u0328" + ";\u0323;\u0332;\u0305;\u0309;\u030e;\u030f;\u0310;\u0311;\u0312" + ";\u0313;\u0314;\u0315;\u0316;\u0317;\u0318;\u0319;\u031a;\u031b" + ";\u031c;\u031d;\u031e;\u031f;\u0320;\u0321;\u0322;\u0324;\u0325" + ";\u0326;\u0329;\u032a;\u032b;\u032c;\u032d;\u032e;\u032f;\u0330" + ";\u0331;\u0333;\u0334;\u0335;\u0336;\u0338;\u0339;\u033a;\u033b" + ";\u033c;\u033d;\u033e;\u033f;\u0342;\u0344;\u0345;\u0360;\u0361" + ";\u0483;\u0484;\u0485;\u0486;\u20d0;\u20d1;\u20d2;\u20d3;\u20d4" + ";\u20d5;\u20d6;\u20d7;\u20d8;\u20d9;\u20da;\u20db;\u20dc;\u20dd" + ";\u20de;\u20df;\u20e0;\u20e1,'-';\u00ad;\u2010;\u2011;\u2012;\u2013" + ";\u2014;\u2015;\u2212<'_'<\u00af<','<';'<':'<'!'<\u00a1<'?'<\u00bf" + "<'/'<'.'<\u00b4<'`'<'^'<\u00a8<'~'<\u00b7<\u00b8<'''<'\"'<\u00ab" + "<\u00bb<'('<')'<'['<']'<'{'<'}'<\u00a7<\u00b6<\u00a9<\u00ae<'@'" + "<\u00a4<\u0e3f<\u00a2<\u20a1<\u20a2<'$'<\u20ab<\u20ac<\u20a3<\u20a4" + "<\u20a5<\u20a6<\u20a7<\u00a3<\u20a8<\u20aa<\u20a9<\u00a5<'*'<'\\'<'&'" + "<'#'<'%'<'+'<\u00b1<\u00f7<\u00d7<'<'<'='<'>'<\u00ac<'|'<\u00a6" + "<\u00b0<\u00b5<0<1<2<3<4<5<6<7<8<9<\u00bc<\u00bd<\u00be<a,A<b,B<c,C" + "<d,D<\u00f0,\u00d0<e,E<f,F<g,G<h,H<i,I<j,J<k,K<l,L<m,M<n,N<o,O<p,P" + "<q,Q<r,R<s, S & SS,\u00df<t,T& TH, \u00de &TH, \u00fe <u,U<v,V<w,W" + "<x,X<y,Y<z,Z&AE,\u00c6&AE,\u00e6&OE,\u0152&OE,\u0153"; private final String FR_CA_RULES = "='\u200b'=\u200c=\u200d=\u200e=\u200f=\u0000=\u0001=\u0002=\u0003" + "=\u0004=\u0005=\u0006=\u0007=\u0008='\t'='\u000b'=\u000e=\u000f" + "='\u0010'=\u0011=\u0012=\u0013=\u0014=\u0015=\u0016=\u0017=\u0018" + "=\u0019=\u001a=\u001b=\u001c=\u001d=\u001e=\u001f=\u007f=\u0080=\u0081" + "=\u0082=\u0083=\u0084=\u0085=\u0086=\u0087=\u0088=\u0089=\u008a=\u008b" + "=\u008c=\u008d=\u008e=\u008f=\u0090=\u0091=\u0092=\u0093=\u0094=\u0095" + "=\u0096=\u0097=\u0098=\u0099=\u009a=\u009b=\u009c=\u009d=\u009e=\u009f" + ";' ';'\u00a0';'\u2000';'\u2001';'\u2002';'\u2003';'\u2004';'\u2005'" + ";'\u2006';'\u2007';'\u2008';'\u2009';'\u200a';'\u3000';'\ufeff';'\r'" + ";'\t';'\n';'\f';'\u000b';\u0301;\u0300;\u0306;\u0302;\u030c;\u030a" + ";\u030d;\u0308;\u030b;\u0303;\u0307;\u0304;\u0337;\u0327;\u0328" + ";\u0323;\u0332;\u0305;\u0309;\u030e;\u030f;\u0310;\u0311;\u0312" + ";\u0313;\u0314;\u0315;\u0316;\u0317;\u0318;\u0319;\u031a;\u031b" + ";\u031c;\u031d;\u031e;\u031f;\u0320;\u0321;\u0322;\u0324;\u0325" + ";\u0326;\u0329;\u032a;\u032b;\u032c;\u032d;\u032e;\u032f;\u0330" + ";\u0331;\u0333;\u0334;\u0335;\u0336;\u0338;\u0339;\u033a;\u033b" + ";\u033c;\u033d;\u033e;\u033f;\u0342;\u0344;\u0345;\u0360;\u0361" + ";\u0483;\u0484;\u0485;\u0486;\u20d0;\u20d1;\u20d2;\u20d3;\u20d4" + ";\u20d5;\u20d6;\u20d7;\u20d8;\u20d9;\u20da;\u20db;\u20dc;\u20dd" + ";\u20de;\u20df;\u20e0;\u20e1,'-';\u00ad;\u2010;\u2011;\u2012;\u2013" + ";\u2014;\u2015;\u2212<'_'<\u00af<','<';'<':'<'!'<\u00a1<'?'<\u00bf" + "<'/'<'.'<\u00b4<'`'<'^'<\u00a8<'~'<\u00b7<\u00b8<'''<'\"'<\u00ab" + "<\u00bb<'('<')'<'['<']'<'{'<'}'<\u00a7<\u00b6<\u00a9<\u00ae<'@'" + "<\u00a4<\u0e3f<\u00a2<\u20a1<\u20a2<'$'<\u20ab<\u20ac<\u20a3<\u20a4" + "<\u20a5<\u20a6<\u20a7<\u00a3<\u20a8<\u20aa<\u20a9<\u00a5<'*'<'\\'<'&'" + "<'#'<'%'<'+'<\u00b1<\u00f7<\u00d7<'<'<'='<'>'<\u00ac<'|'<\u00a6" + "<\u00b0<\u00b5<0<1<2<3<4<5<6<7<8<9<\u00bc<\u00bd<\u00be<a,A<b,B<c,C" + "<d,D<\u00f0,\u00d0<e,E<f,F<g,G<h,H<i,I<j,J<k,K<l,L<m,M<n,N<o,O<p,P" + "<q,Q<r,R<s, S & SS,\u00df<t,T& TH, \u00de &TH, \u00fe <u,U<v,V<w,W" + "<x,X<y,Y<z,Z&AE,\u00c6&AE,\u00e6&OE,\u0152&OE,\u0153@"; private TestHarness harness; private void constructorTests() { harness.checkPoint("constructor rule parsing"); RuleBasedCollator r; final String[] GOOD_RULES = { // Examples from the Sun javadocs "< a < b < c < d", ("< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J < k,K< l,L< m,M" + "< n,N< o,O< p,P< q,Q< r,R< s,S< t,T < u,U< v,V< w,W< x,X< y,Y< z,Z " + "< \u00E5=a\u030A,\u00C5=A\u030A ;aa,AA< \u00E6,\u00C6< \u00F8,\u00D8"), ("=\u0301;\u0300;\u0302;\u0308;\u0327;\u0303;\u0304;\u0305" + ";\u0306;\u0307;\u0309;\u030A;\u030B;\u030C;\u030D;\u030E" + ";\u030F;\u0310;\u0311;\u0312< a , A ; ae, AE ; \u00e6 , \u00c6" + "< b , B < c, C < e, E & C < d, D & \u0300 ; \u0308 ; \u0302"), // Real collation rules EN_US_RULES, FR_CA_RULES, // Cases involving non-significant white-space "=A ", "=A\t", "=A\n", "=A B", "=A\tB", "=A\nB", "= A", "=\tA", "=\nA", " =A", "\t=A", "\n=A", // Dodgy cases that JDKs accept " ", "='\n''\n'", "='\n'\n'\n'", // Dodgy cases with unbalanced quotes. JDKs allow these (though a // couple result in IndexOutOfBoundsExceptions). However, the spec // does not say what they mean. "='", /* <- JDK 1.4.0 exception */ "=' ", "='=A", "='=A'", "=''", "='' ","=''=A", "=''=A'", "=''''", /* <- JDK 1.4.0 exception */ "=''''=A", "=''''=A'", }; for (int i = 0; i < GOOD_RULES.length; i++) { try { r = new RuleBasedCollator(GOOD_RULES[i]); harness.check(true); } catch (ParseException ex) { harness.debug(ex); harness.debug("unexpected ParseException (offset is " + ex.getErrorOffset() + ")"); harness.check(false); } catch (Throwable ex) { harness.debug(ex); harness.check(false); } } try { r = new RuleBasedCollator(null); harness.check(false); } catch (ParseException ex) { harness.check(false); } catch (NullPointerException ex) { harness.check(true); } harness.checkPoint("constructor rule parsing errors"); final String[] BAD_RULES = { // Empty rule list "", // No relation "A", // No text following relation "=", "<", ";", ",", // Special chars should be quoted "=\n", "=#", "==", }; for (int i = 0; i < BAD_RULES.length; i++) { try { r = new RuleBasedCollator(BAD_RULES[i]); harness.check(false); } catch (ParseException ex) { harness.check(true); } catch (Throwable ex) { harness.debug(ex); harness.check(false); } } } private void doComparisons(RuleBasedCollator r, String[][] tests) { for (int i = 0; i < tests.length; i++) { int res = r.compare(tests[i][0], tests[i][1]); if (res < 0) { harness.check(tests[i][2].equals("<")); } else if (res == 0) { harness.check(tests[i][2].equals("=")); } else { harness.check(tests[i][2].equals(">")); } } } private void ignoreTests() { harness.checkPoint("ignorable characters"); final String TEST_RULES = "=Z<a,A<b,B<c,C"; final String[][] TESTS = { {"abc", "ABC", "<"}, {"abc", "abc", "="}, {"Abc", "abc", ">"}, {"aZbZc", "abc", "="}, {"aZbZc", "aZbZc", "="}, {"abc", "aZbZc", "="}, {"aZbZc", "ABC", "<"}, {"Z", "Z", "="}, {"Abc", "aZbZc", ">"}, }; try { RuleBasedCollator r = new RuleBasedCollator(TEST_RULES); doComparisons(r, TESTS); } catch (ParseException ex) { harness.debug(ex); harness.fail("ignorable characters: ParseException (offset is " + ex.getErrorOffset() + ")"); } } private void oneCharTests() { checkStrengths(); harness.checkPoint("single character ordering"); final String TEST_RULES = "<a;A=0<b,B=1<c;C,d=2"; final String[][][] TESTS = { { // PRIMARY {"", "", "="}, {"abc", "abc", "="}, {"abc", "ab", ">"}, {"ab", "abc", "<"}, {"abc", "Abc", "="}, {"abc", "aBc", "="}, {"abc", "abd", "="}, {"abc", "abC", "="}, {"abC", "abd", "="}, {"Abc", "abc", "="}, {"aBc", "abc", "="}, {"abd", "abc", "="}, {"abC", "abc", "="}, {"abd", "abC", "="}, {"abc", "012", "="}, {"ABd", "012", "="}, {"abc", "xyz", "<"}, {"xyz", "abc", ">"}, {"pqr", "xyz", "<"}, /* While the Sun Javadoc simply says that unmentioned characters appear at the end of the collation, the Sun JDK impl'ns appears to order them by raw char value. */ }, { // SECONDARY {"", "", "="}, {"abc", "abc", "="}, {"abc", "ab", ">"}, {"ab", "abc", "<"}, {"abc", "Abc", "<"}, {"abc", "aBc", "="}, {"abc", "abd", "<"}, {"abc", "abC", "<"}, {"abC", "abd", "="}, {"Abc", "abc", ">"}, {"aBc", "abc", "="}, {"abd", "abc", ">"}, {"abC", "abc", ">"}, {"abd", "abC", "="}, {"abc", "012", "<"}, {"ABd", "012", "="}, {"abc", "xyz", "<"}, {"xyz", "abc", ">"}, {"pqr", "xyz", "<"}, }, { // TERTIARY {"", "", "="}, {"abc", "abc", "="}, {"abc", "ab", ">"}, {"ab", "abc", "<"}, {"abc", "Abc", "<"}, {"abc", "aBc", "<"}, {"abc", "abd", "<"}, {"abc", "abC", "<"}, {"abC", "abd", "<"}, {"Abc", "abc", ">"}, {"aBc", "abc", ">"}, {"abd", "abc", ">"}, {"abC", "abc", ">"}, {"abd", "abC", ">"}, {"abc", "012", "<"}, {"ABd", "012", "="}, {"abc", "xyz", "<"}, {"xyz", "abc", ">"}, {"pqr", "xyz", "<"}, }, { // IDENTICAL {"", "", "="}, {"abc", "abc", "="}, {"abc", "ab", ">"}, {"ab", "abc", "<"}, {"abc", "Abc", "<"}, {"abc", "aBc", "<"}, {"abc", "abd", "<"}, {"abc", "abC", "<"}, {"abC", "abd", "<"}, {"Abc", "abc", ">"}, {"aBc", "abc", ">"}, {"abd", "abc", ">"}, {"abC", "abc", ">"}, {"abd", "abC", ">"}, {"abc", "012", "<"}, {"ABd", "012", ">"}, /* It appears that Sun JDKs fall back on the raw character values when characters are defined as equivalent by the rules. */ {"abc", "xyz", "<"}, {"xyz", "abc", ">"}, {"pqr", "xyz", "<"}, }, }; try { RuleBasedCollator r = new RuleBasedCollator(TEST_RULES); for (int i = 0; i < TESTS.length; i++) { r.setStrength(i); doComparisons(r, TESTS[i]); } } catch (ParseException ex) { harness.debug(ex); harness.fail("single character ordering: ParseException (offset is " + ex.getErrorOffset() + ")"); } } private void contractionTests() { checkStrengths(); harness.checkPoint("contraction ordering"); final String OLD_SPANISH_RULES = "<c,C<ch,cH,Ch,CH<d,D"; final String[][][] TESTS = { { // PRIMARY {"cat", "cat", "="}, {"cat", "Cat", "="}, {"cat", "chat", "<"}, {"cot", "chat", "<"}, {"chat", "chit", "<"}, {"chat", "dog", "<"}, }, { // SECONDARY {"cat", "cat", "="}, {"cat", "Cat", "="}, {"cat", "chat", "<"}, {"cot", "chat", "<"}, {"chat", "chit", "<"}, {"chat", "dog", "<"}, }, { // TERTIARY {"cat", "cat", "="}, {"cat", "Cat", "<"}, {"cat", "chat", "<"}, {"cot", "chat", "<"}, {"chat", "chit", "<"}, {"chat", "dog", "<"}, }, { // IDENTICAL {"cat", "cat", "="}, {"cat", "Cat", "<"}, {"cat", "chat", "<"}, {"cot", "chat", "<"}, {"chat", "chit", "<"}, {"chat", "dog", "<"}, }, }; try { RuleBasedCollator r = new RuleBasedCollator(OLD_SPANISH_RULES); for (int i = 0; i < TESTS.length; i++) { r.setStrength(i); doComparisons(r, TESTS[i]); } } catch (ParseException ex) { harness.debug(ex); harness.fail("contraction ordering: ParseException (offset is " + ex.getErrorOffset() + ")"); } } private void expansionTests() { checkStrengths(); harness.checkPoint("expansion ordering"); final String OLD_ENGLISH_RULES = ("<a,A<b,B<c,C<d,D<e,E<f,F" + " &AE,'\u00e6' &AE,'\u00c6'"); final String[][][] TESTS = { { // PRIMARY {"ae", "\u00e6", "="}, {"AE", "\u00e6", "="}, {"ae", "\u00c6", "="}, {"AE", "\u00c6", "="}, {"cat", "cat", "="}, {"cat", "Cat", "="}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "="}, {"c\u00e6t", "caet", "="}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "="}, {"c\u00c6t", "caet", "="}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "="}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", "<"}, {"C\u00c6T", "CAT", "<"}, {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, { // SECONDARY {"ae", "\u00e6", "="}, {"AE", "\u00e6", "="}, {"ae", "\u00c6", "="}, {"AE", "\u00c6", "="}, {"cat", "cat", "="}, {"cat", "Cat", "="}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "="}, {"c\u00e6t", "caet", "="}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "="}, {"c\u00c6t", "caet", "="}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "="}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", "<"}, {"C\u00c6T", "CAT", "<"}, {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, { // TERTIARY {"ae", "\u00e6", "<"}, {"AE", "\u00e6", "<"}, {"ae", "\u00c6", "<"}, {"AE", "\u00c6", "<"}, {"cat", "cat", "="}, {"cat", "Cat", "<"}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "<"}, {"c\u00e6t", "caet", ">"}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "<"}, {"c\u00c6t", "caet", ">"}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "<"}, {"caet", "cat", "<"}, - {"c\u00e6t", "cat", "<"}, - {"C\u00c6T", "CAT", "<"}, + {"c\u00e6t", "cat", ">"}, // JDK is buggy. It fails here. + {"C\u00c6T", "CAT", ">"}, // JDK is buggy. It fails here. {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, { // IDENTICAL {"ae", "\u00e6", "<"}, {"AE", "\u00e6", "<"}, {"ae", "\u00c6", "<"}, {"AE", "\u00c6", "<"}, {"cat", "cat", "="}, {"cat", "Cat", "<"}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "<"}, {"c\u00e6t", "caet", ">"}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "<"}, {"c\u00c6t", "caet", ">"}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "<"}, {"caet", "cat", "<"}, - {"c\u00e6t", "cat", "<"}, - {"C\u00c6T", "CAT", "<"}, + {"c\u00e6t", "cat", ">"}, // JDK is buggy. It fails here. + {"C\u00c6T", "CAT", ">"}, // JDK is buggy. It fails here. {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, }; try { RuleBasedCollator r = new RuleBasedCollator(OLD_ENGLISH_RULES); for (int i = 0; i < TESTS.length; i++) { r.setStrength(i); doComparisons(r, TESTS[i]); } } catch (ParseException ex) { harness.debug(ex); harness.fail("expansion ordering: ParseException (offset is " + ex.getErrorOffset() + ")"); } } private void checkStrengths() { harness.checkPoint("collator strengths"); harness.check(Collator.PRIMARY == 0); harness.check(Collator.SECONDARY == 1); harness.check(Collator.TERTIARY == 2); harness.check(Collator.IDENTICAL == 3); } public void test(TestHarness harness) { this.harness = harness; constructorTests(); ignoreTests(); oneCharTests(); contractionTests(); expansionTests(); // More tests in the pipeline } } // class jdk11
false
true
private void expansionTests() { checkStrengths(); harness.checkPoint("expansion ordering"); final String OLD_ENGLISH_RULES = ("<a,A<b,B<c,C<d,D<e,E<f,F" + " &AE,'\u00e6' &AE,'\u00c6'"); final String[][][] TESTS = { { // PRIMARY {"ae", "\u00e6", "="}, {"AE", "\u00e6", "="}, {"ae", "\u00c6", "="}, {"AE", "\u00c6", "="}, {"cat", "cat", "="}, {"cat", "Cat", "="}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "="}, {"c\u00e6t", "caet", "="}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "="}, {"c\u00c6t", "caet", "="}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "="}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", "<"}, {"C\u00c6T", "CAT", "<"}, {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, { // SECONDARY {"ae", "\u00e6", "="}, {"AE", "\u00e6", "="}, {"ae", "\u00c6", "="}, {"AE", "\u00c6", "="}, {"cat", "cat", "="}, {"cat", "Cat", "="}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "="}, {"c\u00e6t", "caet", "="}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "="}, {"c\u00c6t", "caet", "="}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "="}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", "<"}, {"C\u00c6T", "CAT", "<"}, {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, { // TERTIARY {"ae", "\u00e6", "<"}, {"AE", "\u00e6", "<"}, {"ae", "\u00c6", "<"}, {"AE", "\u00c6", "<"}, {"cat", "cat", "="}, {"cat", "Cat", "<"}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "<"}, {"c\u00e6t", "caet", ">"}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "<"}, {"c\u00c6t", "caet", ">"}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "<"}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", "<"}, {"C\u00c6T", "CAT", "<"}, {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, { // IDENTICAL {"ae", "\u00e6", "<"}, {"AE", "\u00e6", "<"}, {"ae", "\u00c6", "<"}, {"AE", "\u00c6", "<"}, {"cat", "cat", "="}, {"cat", "Cat", "<"}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "<"}, {"c\u00e6t", "caet", ">"}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "<"}, {"c\u00c6t", "caet", ">"}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "<"}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", "<"}, {"C\u00c6T", "CAT", "<"}, {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, }; try { RuleBasedCollator r = new RuleBasedCollator(OLD_ENGLISH_RULES); for (int i = 0; i < TESTS.length; i++) { r.setStrength(i); doComparisons(r, TESTS[i]); } } catch (ParseException ex) { harness.debug(ex); harness.fail("expansion ordering: ParseException (offset is " + ex.getErrorOffset() + ")"); } }
private void expansionTests() { checkStrengths(); harness.checkPoint("expansion ordering"); final String OLD_ENGLISH_RULES = ("<a,A<b,B<c,C<d,D<e,E<f,F" + " &AE,'\u00e6' &AE,'\u00c6'"); final String[][][] TESTS = { { // PRIMARY {"ae", "\u00e6", "="}, {"AE", "\u00e6", "="}, {"ae", "\u00c6", "="}, {"AE", "\u00c6", "="}, {"cat", "cat", "="}, {"cat", "Cat", "="}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "="}, {"c\u00e6t", "caet", "="}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "="}, {"c\u00c6t", "caet", "="}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "="}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", "<"}, {"C\u00c6T", "CAT", "<"}, {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, { // SECONDARY {"ae", "\u00e6", "="}, {"AE", "\u00e6", "="}, {"ae", "\u00c6", "="}, {"AE", "\u00c6", "="}, {"cat", "cat", "="}, {"cat", "Cat", "="}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "="}, {"c\u00e6t", "caet", "="}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "="}, {"c\u00c6t", "caet", "="}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "="}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", "<"}, {"C\u00c6T", "CAT", "<"}, {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, { // TERTIARY {"ae", "\u00e6", "<"}, {"AE", "\u00e6", "<"}, {"ae", "\u00c6", "<"}, {"AE", "\u00c6", "<"}, {"cat", "cat", "="}, {"cat", "Cat", "<"}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "<"}, {"c\u00e6t", "caet", ">"}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "<"}, {"c\u00c6t", "caet", ">"}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "<"}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", ">"}, // JDK is buggy. It fails here. {"C\u00c6T", "CAT", ">"}, // JDK is buggy. It fails here. {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, { // IDENTICAL {"ae", "\u00e6", "<"}, {"AE", "\u00e6", "<"}, {"ae", "\u00c6", "<"}, {"AE", "\u00c6", "<"}, {"cat", "cat", "="}, {"cat", "Cat", "<"}, {"caet", "caet", "="}, {"caet", "c\u00e6t", "<"}, {"c\u00e6t", "caet", ">"}, {"c\u00e6t", "c\u00e6t", "="}, {"caet", "c\u00c6t", "<"}, {"c\u00c6t", "caet", ">"}, {"c\u00c6t", "c\u00c6t", "="}, {"c\u00c6t", "c\u00e6t", "<"}, {"caet", "cat", "<"}, {"c\u00e6t", "cat", ">"}, // JDK is buggy. It fails here. {"C\u00c6T", "CAT", ">"}, // JDK is buggy. It fails here. {"caet", "cab", ">"}, {"c\u00e6t", "cab", ">"}, {"C\u00c6T", "CAB", ">"}, }, }; try { RuleBasedCollator r = new RuleBasedCollator(OLD_ENGLISH_RULES); for (int i = 0; i < TESTS.length; i++) { r.setStrength(i); doComparisons(r, TESTS[i]); } } catch (ParseException ex) { harness.debug(ex); harness.fail("expansion ordering: ParseException (offset is " + ex.getErrorOffset() + ")"); } }
diff --git a/src/gwt/src/org/rstudio/studio/client/workbench/ui/FontSizeManager.java b/src/gwt/src/org/rstudio/studio/client/workbench/ui/FontSizeManager.java index 312b729cbc..6394a92e61 100644 --- a/src/gwt/src/org/rstudio/studio/client/workbench/ui/FontSizeManager.java +++ b/src/gwt/src/org/rstudio/studio/client/workbench/ui/FontSizeManager.java @@ -1,83 +1,85 @@ package org.rstudio.studio.client.workbench.ui; import com.google.inject.Inject; import com.google.inject.Singleton; import org.rstudio.core.client.Debug; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.CommandHandler; import org.rstudio.core.client.widget.FontSizer; import org.rstudio.core.client.widget.FontSizer.Size; import org.rstudio.studio.client.application.events.ChangeFontSizeEvent; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.helper.StringStateValue; @Singleton public class FontSizeManager { @Inject public FontSizeManager(Session session, EventBus events, Commands commands) { session_ = session; events_ = events; commands_ = commands; commands.fontSize10().addHandler(createHandler(FontSizer.Size.Pt10)); commands.fontSize12().addHandler(createHandler(FontSizer.Size.Pt12)); commands.fontSize14().addHandler(createHandler(FontSizer.Size.Pt14)); commands.fontSize16().addHandler(createHandler(FontSizer.Size.Pt16)); commands.fontSize18().addHandler(createHandler(FontSizer.Size.Pt18)); new StringStateValue("font", "size", true, session.getSessionInfo().getClientState()) { @Override protected void onInit(String value) { + final Size DEFAULT_SIZE = Size.Pt12; try { - size_ = FontSizer.Size.valueOf(value); + if (value != null) + size_ = FontSizer.Size.valueOf(value); + else + size_ = DEFAULT_SIZE; } catch (Exception e) { - Debug.log("Unexpected value for font size: " + value); - Debug.log(e.toString()); - size_ = FontSizer.Size.Pt12; + size_ = DEFAULT_SIZE; } } @Override protected String getValue() { return size_.toString(); } }; } private CommandHandler createHandler(final Size size) { return new CommandHandler() { public void onCommand(AppCommand command) { size_ = size; events_.fireEvent(new ChangeFontSizeEvent(size)); session_.persistClientState(); } }; } public Size getSize() { return size_; } private final Session session_; private final EventBus events_; private final Commands commands_; private Size size_; }
false
true
public FontSizeManager(Session session, EventBus events, Commands commands) { session_ = session; events_ = events; commands_ = commands; commands.fontSize10().addHandler(createHandler(FontSizer.Size.Pt10)); commands.fontSize12().addHandler(createHandler(FontSizer.Size.Pt12)); commands.fontSize14().addHandler(createHandler(FontSizer.Size.Pt14)); commands.fontSize16().addHandler(createHandler(FontSizer.Size.Pt16)); commands.fontSize18().addHandler(createHandler(FontSizer.Size.Pt18)); new StringStateValue("font", "size", true, session.getSessionInfo().getClientState()) { @Override protected void onInit(String value) { try { size_ = FontSizer.Size.valueOf(value); } catch (Exception e) { Debug.log("Unexpected value for font size: " + value); Debug.log(e.toString()); size_ = FontSizer.Size.Pt12; } } @Override protected String getValue() { return size_.toString(); } }; }
public FontSizeManager(Session session, EventBus events, Commands commands) { session_ = session; events_ = events; commands_ = commands; commands.fontSize10().addHandler(createHandler(FontSizer.Size.Pt10)); commands.fontSize12().addHandler(createHandler(FontSizer.Size.Pt12)); commands.fontSize14().addHandler(createHandler(FontSizer.Size.Pt14)); commands.fontSize16().addHandler(createHandler(FontSizer.Size.Pt16)); commands.fontSize18().addHandler(createHandler(FontSizer.Size.Pt18)); new StringStateValue("font", "size", true, session.getSessionInfo().getClientState()) { @Override protected void onInit(String value) { final Size DEFAULT_SIZE = Size.Pt12; try { if (value != null) size_ = FontSizer.Size.valueOf(value); else size_ = DEFAULT_SIZE; } catch (Exception e) { size_ = DEFAULT_SIZE; } } @Override protected String getValue() { return size_.toString(); } }; }
diff --git a/src/main/java/com/testdroid/api/APIDeviceQueryBuilder.java b/src/main/java/com/testdroid/api/APIDeviceQueryBuilder.java index 83cfb97..9368057 100644 --- a/src/main/java/com/testdroid/api/APIDeviceQueryBuilder.java +++ b/src/main/java/com/testdroid/api/APIDeviceQueryBuilder.java @@ -1,65 +1,65 @@ package com.testdroid.api; import com.testdroid.api.model.APIDevice; import org.apache.commons.lang.StringUtils; /** * * @author kajdus */ public class APIDeviceQueryBuilder extends APIQueryBuilder { private Long[] labelIds; private Long[] deviceGroupIds; private APIDevice.DeviceFilter[] deviceFilters; public APIDeviceQueryBuilder filterWithLabelIds(Long... labelIds) { this.labelIds = labelIds; return this; } public APIDeviceQueryBuilder filterWithDeviceGroupIds(Long... deviceGroupIds) { this.deviceGroupIds = deviceGroupIds; return this; } public APIDeviceQueryBuilder filterWithDeviceFilters(APIDevice.DeviceFilter... deviceFilters) { this.deviceFilters = deviceFilters; return this; } @Override public APIDeviceQueryBuilder offset(int offset) { return (APIDeviceQueryBuilder) super.offset(offset); } @Override public APIDeviceQueryBuilder limit(int limit) { return (APIDeviceQueryBuilder) super.limit(limit); } @Override public APIDeviceQueryBuilder search(String search) { return (APIDeviceQueryBuilder) super.search(search); } @Override public APIDeviceQueryBuilder sort(Class<? extends APIEntity> type, APISort.SortItem... sortItems) { return (APIDeviceQueryBuilder) sort(type, sortItems); } @Override protected String build(String uri) { String superResult = super.build(uri); String thisResult = superResult + (superResult.contains("?") ? "&" : "?"); if(labelIds != null && labelIds.length > 0) { - thisResult += "label_id=" + StringUtils.join(labelIds, "&label_id=") + "&"; + thisResult += "label_id[]=" + StringUtils.join(labelIds, "&label_id=") + "&"; } if(deviceGroupIds != null && deviceGroupIds.length > 0) { - thisResult += "device_group_id=" + StringUtils.join(deviceGroupIds, "&device_group_id=") + "&"; + thisResult += "device_group_id[]=" + StringUtils.join(deviceGroupIds, "&device_group_id=") + "&"; } if(deviceFilters != null && deviceFilters.length > 0) { - thisResult += "device_filter=" + StringUtils.join(deviceFilters, "&device_filter=") + "&"; + thisResult += "device_filter[]=" + StringUtils.join(deviceFilters, "&device_filter=") + "&"; } return thisResult; } }
false
true
protected String build(String uri) { String superResult = super.build(uri); String thisResult = superResult + (superResult.contains("?") ? "&" : "?"); if(labelIds != null && labelIds.length > 0) { thisResult += "label_id=" + StringUtils.join(labelIds, "&label_id=") + "&"; } if(deviceGroupIds != null && deviceGroupIds.length > 0) { thisResult += "device_group_id=" + StringUtils.join(deviceGroupIds, "&device_group_id=") + "&"; } if(deviceFilters != null && deviceFilters.length > 0) { thisResult += "device_filter=" + StringUtils.join(deviceFilters, "&device_filter=") + "&"; } return thisResult; }
protected String build(String uri) { String superResult = super.build(uri); String thisResult = superResult + (superResult.contains("?") ? "&" : "?"); if(labelIds != null && labelIds.length > 0) { thisResult += "label_id[]=" + StringUtils.join(labelIds, "&label_id=") + "&"; } if(deviceGroupIds != null && deviceGroupIds.length > 0) { thisResult += "device_group_id[]=" + StringUtils.join(deviceGroupIds, "&device_group_id=") + "&"; } if(deviceFilters != null && deviceFilters.length > 0) { thisResult += "device_filter[]=" + StringUtils.join(deviceFilters, "&device_filter=") + "&"; } return thisResult; }
diff --git a/common/logisticspipes/routing/PathFinder.java b/common/logisticspipes/routing/PathFinder.java index bc73af0c..e8ebd089 100644 --- a/common/logisticspipes/routing/PathFinder.java +++ b/common/logisticspipes/routing/PathFinder.java @@ -1,205 +1,205 @@ /** * Copyright (c) Krapht, 2011 * * "LogisticsPipes" is distributed under the terms of the Minecraft Mod Public * License 1.0, or MMPL. Please check the contents of the license located in * http://www.mod-buildcraft.com/MMPL-1.0.txt */ package logisticspipes.routing; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import logisticspipes.interfaces.routing.IDirectRoutingConnection; import logisticspipes.pipes.PipeItemsInvSysConnector; import logisticspipes.pipes.basic.CoreRoutedPipe; import logisticspipes.pipes.basic.RoutedPipe; import logisticspipes.proxy.SimpleServiceLocator; import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.ForgeDirection; import buildcraft.api.core.Position; import buildcraft.transport.TileGenericPipe; import buildcraft.transport.pipes.PipeItemsDiamond; import buildcraft.transport.pipes.PipeItemsIron; import buildcraft.transport.pipes.PipeItemsObsidian; /** * Examines all pipe connections and their forks to locate all connected routers */ class PathFinder { /** * Recurse through all exists of a pipe to find instances of PipeItemsRouting. maxVisited and maxLength are safeguards for * recursion runaways. * * @param startPipe - The TileGenericPipe to start the search from * @param maxVisited - The maximum number of pipes to visit, regardless of recursion level * @param maxLength - The maximum recurse depth, i.e. the maximum length pipe that is supported * @return */ public static HashMap<RoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, int maxVisited, int maxLength) { PathFinder newSearch = new PathFinder(maxVisited, maxLength, null); return newSearch.getConnectedRoutingPipes(startPipe,EnumSet.noneOf(PipeRoutingConnectionType.class)); } public static HashMap<RoutedPipe, ExitRoute> paintAndgetConnectedRoutingPipes(TileGenericPipe startPipe, ForgeDirection startOrientation, int maxVisited, int maxLength, IPaintPath pathPainter) { PathFinder newSearch = new PathFinder(maxVisited, maxLength, pathPainter); newSearch.setVisited.add(startPipe); Position p = new Position(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, startOrientation); p.moveForwards(1); TileEntity entity = startPipe.worldObj.getBlockTileEntity((int)p.x, (int)p.y, (int)p.z); if (!(entity instanceof TileGenericPipe && ((TileGenericPipe)entity).pipe.isPipeConnected(startPipe, startOrientation))){ return new HashMap<RoutedPipe, ExitRoute>(); } return newSearch.getConnectedRoutingPipes((TileGenericPipe) entity,EnumSet.noneOf(PipeRoutingConnectionType.class)); } private PathFinder(int maxVisited, int maxLength, IPaintPath pathPainter) { this.maxVisited = maxVisited; this.maxLength = maxLength; this.setVisited = new HashSet<TileGenericPipe>(); this.pathPainter = pathPainter; } private final int maxVisited; private final int maxLength; private final HashSet<TileGenericPipe> setVisited; private final IPaintPath pathPainter; private int pipesVisited; private HashMap<RoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, EnumSet<PipeRoutingConnectionType> connectionFlags) { HashMap<RoutedPipe, ExitRoute> foundPipes = new HashMap<RoutedPipe, ExitRoute>(); //Reset visited count at top level if (setVisited.size() == 1) { pipesVisited = 0; } //Break recursion if we have visited a set number of pipes, to prevent client hang if pipes are weirdly configured if (++pipesVisited > maxVisited) { return foundPipes; } //Break recursion after certain amount of nodes visited if (setVisited.size() > maxLength) { return foundPipes; } //Break recursion if we end up on a routing pipe, unless its the first one. Will break if matches the first call if (startPipe.pipe instanceof RoutedPipe && setVisited.size() != 0) { foundPipes.put((RoutedPipe) startPipe.pipe, new ExitRoute(ForgeDirection.UNKNOWN, setVisited.size(), connectionFlags)); return foundPipes; } //Visited is checked after, so we can reach the same target twice to allow to keep the shortest path setVisited.add(startPipe); if(startPipe.pipe != null) { List<TileGenericPipe> pipez = SimpleServiceLocator.specialconnection.getConnectedPipes(startPipe); for (TileGenericPipe specialpipe : pipez){ if (setVisited.contains(specialpipe)) { //Don't go where we have been before continue; } HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(specialpipe,connectionFlags); for(RoutedPipe pipe : result.keySet()) { result.get(pipe).exitOrientation = ForgeDirection.UNKNOWN; if (!foundPipes.containsKey(pipe)) { // New path foundPipes.put(pipe, result.get(pipe)); } else if (result.get(pipe).metric < foundPipes.get(pipe).metric) { //If new path is better, replace old path, otherwise do nothing foundPipes.put(pipe, result.get(pipe)); } } } } //Recurse in all directions for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { EnumSet<PipeRoutingConnectionType> nextConnectionFlags = connectionFlags; Position p = new Position(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, direction); p.moveForwards(1); TileEntity tile = startPipe.worldObj.getBlockTileEntity((int) p.x, (int) p.y, (int) p.z); if (tile == null) continue; boolean isDirectConnection = false; int resistance = 0; if(tile instanceof IInventory) { if(startPipe.pipe instanceof IDirectRoutingConnection) { if(SimpleServiceLocator.connectionManager.hasDirectConnection(((RoutedPipe)startPipe.pipe).getRouter())) { CoreRoutedPipe CRP = SimpleServiceLocator.connectionManager.getConnectedPipe(((RoutedPipe)startPipe.pipe).getRouter()); if(CRP != null) { tile = CRP.container; isDirectConnection = true; resistance = ((IDirectRoutingConnection)startPipe.pipe).getConnectionResistance(); } } } } if (tile == null) continue; if (tile instanceof TileGenericPipe && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile))) { TileGenericPipe currentPipe = (TileGenericPipe) tile; if (setVisited.contains(tile)) { //Don't go where we have been before continue; } //Iron, obsidean, and diamond pipes will separate networks if(currentPipe.pipe instanceof PipeItemsObsidian){ nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughObsidian); } if(currentPipe.pipe instanceof PipeItemsDiamond){ nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughDiamond); } if(startPipe.pipe instanceof PipeItemsInvSysConnector){ nextConnectionFlags.add(PipeRoutingConnectionType.blocksPowerFlow); } if(startPipe.pipe instanceof PipeItemsIron){ if(currentPipe.pipe.outputOpen(direction)) nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughIronForwards); - if(currentPipe.pipe.outputOpen(direction)) + else nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughIronBackwards); } int beforeRecurseCount = foundPipes.size(); HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(((TileGenericPipe)tile),nextConnectionFlags); for(RoutedPipe pipe : result.keySet()) { //Update Result with the direction we took result.get(pipe).exitOrientation = direction; if (!foundPipes.containsKey(pipe)) { // New path foundPipes.put(pipe, result.get(pipe)); //Add resistance foundPipes.get(pipe).metric += resistance; } else if (result.get(pipe).metric + resistance < foundPipes.get(pipe).metric) { //If new path is better, replace old path, otherwise do nothing foundPipes.put(pipe, result.get(pipe)); //Add resistance foundPipes.get(pipe).metric += resistance; } } if (foundPipes.size() > beforeRecurseCount && pathPainter != null){ p.moveBackwards(1); pathPainter.addLaser(startPipe.worldObj, p, direction); } } } setVisited.remove(startPipe); return foundPipes; } }
true
true
private HashMap<RoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, EnumSet<PipeRoutingConnectionType> connectionFlags) { HashMap<RoutedPipe, ExitRoute> foundPipes = new HashMap<RoutedPipe, ExitRoute>(); //Reset visited count at top level if (setVisited.size() == 1) { pipesVisited = 0; } //Break recursion if we have visited a set number of pipes, to prevent client hang if pipes are weirdly configured if (++pipesVisited > maxVisited) { return foundPipes; } //Break recursion after certain amount of nodes visited if (setVisited.size() > maxLength) { return foundPipes; } //Break recursion if we end up on a routing pipe, unless its the first one. Will break if matches the first call if (startPipe.pipe instanceof RoutedPipe && setVisited.size() != 0) { foundPipes.put((RoutedPipe) startPipe.pipe, new ExitRoute(ForgeDirection.UNKNOWN, setVisited.size(), connectionFlags)); return foundPipes; } //Visited is checked after, so we can reach the same target twice to allow to keep the shortest path setVisited.add(startPipe); if(startPipe.pipe != null) { List<TileGenericPipe> pipez = SimpleServiceLocator.specialconnection.getConnectedPipes(startPipe); for (TileGenericPipe specialpipe : pipez){ if (setVisited.contains(specialpipe)) { //Don't go where we have been before continue; } HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(specialpipe,connectionFlags); for(RoutedPipe pipe : result.keySet()) { result.get(pipe).exitOrientation = ForgeDirection.UNKNOWN; if (!foundPipes.containsKey(pipe)) { // New path foundPipes.put(pipe, result.get(pipe)); } else if (result.get(pipe).metric < foundPipes.get(pipe).metric) { //If new path is better, replace old path, otherwise do nothing foundPipes.put(pipe, result.get(pipe)); } } } } //Recurse in all directions for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { EnumSet<PipeRoutingConnectionType> nextConnectionFlags = connectionFlags; Position p = new Position(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, direction); p.moveForwards(1); TileEntity tile = startPipe.worldObj.getBlockTileEntity((int) p.x, (int) p.y, (int) p.z); if (tile == null) continue; boolean isDirectConnection = false; int resistance = 0; if(tile instanceof IInventory) { if(startPipe.pipe instanceof IDirectRoutingConnection) { if(SimpleServiceLocator.connectionManager.hasDirectConnection(((RoutedPipe)startPipe.pipe).getRouter())) { CoreRoutedPipe CRP = SimpleServiceLocator.connectionManager.getConnectedPipe(((RoutedPipe)startPipe.pipe).getRouter()); if(CRP != null) { tile = CRP.container; isDirectConnection = true; resistance = ((IDirectRoutingConnection)startPipe.pipe).getConnectionResistance(); } } } } if (tile == null) continue; if (tile instanceof TileGenericPipe && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile))) { TileGenericPipe currentPipe = (TileGenericPipe) tile; if (setVisited.contains(tile)) { //Don't go where we have been before continue; } //Iron, obsidean, and diamond pipes will separate networks if(currentPipe.pipe instanceof PipeItemsObsidian){ nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughObsidian); } if(currentPipe.pipe instanceof PipeItemsDiamond){ nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughDiamond); } if(startPipe.pipe instanceof PipeItemsInvSysConnector){ nextConnectionFlags.add(PipeRoutingConnectionType.blocksPowerFlow); } if(startPipe.pipe instanceof PipeItemsIron){ if(currentPipe.pipe.outputOpen(direction)) nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughIronForwards); if(currentPipe.pipe.outputOpen(direction)) nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughIronBackwards); } int beforeRecurseCount = foundPipes.size(); HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(((TileGenericPipe)tile),nextConnectionFlags); for(RoutedPipe pipe : result.keySet()) { //Update Result with the direction we took result.get(pipe).exitOrientation = direction; if (!foundPipes.containsKey(pipe)) { // New path foundPipes.put(pipe, result.get(pipe)); //Add resistance foundPipes.get(pipe).metric += resistance; } else if (result.get(pipe).metric + resistance < foundPipes.get(pipe).metric) { //If new path is better, replace old path, otherwise do nothing foundPipes.put(pipe, result.get(pipe)); //Add resistance foundPipes.get(pipe).metric += resistance; } } if (foundPipes.size() > beforeRecurseCount && pathPainter != null){ p.moveBackwards(1); pathPainter.addLaser(startPipe.worldObj, p, direction); } } } setVisited.remove(startPipe); return foundPipes; }
private HashMap<RoutedPipe, ExitRoute> getConnectedRoutingPipes(TileGenericPipe startPipe, EnumSet<PipeRoutingConnectionType> connectionFlags) { HashMap<RoutedPipe, ExitRoute> foundPipes = new HashMap<RoutedPipe, ExitRoute>(); //Reset visited count at top level if (setVisited.size() == 1) { pipesVisited = 0; } //Break recursion if we have visited a set number of pipes, to prevent client hang if pipes are weirdly configured if (++pipesVisited > maxVisited) { return foundPipes; } //Break recursion after certain amount of nodes visited if (setVisited.size() > maxLength) { return foundPipes; } //Break recursion if we end up on a routing pipe, unless its the first one. Will break if matches the first call if (startPipe.pipe instanceof RoutedPipe && setVisited.size() != 0) { foundPipes.put((RoutedPipe) startPipe.pipe, new ExitRoute(ForgeDirection.UNKNOWN, setVisited.size(), connectionFlags)); return foundPipes; } //Visited is checked after, so we can reach the same target twice to allow to keep the shortest path setVisited.add(startPipe); if(startPipe.pipe != null) { List<TileGenericPipe> pipez = SimpleServiceLocator.specialconnection.getConnectedPipes(startPipe); for (TileGenericPipe specialpipe : pipez){ if (setVisited.contains(specialpipe)) { //Don't go where we have been before continue; } HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(specialpipe,connectionFlags); for(RoutedPipe pipe : result.keySet()) { result.get(pipe).exitOrientation = ForgeDirection.UNKNOWN; if (!foundPipes.containsKey(pipe)) { // New path foundPipes.put(pipe, result.get(pipe)); } else if (result.get(pipe).metric < foundPipes.get(pipe).metric) { //If new path is better, replace old path, otherwise do nothing foundPipes.put(pipe, result.get(pipe)); } } } } //Recurse in all directions for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { EnumSet<PipeRoutingConnectionType> nextConnectionFlags = connectionFlags; Position p = new Position(startPipe.xCoord, startPipe.yCoord, startPipe.zCoord, direction); p.moveForwards(1); TileEntity tile = startPipe.worldObj.getBlockTileEntity((int) p.x, (int) p.y, (int) p.z); if (tile == null) continue; boolean isDirectConnection = false; int resistance = 0; if(tile instanceof IInventory) { if(startPipe.pipe instanceof IDirectRoutingConnection) { if(SimpleServiceLocator.connectionManager.hasDirectConnection(((RoutedPipe)startPipe.pipe).getRouter())) { CoreRoutedPipe CRP = SimpleServiceLocator.connectionManager.getConnectedPipe(((RoutedPipe)startPipe.pipe).getRouter()); if(CRP != null) { tile = CRP.container; isDirectConnection = true; resistance = ((IDirectRoutingConnection)startPipe.pipe).getConnectionResistance(); } } } } if (tile == null) continue; if (tile instanceof TileGenericPipe && (isDirectConnection || SimpleServiceLocator.buildCraftProxy.checkPipesConnections(startPipe, tile))) { TileGenericPipe currentPipe = (TileGenericPipe) tile; if (setVisited.contains(tile)) { //Don't go where we have been before continue; } //Iron, obsidean, and diamond pipes will separate networks if(currentPipe.pipe instanceof PipeItemsObsidian){ nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughObsidian); } if(currentPipe.pipe instanceof PipeItemsDiamond){ nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughDiamond); } if(startPipe.pipe instanceof PipeItemsInvSysConnector){ nextConnectionFlags.add(PipeRoutingConnectionType.blocksPowerFlow); } if(startPipe.pipe instanceof PipeItemsIron){ if(currentPipe.pipe.outputOpen(direction)) nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughIronForwards); else nextConnectionFlags.add(PipeRoutingConnectionType.passedThroughIronBackwards); } int beforeRecurseCount = foundPipes.size(); HashMap<RoutedPipe, ExitRoute> result = getConnectedRoutingPipes(((TileGenericPipe)tile),nextConnectionFlags); for(RoutedPipe pipe : result.keySet()) { //Update Result with the direction we took result.get(pipe).exitOrientation = direction; if (!foundPipes.containsKey(pipe)) { // New path foundPipes.put(pipe, result.get(pipe)); //Add resistance foundPipes.get(pipe).metric += resistance; } else if (result.get(pipe).metric + resistance < foundPipes.get(pipe).metric) { //If new path is better, replace old path, otherwise do nothing foundPipes.put(pipe, result.get(pipe)); //Add resistance foundPipes.get(pipe).metric += resistance; } } if (foundPipes.size() > beforeRecurseCount && pathPainter != null){ p.moveBackwards(1); pathPainter.addLaser(startPipe.worldObj, p, direction); } } } setVisited.remove(startPipe); return foundPipes; }
diff --git a/Adventron.java b/Adventron.java index 0ac069b..7385c8f 100644 --- a/Adventron.java +++ b/Adventron.java @@ -1,260 +1,260 @@ /* * Adventron - Stan Schwertly * Port of an old game I made. Learning git too! * * Adventron.java * * http://www.schwertly.com for my blog * http://github.com/Stantheman/Adventron-Game for the GitHub */ import java.applet.*; import java.awt.*; import java.util.ArrayList; /* * - don't forget about buser in linodeland for java talk! */ public class Adventron extends Applet implements Runnable { private Image dbImage; private Graphics dbg; // Game variables private Player player = new Player(); private ArrayList <Map> map = new ArrayList<Map>(); private ArrayList <Bullet> bullets = new ArrayList<Bullet>(); private ArrayList <Monster> monsters = new ArrayList<Monster>(); private Statusbar bar = new Statusbar(player); public void init() { setBackground(Color.black); // Suck in the levels for (int i=0; i<9; i++) { map.add(new Map()); map.get(i).readLevel(new String("level" + i + ".dat"), dbg); } // Give everyone local copies player.setMap(map.get(0)); Bullet.initWalls(); Bullet.setMap(map.get(0)); bar.updateStatus(); for (int i=0; i<map.get(0).getMonsterPosition().size(); i++) { monsters.add(new Monster(map.get(0).getMonsterPosition().get(i))); } } public void start() { Thread th = new Thread(this); th.start(); } public void stop() { } public void destroy() { } public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while (true) { // update the player if (!player.move()) { player.setMap(map.get(player.getRoom())); Bullet.setMap(map.get(player.getRoom())); bullets.clear(); monsters.clear(); for (int i=0; i<map.get(player.getRoom()).getMonsterPosition().size(); i++) { - monsters.add(new Monster(map.get(0).getMonsterPosition().get(i))); + monsters.add(new Monster(map.get(player.getRoom()).getMonsterPosition().get(i))); } } // update the bullets for (int i=0; i<bullets.size(); i++) { bullets.get(i).changePosition(player, monsters); if (bullets.get(i).getQuadrant() == Map.OUT_OF_BOUNDS) { bullets.remove(i); i--; continue; } if (player.isHit()) { player.setHealth(player.getHealth()-1); player.setHit(false); bar.updateStatus(); } } // update the monsters for (int i=0; i<monsters.size(); i++) { monsters.get(i).changePosition( map.get(player.getRoom()).getWalls(monsters.get(i).getQuadrant()), bullets); if (monsters.get(i).isHit()) { monsters.remove(i); player.addToScore(100); bar.updateStatus(); i--; } } repaint(); try { Thread.sleep(20); } catch (InterruptedException ex) {} Thread.currentThread().setPriority(Thread.MAX_PRIORITY); } } public void paint(Graphics g) { // draw the walls g.drawImage(map.get(player.getRoom()).image, 0, 0, null); // draw the player g.setColor(Player.COLOR); // This is temporary. Player doesn't get drawn if hit if (player.getHealth()>0) g.fillRect(player.getPosition().x, player.getPosition().y, Player.WIDTH, Player.HEIGHT); // draw the monsters g.setColor(Monster.COLOR); for (int i=0; i<monsters.size(); i++) { g.fillRect(monsters.get(i).getPosition().x, monsters.get(i).getPosition().y, Monster.WIDTH, Monster.HEIGHT); } // draw the bullets g.setColor(Bullet.COLOR); for (int i=0; i<bullets.size(); i++) { g.fillRect(bullets.get(i).getPosition().x, bullets.get(i).getPosition().y, Bullet.WIDTH, Bullet.HEIGHT); } g.setColor(Color.white); g.drawString(bar.toString(), 20, 20); } public void update(Graphics g) { // java reminder: initialize buffer for double buffering if (dbImage == null) { dbImage = createImage(this.getSize().width, this.getSize().height); dbg = dbImage.getGraphics(); } dbg.setColor(getBackground()); dbg.fillRect(0, 0, this.getSize().width, this.getSize().height); dbg.setColor(getForeground()); paint(dbg); g.drawImage(dbImage, 0, 0, this); } public boolean keyDown(Event e, int key) { if (key == Event.LEFT) { player.setDirection(Player.LEFT); player.setFacing(Player.LEFT); } if (key == Event.RIGHT) { player.setDirection(Player.RIGHT); player.setFacing(Player.RIGHT); } if (key == Event.UP) { player.setDirection(Player.UP); player.setFacing(Player.UP); } if (key == Event.DOWN) { player.setDirection(Player.DOWN); player.setFacing(Player.DOWN); } // user presses space bar if (key == 32) { // Bullet gets added to the outside of the box to avoid accidental hits if (player.getFacing() == Player.LEFT) { bullets.add(new Bullet( player.getPosition().x, player.getPosition().y, Player.LEFT)); } else if (player.getFacing() == Player.RIGHT) { bullets.add(new Bullet( player.getPosition().x + Player.WIDTH, player.getPosition().y, Player.RIGHT)); } else if (player.getFacing() == Player.UP) { bullets.add(new Bullet( player.getPosition().x, player.getPosition().y, Player.UP)); } else { bullets.add(new Bullet( player.getPosition().x, player.getPosition().y + Player.HEIGHT, Player.DOWN)); } } if (key == Event.ENTER) { bar.switchDebug(); bar.updateStatus(); } return true; } public boolean keyUp(Event e, int key) { if ( (key == Event.LEFT) || (key == Event.RIGHT) || (key == Event.UP) || (key == Event.DOWN) ) { player.setDirection(Player.STILL); } return true; } }
true
true
public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while (true) { // update the player if (!player.move()) { player.setMap(map.get(player.getRoom())); Bullet.setMap(map.get(player.getRoom())); bullets.clear(); monsters.clear(); for (int i=0; i<map.get(player.getRoom()).getMonsterPosition().size(); i++) { monsters.add(new Monster(map.get(0).getMonsterPosition().get(i))); } } // update the bullets for (int i=0; i<bullets.size(); i++) { bullets.get(i).changePosition(player, monsters); if (bullets.get(i).getQuadrant() == Map.OUT_OF_BOUNDS) { bullets.remove(i); i--; continue; } if (player.isHit()) { player.setHealth(player.getHealth()-1); player.setHit(false); bar.updateStatus(); } } // update the monsters for (int i=0; i<monsters.size(); i++) { monsters.get(i).changePosition( map.get(player.getRoom()).getWalls(monsters.get(i).getQuadrant()), bullets); if (monsters.get(i).isHit()) { monsters.remove(i); player.addToScore(100); bar.updateStatus(); i--; } } repaint(); try { Thread.sleep(20); } catch (InterruptedException ex) {} Thread.currentThread().setPriority(Thread.MAX_PRIORITY); } }
public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while (true) { // update the player if (!player.move()) { player.setMap(map.get(player.getRoom())); Bullet.setMap(map.get(player.getRoom())); bullets.clear(); monsters.clear(); for (int i=0; i<map.get(player.getRoom()).getMonsterPosition().size(); i++) { monsters.add(new Monster(map.get(player.getRoom()).getMonsterPosition().get(i))); } } // update the bullets for (int i=0; i<bullets.size(); i++) { bullets.get(i).changePosition(player, monsters); if (bullets.get(i).getQuadrant() == Map.OUT_OF_BOUNDS) { bullets.remove(i); i--; continue; } if (player.isHit()) { player.setHealth(player.getHealth()-1); player.setHit(false); bar.updateStatus(); } } // update the monsters for (int i=0; i<monsters.size(); i++) { monsters.get(i).changePosition( map.get(player.getRoom()).getWalls(monsters.get(i).getQuadrant()), bullets); if (monsters.get(i).isHit()) { monsters.remove(i); player.addToScore(100); bar.updateStatus(); i--; } } repaint(); try { Thread.sleep(20); } catch (InterruptedException ex) {} Thread.currentThread().setPriority(Thread.MAX_PRIORITY); } }
diff --git a/src/com/matburt/mobileorg/Gui/Agenda/OrgQueryBuilder.java b/src/com/matburt/mobileorg/Gui/Agenda/OrgQueryBuilder.java index 63b21ec..2464870 100644 --- a/src/com/matburt/mobileorg/Gui/Agenda/OrgQueryBuilder.java +++ b/src/com/matburt/mobileorg/Gui/Agenda/OrgQueryBuilder.java @@ -1,134 +1,134 @@ package com.matburt.mobileorg.Gui.Agenda; import java.io.Serializable; import java.util.ArrayList; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.matburt.mobileorg.OrgData.OrgContract.OrgData; import com.matburt.mobileorg.OrgData.OrgDatabase.Tables; import com.matburt.mobileorg.OrgData.OrgFile; import com.matburt.mobileorg.OrgData.OrgProviderUtils; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.SelectionBuilder; public class OrgQueryBuilder implements Serializable { private static final long serialVersionUID = 2; public String title = ""; public ArrayList<String> files = new ArrayList<String>(); public ArrayList<String> todos = new ArrayList<String>(); public ArrayList<String> tags = new ArrayList<String>(); public ArrayList<String> priorities = new ArrayList<String>(); public ArrayList<String> payloads = new ArrayList<String>(); public boolean filterHabits = false; public boolean activeTodos = false; public OrgQueryBuilder(String title) { this.title = title; } public long[] getNodes(SQLiteDatabase db, Context context) { long[] result = null; Cursor cursor = getQuery(context).query(db, OrgData.DEFAULT_COLUMNS, OrgData.DEFAULT_SORT); result = new long[cursor.getCount()]; cursor.moveToFirst(); int i = 0; while(cursor.isAfterLast() == false) { result[i++] = cursor.getLong(cursor.getColumnIndex(OrgData.ID)); cursor.moveToNext(); } cursor.close(); return result; } public SelectionBuilder getQuery(Context context) { final SelectionBuilder builder = new SelectionBuilder(); builder.table(Tables.ORGDATA); getFileSelection(builder, context); if (activeTodos) builder.where(getSelection(OrgProviderUtils.getActiveTodos(context .getContentResolver()), OrgData.TODO)); if(todos != null && todos.size() > 0) builder.where(getSelection(todos, OrgData.TODO)); if(tags != null && tags.size() > 0) builder.where(getLikeSelection(tags, OrgData.TAGS) + " OR " + getLikeSelection(tags, OrgData.TAGS_INHERITED)); if(priorities != null && priorities.size() > 0) builder.where(getSelection(priorities, OrgData.PRIORITY)); if(payloads != null && payloads.size() > 0) builder.where(getLikeSelection(payloads, OrgData.PAYLOAD)); if(filterHabits) - builder.where("NOT " + OrgData.PAYLOAD + " LIKE ?", "'%:STYLE: habit%'"); + builder.where("NOT " + OrgData.PAYLOAD + " LIKE ?", "%:STYLE: habit%"); return builder; } private String getLikeSelection(ArrayList<String> values, String column) { StringBuilder builder = new StringBuilder(); if(values == null) return ""; for (String value: values) { builder.append(column + " LIKE '%" + value + "%'").append(" OR "); } builder.delete(builder.length() - " OR ".length(), builder.length() - 1); return builder.toString(); } private String getSelection(ArrayList<String> values, String column) { StringBuilder builder = new StringBuilder(); if(values == null) return ""; for (String value: values) { builder.append(column + "='" + value + "'").append(" OR "); } builder.delete(builder.length() - " OR ".length(), builder.length() - 1); return builder.toString(); } private void getFileSelection(SelectionBuilder builder, Context context) { if(files == null || files.size() == 0) { builder.where("NOT " + OrgData.FILE_ID + "=?", Long.toString(getFileId(OrgFile.AGENDA_FILE, context.getContentResolver()))); return; } StringBuilder stringBuilder = new StringBuilder(); for (String filename: files) { long fileId = getFileId(filename, context.getContentResolver()); stringBuilder.append(OrgData.FILE_ID + "=" + Long.toString(fileId)).append(" OR "); } stringBuilder.delete(stringBuilder.length() - " OR ".length(), stringBuilder.length() - 1); builder.where(stringBuilder.toString()); } private long getFileId(String filename, ContentResolver resolver) { try { OrgFile agendaFile = new OrgFile(filename, resolver); return agendaFile.id; } catch (OrgFileNotFoundException e) { return -1;} } }
true
true
public SelectionBuilder getQuery(Context context) { final SelectionBuilder builder = new SelectionBuilder(); builder.table(Tables.ORGDATA); getFileSelection(builder, context); if (activeTodos) builder.where(getSelection(OrgProviderUtils.getActiveTodos(context .getContentResolver()), OrgData.TODO)); if(todos != null && todos.size() > 0) builder.where(getSelection(todos, OrgData.TODO)); if(tags != null && tags.size() > 0) builder.where(getLikeSelection(tags, OrgData.TAGS) + " OR " + getLikeSelection(tags, OrgData.TAGS_INHERITED)); if(priorities != null && priorities.size() > 0) builder.where(getSelection(priorities, OrgData.PRIORITY)); if(payloads != null && payloads.size() > 0) builder.where(getLikeSelection(payloads, OrgData.PAYLOAD)); if(filterHabits) builder.where("NOT " + OrgData.PAYLOAD + " LIKE ?", "'%:STYLE: habit%'"); return builder; }
public SelectionBuilder getQuery(Context context) { final SelectionBuilder builder = new SelectionBuilder(); builder.table(Tables.ORGDATA); getFileSelection(builder, context); if (activeTodos) builder.where(getSelection(OrgProviderUtils.getActiveTodos(context .getContentResolver()), OrgData.TODO)); if(todos != null && todos.size() > 0) builder.where(getSelection(todos, OrgData.TODO)); if(tags != null && tags.size() > 0) builder.where(getLikeSelection(tags, OrgData.TAGS) + " OR " + getLikeSelection(tags, OrgData.TAGS_INHERITED)); if(priorities != null && priorities.size() > 0) builder.where(getSelection(priorities, OrgData.PRIORITY)); if(payloads != null && payloads.size() > 0) builder.where(getLikeSelection(payloads, OrgData.PAYLOAD)); if(filterHabits) builder.where("NOT " + OrgData.PAYLOAD + " LIKE ?", "%:STYLE: habit%"); return builder; }
diff --git a/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/tests/MonitorTest.java b/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/tests/MonitorTest.java index 84ca5879..03ab8332 100644 --- a/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/tests/MonitorTest.java +++ b/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/tests/MonitorTest.java @@ -1,156 +1,156 @@ /******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ /* * Created on Jun 9, 2005 */ package org.eclipse.mylar.monitor.tests; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import junit.framework.TestCase; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylar.core.InteractionEvent; import org.eclipse.mylar.core.MylarPlugin; import org.eclipse.mylar.monitor.InteractionEventLogger; import org.eclipse.mylar.monitor.MylarMonitorPlugin; import org.eclipse.mylar.monitor.monitors.BrowserMonitor; import org.eclipse.mylar.monitor.monitors.KeybindingCommandMonitor; import org.eclipse.mylar.monitor.monitors.PerspectiveChangeMonitor; import org.eclipse.mylar.monitor.monitors.SelectionMonitor; import org.eclipse.ui.IPerspectiveDescriptor; import org.eclipse.ui.IPerspectiveRegistry; import org.eclipse.ui.internal.Workbench; /** * @author Mik Kersten */ public class MonitorTest extends TestCase { private InteractionEventLogger logger = MylarMonitorPlugin.getDefault().getInteractionLogger(); private SelectionMonitor selectionMonitor = new SelectionMonitor(); private KeybindingCommandMonitor commandMonitor = new KeybindingCommandMonitor(); private BrowserMonitor browserMonitor = new BrowserMonitor(); private PerspectiveChangeMonitor perspectiveMonitor = new PerspectiveChangeMonitor(); @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testEnablement() throws IOException { File monitorFile = MylarMonitorPlugin.getDefault().getMonitorLogFile(); assertTrue(monitorFile.exists()); MylarMonitorPlugin.getDefault().stopMonitoring(); logger.clearInteractionHistory(); assertEquals(0, logger.getHistoryFromFile(monitorFile).size()); generateSelection(); assertEquals(0, logger.getHistoryFromFile(monitorFile).size()); MylarMonitorPlugin.getDefault().startMonitoring(); generateSelection(); assertEquals(1, logger.getHistoryFromFile(monitorFile).size()); MylarMonitorPlugin.getDefault().stopMonitoring(); generateSelection(); assertEquals(1, logger.getHistoryFromFile(monitorFile).size()); MylarMonitorPlugin.getDefault().startMonitoring(); generateSelection(); assertEquals(2, logger.getHistoryFromFile(monitorFile).size()); MylarMonitorPlugin.getDefault().stopMonitoring(); } // public void testLogFileMove() throws IOException { // File defaultFile = MylarMonitorPlugin.getDefault().getMonitorLogFile(); // MylarMonitorPlugin.getDefault().stopMonitoring(); // assertTrue(logger.clearInteractionHistory()); // // MylarMonitorPlugin.getDefault().startMonitoring(); // generateSelection(); // generateSelection(); // assertEquals(2, logger.getHistoryFromFile(defaultFile).size()); // // File newFile = MylarMonitorPlugin.getDefault().moveMonitorLogFile(MylarPlugin.getDefault().getMylarDataDirectory() + "/monitor-test-new.xml"); // assertNotNull(newFile); // File movedFile = MylarMonitorPlugin.getDefault().getMonitorLogFile(); // assertTrue(!newFile.equals(defaultFile)); // assertEquals(newFile, movedFile); // assertEquals(newFile, logger.getOutputFile()); // assertEquals(2, logger.getHistoryFromFile(newFile).size()); // assertEquals(0, logger.getHistoryFromFile(defaultFile).size()); // // generateSelection(); // assertEquals(3, logger.getHistoryFromFile(newFile).size()); // File restoredFile = MylarMonitorPlugin.getDefault().moveMonitorLogFile(defaultFile.getAbsolutePath()); // assertNotNull(restoredFile); // } public void testUrlFilter() { browserMonitor.setAcceptedUrls("url1,url2,url3"); assertEquals(3, browserMonitor.getAcceptedUrls().size()); browserMonitor.setAcceptedUrls(null); assertEquals(0, browserMonitor.getAcceptedUrls().size()); browserMonitor.setAcceptedUrls(""); assertEquals(0, browserMonitor.getAcceptedUrls().size()); } public void testLogging() throws InterruptedException { MylarMonitorPlugin.getDefault().startMonitoring(); logger.stopObserving(); MylarMonitorPlugin.getDefault().getMonitorLogFile().delete(); logger.startObserving(); generateSelection(); commandMonitor.preExecute("foo.command", new ExecutionEvent(new HashMap(), "trigger", "context")); File monitorFile = MylarMonitorPlugin.getDefault().getMonitorLogFile(); assertTrue(monitorFile.exists()); logger.stopObserving(); List<InteractionEvent> events = logger.getHistoryFromFile(monitorFile); - assertTrue(events.size() >= 2); + assertTrue(""+events.size(), events.size() >= 2); logger.stopObserving(); events = logger.getHistoryFromFile(monitorFile); assertTrue(events.size() >= 0); MylarMonitorPlugin.getDefault().getMonitorLogFile().delete(); logger.startObserving(); generatePerspectiveSwitch(); assertTrue(monitorFile.exists()); logger.stopObserving(); events = logger.getHistoryFromFile(monitorFile); assertTrue(events.size() >= 1); } private void generateSelection() { selectionMonitor.selectionChanged( Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActivePart(), new StructuredSelection("yo")); } private void generatePerspectiveSwitch() { IPerspectiveRegistry registry = MylarPlugin.getDefault().getWorkbench().getPerspectiveRegistry(); IPerspectiveDescriptor perspective = registry.clonePerspective("newId","newLabel",registry.getPerspectives()[0]); perspectiveMonitor.perspectiveActivated(null, perspective); } }
true
true
public void testLogging() throws InterruptedException { MylarMonitorPlugin.getDefault().startMonitoring(); logger.stopObserving(); MylarMonitorPlugin.getDefault().getMonitorLogFile().delete(); logger.startObserving(); generateSelection(); commandMonitor.preExecute("foo.command", new ExecutionEvent(new HashMap(), "trigger", "context")); File monitorFile = MylarMonitorPlugin.getDefault().getMonitorLogFile(); assertTrue(monitorFile.exists()); logger.stopObserving(); List<InteractionEvent> events = logger.getHistoryFromFile(monitorFile); assertTrue(events.size() >= 2); logger.stopObserving(); events = logger.getHistoryFromFile(monitorFile); assertTrue(events.size() >= 0); MylarMonitorPlugin.getDefault().getMonitorLogFile().delete(); logger.startObserving(); generatePerspectiveSwitch(); assertTrue(monitorFile.exists()); logger.stopObserving(); events = logger.getHistoryFromFile(monitorFile); assertTrue(events.size() >= 1); }
public void testLogging() throws InterruptedException { MylarMonitorPlugin.getDefault().startMonitoring(); logger.stopObserving(); MylarMonitorPlugin.getDefault().getMonitorLogFile().delete(); logger.startObserving(); generateSelection(); commandMonitor.preExecute("foo.command", new ExecutionEvent(new HashMap(), "trigger", "context")); File monitorFile = MylarMonitorPlugin.getDefault().getMonitorLogFile(); assertTrue(monitorFile.exists()); logger.stopObserving(); List<InteractionEvent> events = logger.getHistoryFromFile(monitorFile); assertTrue(""+events.size(), events.size() >= 2); logger.stopObserving(); events = logger.getHistoryFromFile(monitorFile); assertTrue(events.size() >= 0); MylarMonitorPlugin.getDefault().getMonitorLogFile().delete(); logger.startObserving(); generatePerspectiveSwitch(); assertTrue(monitorFile.exists()); logger.stopObserving(); events = logger.getHistoryFromFile(monitorFile); assertTrue(events.size() >= 1); }
diff --git a/src/org/compiere/model/MInOut.java b/src/org/compiere/model/MInOut.java index d98105e..f34e579 100644 --- a/src/org/compiere/model/MInOut.java +++ b/src/org/compiere/model/MInOut.java @@ -1,2305 +1,2307 @@ /****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via [email protected] or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.io.File; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import org.adempiere.exceptions.AdempiereException; import org.adempiere.process.AllocateSalesOrders; import org.compiere.print.ReportEngine; import org.compiere.process.DocAction; import org.compiere.process.DocumentEngine; import org.compiere.util.CLogger; import org.compiere.util.DB; import org.compiere.util.Env; import org.compiere.util.Msg; /** * Shipment Model * * @author Jorg Janke * @version $Id: MInOut.java,v 1.4 2006/07/30 00:51:03 jjanke Exp $ * * Modifications: Added the RMA functionality (Ashley Ramdass) * @author Karsten Thiemann, Schaeffer AG * <li>Bug [ 1759431 ] Problems with VCreateFrom * @author [email protected], e-Evolution http://www.e-evolution.com * <li>FR [ 1948157 ] Is necessary the reference for document reverse * <li> FR [ 2520591 ] Support multiples calendar for Org * @see http://sourceforge.net/tracker2/?func=detail&atid=879335&aid=2520591&group_id=176962 * @author Armen Rizal, Goodwill Consulting * <li>BF [ 1745154 ] Cost in Reversing Material Related Docs * @see http://sourceforge.net/tracker/?func=detail&atid=879335&aid=1948157&group_id=176962 * @author Teo Sarca, [email protected] * <li>BF [ 2993853 ] Voiding/Reversing Receipt should void confirmations * https://sourceforge.net/tracker/?func=detail&atid=879332&aid=2993853&group_id=176962 */ public class MInOut extends X_M_InOut implements DocAction { /** * */ private static final long serialVersionUID = -239302197968535277L; /** * Create Shipment From Order * @param order order * @param oLines order lines to use when creating the shipment. If null all lines * from the order is used. * @param movementDate optional movement date * @param forceDelivery ignore order delivery rule * @param allAttributeInstances if true, all attribute set instances * @param minGuaranteeDate optional minimum guarantee date if all attribute instances * @param complete complete document (Process if false, Complete if true) * @param trxName transaction * @return Shipment or null */ public static MInOut createFrom (MOrder order, MOrderLine[] oLines, Timestamp movementDate, boolean forceDelivery, boolean allAttributeInstances, Timestamp minGuaranteeDate, boolean complete, String trxName) { if (order == null) throw new IllegalArgumentException("No Order"); // if (!forceDelivery && DELIVERYRULE_CompleteLine.equals(order.getDeliveryRule())) { return null; } // Create Header MInOut retValue = new MInOut (order, 0, movementDate); retValue.setDocAction(complete ? DOCACTION_Complete : DOCACTION_Prepare); if (oLines == null) { oLines = order.getLines(true, "M_Product_ID"); } for (int i = 0; i < oLines.length; i++) { if (oLines[i].getC_Order_ID()!=order.get_ID()) { // If the orderline ID and order ID doesn't match, skip the line continue; } // Calculate how much is left to deliver (ordered - delivered) BigDecimal qty = oLines[i].getQtyOrdered().subtract(oLines[i].getQtyDelivered()); // Nothing to deliver if (qty.signum() == 0) continue; // Stock Info MStorage[] storages = null; MProduct product = oLines[i].getProduct(); // If the order line is a product (not a charge) and the product is stocked, find the locators if (product != null && product.get_ID() != 0 && product.isStocked()) { String MMPolicy = product.getMMPolicy(); storages = MStorage.getWarehouse (order.getCtx(), order.getM_Warehouse_ID(), oLines[i].getM_Product_ID(), oLines[i].getM_AttributeSetInstance_ID(), minGuaranteeDate, MClient.MMPOLICY_FiFo.equals(MMPolicy), true, 0, trxName); } else { // If the order is a charge or the product is not stocked, don't try to deliver it. continue; } // Unless the order is force delivery then check delivery rule if (!forceDelivery) { BigDecimal maxQty = Env.ZERO; for (int ll = 0; ll < storages.length; ll++) maxQty = maxQty.add(storages[ll].getQtyOnHand()); if (DELIVERYRULE_Availability.equals(order.getDeliveryRule())) { if (maxQty.compareTo(qty) < 0) qty = maxQty; } else if (DELIVERYRULE_CompleteLine.equals(order.getDeliveryRule()) || DELIVERYRULE_CompleteOrder.equals(order.getDeliveryRule())) { if (maxQty.compareTo(qty) < 0) // Not enough to deliver the complete line continue; } } // Create Line if (retValue.get_ID() == 0) // not saved yet retValue.save(trxName); // Create a line until qty is reached // There will be one line per storage (if there items are stored in more than one storage) for (int ll = 0; ll < storages.length; ll++) { // Set lineQty to what's available in the storage BigDecimal lineQty = storages[ll].getQtyOnHand(); // If lineQty is more than enough, set lineQty to original qty to be delivered. if (lineQty.compareTo(qty) > 0) lineQty = qty; MInOutLine line = new MInOutLine (retValue); line.setOrderLine(oLines[i], storages[ll].getM_Locator_ID(), order.isSOTrx() ? lineQty : Env.ZERO); line.setQty(lineQty); // Correct UOM for QtyEntered if (oLines[i].getQtyEntered().compareTo(oLines[i].getQtyOrdered()) != 0) line.setQtyEntered(lineQty .multiply(oLines[i].getQtyEntered()) .divide(oLines[i].getQtyOrdered(), 12, BigDecimal.ROUND_HALF_UP)); // Set project ID if any line.setC_Project_ID(oLines[i].getC_Project_ID()); line.save(trxName); // Delivered everything ? qty = qty.subtract(lineQty); // storage[ll].changeQtyOnHand(lineQty, !order.isSOTrx()); // Credit Memo not considered // storage[ll].save(get_TrxName()); if (qty.signum() == 0) break; } } // for all order lines // No Lines saved if (retValue.get_ID() == 0) return null; return retValue; } /** * Create Shipment From Order (using all order lines) * @param order order * @param movementDate optional movement date * @param forceDelivery ignore order delivery rule * @param allAttributeInstances if true, all attribute set instances * @param minGuaranteeDate optional minimum guarantee date if all attribute instances * @param complete complete document (Process if false, Complete if true) * @param trxName transaction * @return Shipment or null */ public static MInOut createFrom (MOrder order, Timestamp movementDate, boolean forceDelivery, boolean allAttributeInstances, Timestamp minGuaranteeDate, boolean complete, String trxName) { // Select all lines of the order MOrderLine[] oLines = order.getLines(true, "M_Product_ID"); return createFrom(order, oLines, movementDate, forceDelivery, allAttributeInstances, minGuaranteeDate,complete,trxName); } // createFrom /** * Create new Shipment by copying * @param from shipment * @param dateDoc date of the document date * @param C_DocType_ID doc type * @param isSOTrx sales order * @param counter create counter links * @param trxName trx * @param setOrder set the order link * @return Shipment */ public static MInOut copyFrom (MInOut from, Timestamp dateDoc, Timestamp dateAcct, int C_DocType_ID, boolean isSOTrx, boolean counter, String trxName, boolean setOrder) { MInOut to = new MInOut (from.getCtx(), 0, null); to.set_TrxName(trxName); copyValues(from, to, from.getAD_Client_ID(), from.getAD_Org_ID()); to.set_ValueNoCheck ("M_InOut_ID", I_ZERO); to.set_ValueNoCheck ("DocumentNo", null); // to.setDocStatus (DOCSTATUS_Drafted); // Draft to.setDocAction(DOCACTION_Complete); // to.setC_DocType_ID (C_DocType_ID); to.setIsSOTrx(isSOTrx); if (counter) { MDocType docType = MDocType.get(from.getCtx(), C_DocType_ID); if (MDocType.DOCBASETYPE_MaterialDelivery.equals(docType.getDocBaseType())) { to.setMovementType (isSOTrx ? MOVEMENTTYPE_CustomerShipment : MOVEMENTTYPE_VendorReturns); } else if (MDocType.DOCBASETYPE_MaterialReceipt.equals(docType.getDocBaseType())) { to.setMovementType (isSOTrx ? MOVEMENTTYPE_CustomerReturns : MOVEMENTTYPE_VendorReceipts); } } // to.setDateOrdered (dateDoc); to.setDateAcct (dateAcct); to.setMovementDate(dateDoc); to.setDatePrinted(null); to.setIsPrinted (false); to.setDateReceived(null); to.setNoPackages(0); to.setShipDate(null); to.setPickDate(null); to.setIsInTransit(false); // to.setIsApproved (false); to.setC_Invoice_ID(0); to.setTrackingNo(null); to.setIsInDispute(false); // to.setPosted (false); to.setProcessed (false); //[ 1633721 ] Reverse Documents- Processing=Y to.setProcessing(false); to.setC_Order_ID(0); // Overwritten by setOrder to.setM_RMA_ID(0); // Overwritten by setOrder if (counter) { to.setC_Order_ID(0); to.setRef_InOut_ID(from.getM_InOut_ID()); // Try to find Order/Invoice link if (from.getC_Order_ID() != 0) { MOrder peer = new MOrder (from.getCtx(), from.getC_Order_ID(), from.get_TrxName()); if (peer.getRef_Order_ID() != 0) to.setC_Order_ID(peer.getRef_Order_ID()); } if (from.getC_Invoice_ID() != 0) { MInvoice peer = new MInvoice (from.getCtx(), from.getC_Invoice_ID(), from.get_TrxName()); if (peer.getRef_Invoice_ID() != 0) to.setC_Invoice_ID(peer.getRef_Invoice_ID()); } //find RMA link if (from.getM_RMA_ID() != 0) { MRMA peer = new MRMA (from.getCtx(), from.getM_RMA_ID(), from.get_TrxName()); if (peer.getRef_RMA_ID() > 0) to.setM_RMA_ID(peer.getRef_RMA_ID()); } } else { to.setRef_InOut_ID(0); if (setOrder) { to.setC_Order_ID(from.getC_Order_ID()); to.setM_RMA_ID(from.getM_RMA_ID()); // Copy also RMA } } // if (!to.save(trxName)) throw new IllegalStateException("Could not create Shipment"); if (counter) from.setRef_InOut_ID(to.getM_InOut_ID()); if (to.copyLinesFrom(from, counter, setOrder) == 0) throw new IllegalStateException("Could not create Shipment Lines"); return to; } // copyFrom /** * @deprecated * Create new Shipment by copying * @param from shipment * @param dateDoc date of the document date * @param C_DocType_ID doc type * @param isSOTrx sales order * @param counter create counter links * @param trxName trx * @param setOrder set the order link * @return Shipment */ public static MInOut copyFrom (MInOut from, Timestamp dateDoc, int C_DocType_ID, boolean isSOTrx, boolean counter, String trxName, boolean setOrder) { MInOut to = copyFrom ( from, dateDoc, dateDoc, C_DocType_ID, isSOTrx, counter, trxName, setOrder); return to; } /************************************************************************** * Standard Constructor * @param ctx context * @param M_InOut_ID * @param trxName rx name */ public MInOut (Properties ctx, int M_InOut_ID, String trxName) { super (ctx, M_InOut_ID, trxName); if (M_InOut_ID == 0) { // setDocumentNo (null); // setC_BPartner_ID (0); // setC_BPartner_Location_ID (0); // setM_Warehouse_ID (0); // setC_DocType_ID (0); setIsSOTrx (false); setMovementDate (new Timestamp (System.currentTimeMillis ())); setDateAcct (getMovementDate()); // setMovementType (MOVEMENTTYPE_CustomerShipment); setDeliveryRule (DELIVERYRULE_Availability); setDeliveryViaRule (DELIVERYVIARULE_Pickup); setFreightCostRule (FREIGHTCOSTRULE_FreightIncluded); setDocStatus (DOCSTATUS_Drafted); setDocAction (DOCACTION_Complete); setPriorityRule (PRIORITYRULE_Medium); setNoPackages(0); setIsInTransit(false); setIsPrinted (false); setSendEMail (false); setIsInDispute(false); // setIsApproved(false); super.setProcessed (false); setProcessing(false); setPosted(false); } } // MInOut /** * Load Constructor * @param ctx context * @param rs result set record * @param trxName transaction */ public MInOut (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MInOut /** * Order Constructor - create header only * @param order order * @param movementDate optional movement date (default today) * @param C_DocTypeShipment_ID document type or 0 */ public MInOut (MOrder order, int C_DocTypeShipment_ID, Timestamp movementDate) { this (order.getCtx(), 0, order.get_TrxName()); setClientOrg(order); setC_BPartner_ID (order.getC_BPartner_ID()); setC_BPartner_Location_ID (order.getC_BPartner_Location_ID()); // shipment address setAD_User_ID(order.getAD_User_ID()); // setM_Warehouse_ID (order.getM_Warehouse_ID()); setIsSOTrx (order.isSOTrx()); if (C_DocTypeShipment_ID == 0) C_DocTypeShipment_ID = DB.getSQLValue(null, "SELECT C_DocTypeShipment_ID FROM C_DocType WHERE C_DocType_ID=?", order.getC_DocType_ID()); setC_DocType_ID (C_DocTypeShipment_ID); // patch suggested by Armen // setMovementType (order.isSOTrx() ? MOVEMENTTYPE_CustomerShipment : MOVEMENTTYPE_VendorReceipts); String movementTypeShipment = null; MDocType dtShipment = new MDocType(order.getCtx(), C_DocTypeShipment_ID, order.get_TrxName()); if (dtShipment.getDocBaseType().equals(MDocType.DOCBASETYPE_MaterialDelivery)) movementTypeShipment = dtShipment.isSOTrx() ? MOVEMENTTYPE_CustomerShipment : MOVEMENTTYPE_VendorReturns; else if (dtShipment.getDocBaseType().equals(MDocType.DOCBASETYPE_MaterialReceipt)) movementTypeShipment = dtShipment.isSOTrx() ? MOVEMENTTYPE_CustomerReturns : MOVEMENTTYPE_VendorReceipts; setMovementType (movementTypeShipment); // Default - Today if (movementDate != null) setMovementDate (movementDate); setDateAcct (getMovementDate()); // Copy from Order setC_Order_ID(order.getC_Order_ID()); setDeliveryRule (order.getDeliveryRule()); setDeliveryViaRule (order.getDeliveryViaRule()); setM_Shipper_ID(order.getM_Shipper_ID()); setFreightCostRule (order.getFreightCostRule()); setFreightAmt(order.getFreightAmt()); setSalesRep_ID(order.getSalesRep_ID()); // setC_Activity_ID(order.getC_Activity_ID()); setC_Campaign_ID(order.getC_Campaign_ID()); setC_Charge_ID(order.getC_Charge_ID()); setChargeAmt(order.getChargeAmt()); // setC_Project_ID(order.getC_Project_ID()); setDateOrdered(order.getDateOrdered()); setDescription(order.getDescription()); setPOReference(order.getPOReference()); setSalesRep_ID(order.getSalesRep_ID()); setAD_OrgTrx_ID(order.getAD_OrgTrx_ID()); setUser1_ID(order.getUser1_ID()); setUser2_ID(order.getUser2_ID()); setPriorityRule(order.getPriorityRule()); // Drop shipment setIsDropShip(order.isDropShip()); setDropShip_BPartner_ID(order.getDropShip_BPartner_ID()); setDropShip_Location_ID(order.getDropShip_Location_ID()); setDropShip_User_ID(order.getDropShip_User_ID()); } // MInOut /** * Invoice Constructor - create header only * @param invoice invoice * @param C_DocTypeShipment_ID document type or 0 * @param movementDate optional movement date (default today) * @param M_Warehouse_ID warehouse */ public MInOut (MInvoice invoice, int C_DocTypeShipment_ID, Timestamp movementDate, int M_Warehouse_ID) { this (invoice.getCtx(), 0, invoice.get_TrxName()); setClientOrg(invoice); setC_BPartner_ID (invoice.getC_BPartner_ID()); setC_BPartner_Location_ID (invoice.getC_BPartner_Location_ID()); // shipment address setAD_User_ID(invoice.getAD_User_ID()); // setM_Warehouse_ID (M_Warehouse_ID); setIsSOTrx (invoice.isSOTrx()); setMovementType (invoice.isSOTrx() ? MOVEMENTTYPE_CustomerShipment : MOVEMENTTYPE_VendorReceipts); MOrder order = null; if (invoice.getC_Order_ID() != 0) order = new MOrder (invoice.getCtx(), invoice.getC_Order_ID(), invoice.get_TrxName()); if (C_DocTypeShipment_ID == 0 && order != null) C_DocTypeShipment_ID = DB.getSQLValue(null, "SELECT C_DocTypeShipment_ID FROM C_DocType WHERE C_DocType_ID=?", order.getC_DocType_ID()); if (C_DocTypeShipment_ID != 0) setC_DocType_ID (C_DocTypeShipment_ID); else setC_DocType_ID(); // Default - Today if (movementDate != null) setMovementDate (movementDate); setDateAcct (getMovementDate()); // Copy from Invoice setC_Order_ID(invoice.getC_Order_ID()); setSalesRep_ID(invoice.getSalesRep_ID()); // setC_Activity_ID(invoice.getC_Activity_ID()); setC_Campaign_ID(invoice.getC_Campaign_ID()); setC_Charge_ID(invoice.getC_Charge_ID()); setChargeAmt(invoice.getChargeAmt()); // setC_Project_ID(invoice.getC_Project_ID()); setDateOrdered(invoice.getDateOrdered()); setDescription(invoice.getDescription()); setPOReference(invoice.getPOReference()); setAD_OrgTrx_ID(invoice.getAD_OrgTrx_ID()); setUser1_ID(invoice.getUser1_ID()); setUser2_ID(invoice.getUser2_ID()); if (order != null) { setDeliveryRule (order.getDeliveryRule()); setDeliveryViaRule (order.getDeliveryViaRule()); setM_Shipper_ID(order.getM_Shipper_ID()); setFreightCostRule (order.getFreightCostRule()); setFreightAmt(order.getFreightAmt()); // Drop Shipment setIsDropShip(order.isDropShip()); setDropShip_BPartner_ID(order.getDropShip_BPartner_ID()); setDropShip_Location_ID(order.getDropShip_Location_ID()); setDropShip_User_ID(order.getDropShip_User_ID()); } } // MInOut /** * Copy Constructor - create header only * @param original original * @param movementDate optional movement date (default today) * @param C_DocTypeShipment_ID document type or 0 */ public MInOut (MInOut original, int C_DocTypeShipment_ID, Timestamp movementDate) { this (original.getCtx(), 0, original.get_TrxName()); setClientOrg(original); setC_BPartner_ID (original.getC_BPartner_ID()); setC_BPartner_Location_ID (original.getC_BPartner_Location_ID()); // shipment address setAD_User_ID(original.getAD_User_ID()); // setM_Warehouse_ID (original.getM_Warehouse_ID()); setIsSOTrx (original.isSOTrx()); setMovementType (original.getMovementType()); if (C_DocTypeShipment_ID == 0) setC_DocType_ID(original.getC_DocType_ID()); else setC_DocType_ID (C_DocTypeShipment_ID); // Default - Today if (movementDate != null) setMovementDate (movementDate); setDateAcct (getMovementDate()); // Copy from Order setC_Order_ID(original.getC_Order_ID()); setDeliveryRule (original.getDeliveryRule()); setDeliveryViaRule (original.getDeliveryViaRule()); setM_Shipper_ID(original.getM_Shipper_ID()); setFreightCostRule (original.getFreightCostRule()); setFreightAmt(original.getFreightAmt()); setSalesRep_ID(original.getSalesRep_ID()); // setC_Activity_ID(original.getC_Activity_ID()); setC_Campaign_ID(original.getC_Campaign_ID()); setC_Charge_ID(original.getC_Charge_ID()); setChargeAmt(original.getChargeAmt()); // setC_Project_ID(original.getC_Project_ID()); setDateOrdered(original.getDateOrdered()); setDescription(original.getDescription()); setPOReference(original.getPOReference()); setSalesRep_ID(original.getSalesRep_ID()); setAD_OrgTrx_ID(original.getAD_OrgTrx_ID()); setUser1_ID(original.getUser1_ID()); setUser2_ID(original.getUser2_ID()); // DropShipment setIsDropShip(original.isDropShip()); setDropShip_BPartner_ID(original.getDropShip_BPartner_ID()); setDropShip_Location_ID(original.getDropShip_Location_ID()); setDropShip_User_ID(original.getDropShip_User_ID()); } // MInOut /** Lines */ private MInOutLine[] m_lines = null; /** Confirmations */ private MInOutConfirm[] m_confirms = null; /** BPartner */ private MBPartner m_partner = null; /** * Get Document Status * @return Document Status Clear Text */ public String getDocStatusName() { return MRefList.getListName(getCtx(), 131, getDocStatus()); } // getDocStatusName /** * Add to Description * @param description text */ public void addDescription (String description) { String desc = getDescription(); if (desc == null) setDescription(description); else setDescription(desc + " | " + description); } // addDescription /** * String representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MInOut[") .append (get_ID()).append("-").append(getDocumentNo()) .append(",DocStatus=").append(getDocStatus()) .append ("]"); return sb.toString (); } // toString /** * Get Document Info * @return document info (untranslated) */ public String getDocumentInfo() { MDocType dt = MDocType.get(getCtx(), getC_DocType_ID()); return dt.getName() + " " + getDocumentNo(); } // getDocumentInfo /** * Create PDF * @return File or null */ public File createPDF () { try { File temp = File.createTempFile(get_TableName()+get_ID()+"_", ".pdf"); return createPDF (temp); } catch (Exception e) { log.severe("Could not create PDF - " + e.getMessage()); } return null; } // getPDF /** * Create PDF file * @param file output file * @return file if success */ public File createPDF (File file) { ReportEngine re = ReportEngine.get (getCtx(), ReportEngine.SHIPMENT, getM_InOut_ID(), get_TrxName()); if (re == null) return null; return re.getPDF(file); } // createPDF /** * Get Lines of Shipment * @param requery refresh from db * @return lines */ public MInOutLine[] getLines (boolean requery) { if (m_lines != null && !requery) { set_TrxName(m_lines, get_TrxName()); return m_lines; } List<MInOutLine> list = new Query(getCtx(), I_M_InOutLine.Table_Name, "M_InOut_ID=?", get_TrxName()) .setParameters(getM_InOut_ID()) .setOrderBy(MInOutLine.COLUMNNAME_Line) .list(); // m_lines = new MInOutLine[list.size()]; list.toArray(m_lines); return m_lines; } // getMInOutLines /** * Get Lines of Shipment * @return lines */ public MInOutLine[] getLines() { return getLines(false); } // getLines /** * Get Confirmations * @param requery requery * @return array of Confirmations */ public MInOutConfirm[] getConfirmations(boolean requery) { if (m_confirms != null && !requery) { set_TrxName(m_confirms, get_TrxName()); return m_confirms; } List<MInOutConfirm> list = new Query(getCtx(), I_M_InOutConfirm.Table_Name, "M_InOut_ID=?", get_TrxName()) .setParameters(getM_InOut_ID()) .list(); m_confirms = new MInOutConfirm[list.size ()]; list.toArray (m_confirms); return m_confirms; } // getConfirmations /** * Copy Lines From other Shipment * @param otherShipment shipment * @param counter set counter info * @param setOrder set order link * @return number of lines copied */ public int copyLinesFrom (MInOut otherShipment, boolean counter, boolean setOrder) { if (isProcessed() || isPosted() || otherShipment == null) return 0; MInOutLine[] fromLines = otherShipment.getLines(false); int count = 0; for (int i = 0; i < fromLines.length; i++) { MInOutLine line = new MInOutLine (this); MInOutLine fromLine = fromLines[i]; line.set_TrxName(get_TrxName()); if (counter) // header PO.copyValues(fromLine, line, getAD_Client_ID(), getAD_Org_ID()); else PO.copyValues(fromLine, line, fromLine.getAD_Client_ID(), fromLine.getAD_Org_ID()); line.setM_InOut_ID(getM_InOut_ID()); line.set_ValueNoCheck ("M_InOutLine_ID", I_ZERO); // new // Reset if (!setOrder) { line.setC_OrderLine_ID(0); line.setM_RMALine_ID(0); // Reset RMA Line } if (!counter) line.setM_AttributeSetInstance_ID(0); // line.setS_ResourceAssignment_ID(0); line.setRef_InOutLine_ID(0); line.setIsInvoiced(false); // line.setConfirmedQty(Env.ZERO); line.setPickedQty(Env.ZERO); line.setScrappedQty(Env.ZERO); line.setTargetQty(Env.ZERO); // Set Locator based on header Warehouse if (getM_Warehouse_ID() != otherShipment.getM_Warehouse_ID()) { line.setM_Locator_ID(0); line.setM_Locator_ID(Env.ZERO); } // if (counter) { line.setRef_InOutLine_ID(fromLine.getM_InOutLine_ID()); if (fromLine.getC_OrderLine_ID() != 0) { MOrderLine peer = new MOrderLine (getCtx(), fromLine.getC_OrderLine_ID(), get_TrxName()); if (peer.getRef_OrderLine_ID() != 0) line.setC_OrderLine_ID(peer.getRef_OrderLine_ID()); } //RMALine link if (fromLine.getM_RMALine_ID() != 0) { MRMALine peer = new MRMALine (getCtx(), fromLine.getM_RMALine_ID(), get_TrxName()); if (peer.getRef_RMALine_ID() > 0) line.setM_RMALine_ID(peer.getRef_RMALine_ID()); } } // line.setProcessed(false); if (line.save(get_TrxName())) count++; // Cross Link if (counter) { fromLine.setRef_InOutLine_ID(line.getM_InOutLine_ID()); fromLine.save(get_TrxName()); } } if (fromLines.length != count) log.log(Level.SEVERE, "Line difference - From=" + fromLines.length + " <> Saved=" + count); return count; } // copyLinesFrom /** Reversal Flag */ private boolean m_reversal = false; /** * Set Reversal * @param reversal reversal */ private void setReversal(boolean reversal) { m_reversal = reversal; } // setReversal /** * Is Reversal * @return reversal */ public boolean isReversal() { return m_reversal; } // isReversal /** * Set Processed. * Propagate to Lines/Taxes * @param processed processed */ public void setProcessed (boolean processed) { super.setProcessed (processed); if (get_ID() == 0) return; String sql = "UPDATE M_InOutLine SET Processed='" + (processed ? "Y" : "N") + "' WHERE M_InOut_ID=" + getM_InOut_ID(); int noLine = DB.executeUpdate(sql, get_TrxName()); m_lines = null; log.fine(processed + " - Lines=" + noLine); } // setProcessed /** * Get BPartner * @return partner */ public MBPartner getBPartner() { if (m_partner == null) m_partner = new MBPartner (getCtx(), getC_BPartner_ID(), get_TrxName()); return m_partner; } // getPartner /** * Set Document Type * @param DocBaseType doc type MDocType.DOCBASETYPE_ */ public void setC_DocType_ID (String DocBaseType) { String sql = "SELECT C_DocType_ID FROM C_DocType " + "WHERE AD_Client_ID=? AND DocBaseType=?" + " AND IsActive='Y'" + " AND IsSOTrx='" + (isSOTrx() ? "Y" : "N") + "' " + "ORDER BY IsDefault DESC"; int C_DocType_ID = DB.getSQLValue(null, sql, getAD_Client_ID(), DocBaseType); if (C_DocType_ID <= 0) log.log(Level.SEVERE, "Not found for AC_Client_ID=" + getAD_Client_ID() + " - " + DocBaseType); else { log.fine("DocBaseType=" + DocBaseType + " - C_DocType_ID=" + C_DocType_ID); setC_DocType_ID (C_DocType_ID); boolean isSOTrx = MDocType.DOCBASETYPE_MaterialDelivery.equals(DocBaseType); setIsSOTrx (isSOTrx); } } // setC_DocType_ID /** * Set Default C_DocType_ID. * Based on SO flag */ public void setC_DocType_ID() { if (isSOTrx()) setC_DocType_ID(MDocType.DOCBASETYPE_MaterialDelivery); else setC_DocType_ID(MDocType.DOCBASETYPE_MaterialReceipt); } // setC_DocType_ID /** * Set Business Partner Defaults & Details * @param bp business partner */ public void setBPartner (MBPartner bp) { if (bp == null) return; setC_BPartner_ID(bp.getC_BPartner_ID()); // Set Locations MBPartnerLocation[] locs = bp.getLocations(false); if (locs != null) { for (int i = 0; i < locs.length; i++) { if (locs[i].isShipTo()) setC_BPartner_Location_ID(locs[i].getC_BPartner_Location_ID()); } // set to first if not set if (getC_BPartner_Location_ID() == 0 && locs.length > 0) setC_BPartner_Location_ID(locs[0].getC_BPartner_Location_ID()); } if (getC_BPartner_Location_ID() == 0) log.log(Level.SEVERE, "Has no To Address: " + bp); // Set Contact MUser[] contacts = bp.getContacts(false); if (contacts != null && contacts.length > 0) // get first User setAD_User_ID(contacts[0].getAD_User_ID()); } // setBPartner /** * Create the missing next Confirmation */ public void createConfirmation() { MDocType dt = MDocType.get(getCtx(), getC_DocType_ID()); boolean pick = dt.isPickQAConfirm(); boolean ship = dt.isShipConfirm(); // Nothing to do if (!pick && !ship) { log.fine("No need"); return; } // Create Both .. after each other if (pick && ship) { boolean havePick = false; boolean haveShip = false; MInOutConfirm[] confirmations = getConfirmations(false); for (int i = 0; i < confirmations.length; i++) { MInOutConfirm confirm = confirmations[i]; if (MInOutConfirm.CONFIRMTYPE_PickQAConfirm.equals(confirm.getConfirmType())) { if (!confirm.isProcessed()) // wait intil done { log.fine("Unprocessed: " + confirm); return; } havePick = true; } else if (MInOutConfirm.CONFIRMTYPE_ShipReceiptConfirm.equals(confirm.getConfirmType())) haveShip = true; } // Create Pick if (!havePick) { MInOutConfirm.create (this, MInOutConfirm.CONFIRMTYPE_PickQAConfirm, false); return; } // Create Ship if (!haveShip) { MInOutConfirm.create (this, MInOutConfirm.CONFIRMTYPE_ShipReceiptConfirm, false); return; } return; } // Create just one if (pick) MInOutConfirm.create (this, MInOutConfirm.CONFIRMTYPE_PickQAConfirm, true); else if (ship) MInOutConfirm.create (this, MInOutConfirm.CONFIRMTYPE_ShipReceiptConfirm, true); } // createConfirmation private void voidConfirmations() { for(MInOutConfirm confirm : getConfirmations(true)) { if (!confirm.isProcessed()) { if (!confirm.processIt(MInOutConfirm.DOCACTION_Void)) throw new AdempiereException(confirm.getProcessMsg()); confirm.saveEx(); } } } /** * Set Warehouse and check/set Organization * @param M_Warehouse_ID id */ public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID == 0) { log.severe("Ignored - Cannot set AD_Warehouse_ID to 0"); return; } super.setM_Warehouse_ID (M_Warehouse_ID); // MWarehouse wh = MWarehouse.get(getCtx(), getM_Warehouse_ID()); if (wh.getAD_Org_ID() != getAD_Org_ID()) { log.warning("M_Warehouse_ID=" + M_Warehouse_ID + ", Overwritten AD_Org_ID=" + getAD_Org_ID() + "->" + wh.getAD_Org_ID()); setAD_Org_ID(wh.getAD_Org_ID()); } } // setM_Warehouse_ID /** * Before Save * @param newRecord new * @return true or false */ protected boolean beforeSave (boolean newRecord) { // Warehouse Org if (newRecord) { MWarehouse wh = MWarehouse.get(getCtx(), getM_Warehouse_ID()); if (wh.getAD_Org_ID() != getAD_Org_ID()) { log.saveError("WarehouseOrgConflict", ""); return false; } } // Shipment/Receipt can have either Order/RMA (For Movement type) if (getC_Order_ID() != 0 && getM_RMA_ID() != 0) { log.saveError("OrderOrRMA", ""); return false; } // Shipment - Needs Order/RMA if (!getMovementType().contentEquals(MInOut.MOVEMENTTYPE_CustomerReturns) && isSOTrx() && getC_Order_ID() == 0 && getM_RMA_ID() == 0) { log.saveError("FillMandatory", Msg.translate(getCtx(), "C_Order_ID")); return false; } if (isSOTrx() && getM_RMA_ID() != 0) { // Set Document and Movement type for this Receipt MRMA rma = new MRMA(getCtx(), getM_RMA_ID(), get_TrxName()); MDocType docType = MDocType.get(getCtx(), rma.getC_DocType_ID()); setC_DocType_ID(docType.getC_DocTypeShipment_ID()); } return true; } // beforeSave /** * After Save * @param newRecord new * @param success success * @return success */ protected boolean afterSave (boolean newRecord, boolean success) { if (!success || newRecord) return success; if (is_ValueChanged("AD_Org_ID")) { String sql = "UPDATE M_InOutLine ol" + " SET AD_Org_ID =" + "(SELECT AD_Org_ID" + " FROM M_InOut o WHERE ol.M_InOut_ID=o.M_InOut_ID) " + "WHERE M_InOut_ID=" + getC_Order_ID(); int no = DB.executeUpdate(sql, get_TrxName()); log.fine("Lines -> #" + no); } return true; } // afterSave /************************************************************************** * Process document * @param processAction document action * @return true if performed */ public boolean processIt (String processAction) { m_processMsg = null; DocumentEngine engine = new DocumentEngine (this, getDocStatus()); return engine.processIt (processAction, getDocAction()); } // process /** Process Message */ private String m_processMsg = null; /** Just Prepared Flag */ private boolean m_justPrepared = false; /** * Unlock Document. * @return true if success */ public boolean unlockIt() { log.info(toString()); setProcessing(false); return true; } // unlockIt /** * Invalidate Document * @return true if success */ public boolean invalidateIt() { log.info(toString()); setDocAction(DOCACTION_Prepare); return true; } // invalidateIt /** * Prepare Document * @return new status (In Progress or Invalid) */ public String prepareIt() { log.info(toString()); m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE); if (m_processMsg != null) return DocAction.STATUS_Invalid; MDocType dt = MDocType.get(getCtx(), getC_DocType_ID()); // Order OR RMA can be processed on a shipment/receipt if (getC_Order_ID() != 0 && getM_RMA_ID() != 0) { m_processMsg = "@OrderOrRMA@"; return DocAction.STATUS_Invalid; } // Std Period open? if (!MPeriod.isOpen(getCtx(), getDateAcct(), dt.getDocBaseType(), getAD_Org_ID())) { m_processMsg = "@PeriodClosed@"; return DocAction.STATUS_Invalid; } // Credit Check if (isSOTrx() && !isReversal()) { I_C_Order order = getC_Order(); if (order != null && MDocType.DOCSUBTYPESO_PrepayOrder.equals(order.getC_DocType().getDocSubTypeSO()) && !MSysConfig.getBooleanValue("CHECK_CREDIT_ON_PREPAY_ORDER", true, getAD_Client_ID(), getAD_Org_ID())) { // ignore -- don't validate Prepay Orders depending on sysconfig parameter } else { MBPartner bp = new MBPartner (getCtx(), getC_BPartner_ID(), get_TrxName()); if (MBPartner.SOCREDITSTATUS_CreditStop.equals(bp.getSOCreditStatus())) { m_processMsg = "@BPartnerCreditStop@ - @TotalOpenBalance@=" + bp.getTotalOpenBalance() + ", @SO_CreditLimit@=" + bp.getSO_CreditLimit(); return DocAction.STATUS_Invalid; } if (MBPartner.SOCREDITSTATUS_CreditHold.equals(bp.getSOCreditStatus())) { m_processMsg = "@BPartnerCreditHold@ - @TotalOpenBalance@=" + bp.getTotalOpenBalance() + ", @SO_CreditLimit@=" + bp.getSO_CreditLimit(); return DocAction.STATUS_Invalid; } BigDecimal notInvoicedAmt = MBPartner.getNotInvoicedAmt(getC_BPartner_ID()); if (MBPartner.SOCREDITSTATUS_CreditHold.equals(bp.getSOCreditStatus(notInvoicedAmt))) { m_processMsg = "@BPartnerOverSCreditHold@ - @TotalOpenBalance@=" + bp.getTotalOpenBalance() + ", @NotInvoicedAmt@=" + notInvoicedAmt + ", @SO_CreditLimit@=" + bp.getSO_CreditLimit(); return DocAction.STATUS_Invalid; } } } // Lines MInOutLine[] lines = getLines(true); if (lines == null || lines.length == 0) { m_processMsg = "@NoLines@"; return DocAction.STATUS_Invalid; } BigDecimal Volume = Env.ZERO; BigDecimal Weight = Env.ZERO; // Mandatory Attributes for (int i = 0; i < lines.length; i++) { MInOutLine line = lines[i]; MProduct product = line.getProduct(); if (product != null) { Volume = Volume.add(product.getVolume().multiply(line.getMovementQty())); Weight = Weight.add(product.getWeight().multiply(line.getMovementQty())); } // if (line.getM_AttributeSetInstance_ID() != 0) continue; if (product != null && product.isASIMandatory(isSOTrx())) { m_processMsg = "@M_AttributeSet_ID@ @IsMandatory@ (@Line@ #" + lines[i].getLine() + ", @M_Product_ID@=" + product.getValue() + ")"; return DocAction.STATUS_Invalid; } } setVolume(Volume); setWeight(Weight); if (!isReversal()) // don't change reversal { createConfirmation(); } m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_PREPARE); if (m_processMsg != null) return DocAction.STATUS_Invalid; m_justPrepared = true; if (!DOCACTION_Complete.equals(getDocAction())) setDocAction(DOCACTION_Complete); return DocAction.STATUS_InProgress; } // prepareIt /** * Approve Document * @return true if success */ public boolean approveIt() { log.info(toString()); setIsApproved(true); return true; } // approveIt /** * Reject Approval * @return true if success */ public boolean rejectIt() { log.info(toString()); setIsApproved(false); return true; } // rejectIt /** * Complete Document * @return new status (Complete, In Progress, Invalid, Waiting ..) */ public String completeIt() { // Re-Check if (!m_justPrepared) { String status = prepareIt(); if (!DocAction.STATUS_InProgress.equals(status)) return status; } m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE); if (m_processMsg != null) return DocAction.STATUS_Invalid; // Outstanding (not processed) Incoming Confirmations ? MInOutConfirm[] confirmations = getConfirmations(true); for (int i = 0; i < confirmations.length; i++) { MInOutConfirm confirm = confirmations[i]; if (!confirm.isProcessed()) { if (MInOutConfirm.CONFIRMTYPE_CustomerConfirmation.equals(confirm.getConfirmType())) continue; // m_processMsg = "Open @M_InOutConfirm_ID@: " + confirm.getConfirmTypeName() + " - " + confirm.getDocumentNo(); return DocAction.STATUS_InProgress; } } // Implicit Approval if (!isApproved()) approveIt(); log.info(toString()); StringBuffer info = new StringBuffer(); // Set of shipped orders // Use this set to determine what orders are shipped on // this inout record. Set<Integer> inOutOrders = new TreeSet<Integer>(); // For all lines MInOutLine[] lines = getLines(false); for (int lineIndex = 0; lineIndex < lines.length; lineIndex++) { MInOutLine sLine = lines[lineIndex]; MProduct product = sLine.getProduct(); // Qty & Type String MovementType = getMovementType(); BigDecimal Qty = sLine.getMovementQty(); if (MovementType.charAt(1) == '-') // C- Customer Shipment - V- Vendor Return Qty = Qty.negate(); BigDecimal QtySO = Env.ZERO; BigDecimal QtyPO = Env.ZERO; // Update Order Line MOrderLine oLine = null; if (sLine.getC_OrderLine_ID() != 0) { oLine = new MOrderLine (getCtx(), sLine.getC_OrderLine_ID(), get_TrxName()); // Add order id to set of orders inOutOrders.add(oLine.getC_Order_ID()); log.fine("OrderLine - Reserved=" + oLine.getQtyReserved() + ", Delivered=" + oLine.getQtyDelivered()); if (isSOTrx()) QtySO = sLine.getMovementQty(); else QtyPO = sLine.getMovementQty(); } // Load RMA Line MRMALine rmaLine = null; if (sLine.getM_RMALine_ID() != 0) { rmaLine = new MRMALine(getCtx(), sLine.getM_RMALine_ID(), get_TrxName()); } log.info("Line=" + sLine.getLine() + " - Qty=" + sLine.getMovementQty()); // Check delivery policy MOrgInfo orgInfo = MOrgInfo.get(getCtx(), sLine.getAD_Org_ID(), get_TrxName()); boolean isStrictOrder = MClientInfo.DELIVERYPOLICY_StrictOrder.equalsIgnoreCase(orgInfo.getDeliveryPolicy()); // Stock Movement - Counterpart MOrder.reserveStock if (product != null && product.isStocked() ) { //Ignore the Material Policy when is Reverse Correction if(!isReversal()) { checkMaterialPolicy(sLine); } log.fine("Material Transaction"); MTransaction mtrx = null; //same warehouse in order and receipt? boolean sameWarehouse = true; // Reservation ASI - assume none int reservationAttributeSetInstance_ID = 0; // sLine.getM_AttributeSetInstance_ID(); if (oLine != null) { reservationAttributeSetInstance_ID = oLine.getM_AttributeSetInstance_ID(); sameWarehouse = oLine.getM_Warehouse_ID()==getM_Warehouse_ID(); } // if (sLine.getM_AttributeSetInstance_ID() == 0) { MInOutLineMA mas[] = MInOutLineMA.get(getCtx(), sLine.getM_InOutLine_ID(), get_TrxName()); for (int j = 0; j < mas.length; j++) { MInOutLineMA ma = mas[j]; BigDecimal QtyMA = ma.getMovementQty(); if (MovementType.charAt(1) == '-') // C- Customer Shipment - V- Vendor Return QtyMA = QtyMA.negate(); BigDecimal reservedDiff = Env.ZERO; BigDecimal orderedDiff = Env.ZERO; BigDecimal allocatedDiff = Env.ZERO; if (sLine.getC_OrderLine_ID() != 0) { if (isSOTrx()) { reservedDiff = ma.getMovementQty().negate(); allocatedDiff = ma.getMovementQty().negate(); } else orderedDiff = ma.getMovementQty().negate(); } // Update Storage - see also VMatch.createMatchRecord if (!MStorage.add(getCtx(), getM_Warehouse_ID(), sLine.getM_Locator_ID(), sLine.getM_Product_ID(), ma.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, QtyMA, sameWarehouse ? reservedDiff : Env.ZERO, sameWarehouse ? orderedDiff : Env.ZERO, sameWarehouse && isStrictOrder ? allocatedDiff : Env.ZERO, get_TrxName())) { m_processMsg = "Cannot correct Inventory (MA)"; return DocAction.STATUS_Invalid; } if (!sameWarehouse) { //correct qtyOrdered in warehouse of order MWarehouse wh = MWarehouse.get(getCtx(), oLine.getM_Warehouse_ID()); if (!MStorage.add(getCtx(), oLine.getM_Warehouse_ID(), wh.getDefaultLocator().getM_Locator_ID(), sLine.getM_Product_ID(), ma.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, Env.ZERO, reservedDiff, orderedDiff, allocatedDiff, get_TrxName())) { m_processMsg = "Cannot correct Inventory (MA) in order warehouse"; return DocAction.STATUS_Invalid; } } // Create Transaction mtrx = new MTransaction (getCtx(), sLine.getAD_Org_ID(), MovementType, sLine.getM_Locator_ID(), sLine.getM_Product_ID(), ma.getM_AttributeSetInstance_ID(), QtyMA, getMovementDate(), get_TrxName()); mtrx.setM_InOutLine_ID(sLine.getM_InOutLine_ID()); if (!mtrx.save()) { m_processMsg = "Could not create Material Transaction (MA)"; return DocAction.STATUS_Invalid; } } } // sLine.getM_AttributeSetInstance_ID() != 0 if (mtrx == null) { BigDecimal reservedDiff = sameWarehouse ? QtySO.negate() : Env.ZERO; BigDecimal orderedDiff = sameWarehouse ? QtyPO.negate(): Env.ZERO; BigDecimal allocatedDiff = isStrictOrder ? reservedDiff : Env.ZERO; // Fallback: Update Storage - see also VMatch.createMatchRecord if (!MStorage.add(getCtx(), getM_Warehouse_ID(), sLine.getM_Locator_ID(), sLine.getM_Product_ID(), sLine.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, Qty, reservedDiff, orderedDiff, allocatedDiff, get_TrxName())) { m_processMsg = "Cannot correct Inventory"; return DocAction.STATUS_Invalid; } if (!sameWarehouse) { //correct qtyOrdered in warehouse of order MWarehouse wh = MWarehouse.get(getCtx(), oLine.getM_Warehouse_ID()); if (!MStorage.add(getCtx(), oLine.getM_Warehouse_ID(), wh.getDefaultLocator().getM_Locator_ID(), sLine.getM_Product_ID(), sLine.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, Env.ZERO, QtySO.negate(), QtyPO.negate(), allocatedDiff, get_TrxName())) { m_processMsg = "Cannot correct Inventory"; return DocAction.STATUS_Invalid; } } // FallBack: Create Transaction mtrx = new MTransaction (getCtx(), sLine.getAD_Org_ID(), MovementType, sLine.getM_Locator_ID(), sLine.getM_Product_ID(), sLine.getM_AttributeSetInstance_ID(), Qty, getMovementDate(), get_TrxName()); mtrx.setM_InOutLine_ID(sLine.getM_InOutLine_ID()); if (!mtrx.save()) { m_processMsg = CLogger.retrieveErrorString("Could not create Material Transaction"); return DocAction.STATUS_Invalid; } } } // stock movement // Correct Order Line if (product != null && oLine != null) // other in VMatch.createMatchRecord oLine.setQtyReserved(oLine.getQtyReserved().subtract(sLine.getMovementQty())); // Update Sales Order Line if (oLine != null) { if (isSOTrx() // PO is done by Matching || sLine.getM_Product_ID() == 0) // PO Charges, empty lines { if (isSOTrx()) { oLine.setQtyDelivered(oLine.getQtyDelivered().subtract(Qty)); // Adjust allocated on order line when sales transaction if (isStrictOrder && product!=null && product.isStocked()) { oLine.setQtyAllocated(oLine.getQtyAllocated().add(Qty)); // Make sure qty allocated never goes below (zero) // which can happen when delivery rule is force if (oLine.getQtyAllocated().signum()==-1) oLine.setQtyAllocated(Env.ZERO); } } else { oLine.setQtyDelivered(oLine.getQtyDelivered().add(Qty)); // No allocation adjustment on non SO-Trx } oLine.setDateDelivered(getMovementDate()); // overwrite=last } if (!oLine.save()) { m_processMsg = "Could not update Order Line"; return DocAction.STATUS_Invalid; } else log.fine("OrderLine -> Reserved=" + oLine.getQtyReserved() + ", Delivered=" + oLine.getQtyReserved()); } // Update RMA Line Qty Delivered else if (rmaLine != null) { if (isSOTrx()) { rmaLine.setQtyDelivered(rmaLine.getQtyDelivered().add(Qty)); } else { rmaLine.setQtyDelivered(rmaLine.getQtyDelivered().subtract(Qty)); } if (!rmaLine.save()) { m_processMsg = "Could not update RMA Line"; return DocAction.STATUS_Invalid; } } // Create Asset for SO if (product != null && isSOTrx() && product.isCreateAsset() && sLine.getMovementQty().signum() > 0 && !isReversal()) { log.fine("Asset"); info.append("@A_Asset_ID@: "); int noAssets = sLine.getMovementQty().intValue(); if (!product.isOneAssetPerUOM()) noAssets = 1; for (int i = 0; i < noAssets; i++) { if (i > 0) info.append(" - "); int deliveryCount = i+1; if (!product.isOneAssetPerUOM()) deliveryCount = 0; MAsset asset = new MAsset (this, sLine, deliveryCount); if (!asset.save(get_TrxName())) { m_processMsg = "Could not create Asset"; return DocAction.STATUS_Invalid; } info.append(asset.getValue()); } } // Asset // Matching if (!isSOTrx() && sLine.getM_Product_ID() != 0 && !isReversal()) { BigDecimal matchQty = sLine.getMovementQty(); // Invoice - Receipt Match (requires Product) MInvoiceLine iLine = MInvoiceLine.getOfInOutLine (sLine); if (iLine != null && iLine.getM_Product_ID() != 0) { if (matchQty.compareTo(iLine.getQtyInvoiced())>0) matchQty = iLine.getQtyInvoiced(); MMatchInv[] matches = MMatchInv.get(getCtx(), sLine.getM_InOutLine_ID(), iLine.getC_InvoiceLine_ID(), get_TrxName()); if (matches == null || matches.length == 0) { MMatchInv inv = new MMatchInv (iLine, getMovementDate(), matchQty); if (sLine.getM_AttributeSetInstance_ID() != iLine.getM_AttributeSetInstance_ID()) { iLine.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); iLine.save(); // update matched invoice with ASI inv.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); } boolean isNewMatchInv = false; if (inv.get_ID() == 0) isNewMatchInv = true; if (!inv.save(get_TrxName())) { m_processMsg = CLogger.retrieveErrorString("Could not create Inv Matching"); return DocAction.STATUS_Invalid; } if (isNewMatchInv) addDocsPostProcess(inv); } } // Link to Order if (sLine.getC_OrderLine_ID() != 0) { log.fine("PO Matching"); // Ship - PO MMatchPO po = MMatchPO.create (null, sLine, getMovementDate(), matchQty); boolean isNewMatchPO = false; if (po.get_ID() == 0) isNewMatchPO = true; if (!po.save(get_TrxName())) { m_processMsg = "Could not create PO Matching"; return DocAction.STATUS_Invalid; } if (isNewMatchPO) addDocsPostProcess(po); // Update PO with ASI if ( oLine != null && oLine.getM_AttributeSetInstance_ID() == 0 && sLine.getMovementQty().compareTo(oLine.getQtyOrdered()) == 0) // just if full match [ 1876965 ] { oLine.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); oLine.save(get_TrxName()); } } else // No Order - Try finding links via Invoice { // Invoice has an Order Link if (iLine != null && iLine.getC_OrderLine_ID() != 0) { // Invoice is created before Shipment log.fine("PO(Inv) Matching"); // Ship - Invoice MMatchPO po = MMatchPO.create (iLine, sLine, getMovementDate(), matchQty); boolean isNewMatchPO = false; if (po.get_ID() == 0) isNewMatchPO = true; if (!po.save(get_TrxName())) { m_processMsg = "Could not create PO(Inv) Matching"; return DocAction.STATUS_Invalid; } if (isNewMatchPO) addDocsPostProcess(po); // Update PO with ASI oLine = new MOrderLine (getCtx(), po.getC_OrderLine_ID(), get_TrxName()); if ( oLine != null && oLine.getM_AttributeSetInstance_ID() == 0 && sLine.getMovementQty().compareTo(oLine.getQtyOrdered()) == 0) // just if full match [ 1876965 ] { oLine.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); oLine.save(get_TrxName()); } } } // No Order } // PO Matching } // for all lines // Counter Documents MInOut counter = createCounterDoc(); if (counter != null) info.append(" - @CounterDoc@: @M_InOut_ID@=").append(counter.getDocumentNo()); // Drop Shipments MInOut dropShipment = createDropShipment(); if (dropShipment != null) info.append(" - @DropShipment@: @M_InOut_ID@=").append(dropShipment.getDocumentNo()); // User Validation String valid = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE); if (valid != null) { m_processMsg = valid; return DocAction.STATUS_Invalid; } // Set the definite document number after completed (if needed) setDefiniteDocumentNo(); // Update IsDelivered on orders if (inOutOrders.size()>0) { MOrder order; for (Iterator<Integer> it = inOutOrders.iterator(); it.hasNext(); ) { order = new MOrder(getCtx(), it.next().intValue(), get_TrxName()); try { + // First set Delivered=false see Morder.updateIsDelivered + order.setIsDelivered(false); order.updateIsDelivered(); } catch (SQLException ee) { log.warning("Could not update isDelivered flag on order " + order.getDocumentNo() + " : " + ee.getMessage()); } order.saveEx(get_TrxName()); } } m_processMsg = info.toString(); setProcessed(true); setDocAction(DOCACTION_Close); return DocAction.STATUS_Completed; } // completeIt /* Save array of documents to process AFTER completing this one */ ArrayList<PO> docsPostProcess = new ArrayList<PO>(); private void addDocsPostProcess(PO doc) { docsPostProcess.add(doc); } public ArrayList<PO> getDocsPostProcess() { return docsPostProcess; } /** * Automatically creates a customer shipment for any * drop shipment material receipt * Based on createCounterDoc() by JJ * @return shipment if created else null */ private MInOut createDropShipment() { if ( isSOTrx() || !isDropShip() || getC_Order_ID() == 0 ) return null; // Document Type int C_DocTypeTarget_ID = 0; MDocType[] shipmentTypes = MDocType.getOfDocBaseType(getCtx(), MDocType.DOCBASETYPE_MaterialDelivery); for (int i = 0; i < shipmentTypes.length; i++ ) { if (shipmentTypes[i].isSOTrx() && ( C_DocTypeTarget_ID == 0 || shipmentTypes[i].isDefault() ) ) C_DocTypeTarget_ID = shipmentTypes[i].getC_DocType_ID(); } // Deep Copy MInOut dropShipment = copyFrom(this, getMovementDate(), getDateAcct(), C_DocTypeTarget_ID, !isSOTrx(), false, get_TrxName(), true); int linkedOrderID = new MOrder (getCtx(), getC_Order_ID(), get_TrxName()).getLink_Order_ID(); if (linkedOrderID != 0) { dropShipment.setC_Order_ID(linkedOrderID); // get invoice id from linked order int invID = new MOrder (getCtx(), linkedOrderID, get_TrxName()).getC_Invoice_ID(); if ( invID != 0 ) dropShipment.setC_Invoice_ID(invID); } else return null; dropShipment.setC_BPartner_ID(getDropShip_BPartner_ID()); dropShipment.setC_BPartner_Location_ID(getDropShip_Location_ID()); dropShipment.setAD_User_ID(getDropShip_User_ID()); dropShipment.setIsDropShip(false); dropShipment.setDropShip_BPartner_ID(0); dropShipment.setDropShip_Location_ID(0); dropShipment.setDropShip_User_ID(0); dropShipment.setMovementType(MOVEMENTTYPE_CustomerShipment); // References (Should not be required dropShipment.setSalesRep_ID(getSalesRep_ID()); dropShipment.save(get_TrxName()); // Update line order references to linked sales order lines MInOutLine[] lines = dropShipment.getLines(true); for (int i = 0; i < lines.length; i++) { MInOutLine dropLine = lines[i]; MOrderLine ol = new MOrderLine(getCtx(), dropLine.getC_OrderLine_ID(), null); if ( ol.getC_OrderLine_ID() != 0 ) { dropLine.setC_OrderLine_ID(ol.getLink_OrderLine_ID()); dropLine.save(); } } log.fine(dropShipment.toString()); dropShipment.setDocAction(DocAction.ACTION_Complete); dropShipment.processIt(DocAction.ACTION_Complete); dropShipment.save(); return dropShipment; } /** * Set the definite document number after completed */ private void setDefiniteDocumentNo() { MDocType dt = MDocType.get(getCtx(), getC_DocType_ID()); if (dt.isOverwriteDateOnComplete()) { setMovementDate(new Timestamp (System.currentTimeMillis())); } if (dt.isOverwriteSeqOnComplete()) { String value = DB.getDocumentNo(getC_DocType_ID(), get_TrxName(), true, this); if (value != null) setDocumentNo(value); } } /** * Check Material Policy * Sets line ASI */ private void checkMaterialPolicy(MInOutLine line) { int no = MInOutLineMA.deleteInOutLineMA(line.getM_InOutLine_ID(), get_TrxName()); if (no > 0) log.config("Delete old #" + no); // Incoming Trx String MovementType = getMovementType(); boolean inTrx = MovementType.charAt(1) == '+'; // V+ Vendor Receipt boolean needSave = false; MProduct product = line.getProduct(); // Need to have Location if (product != null && line.getM_Locator_ID() == 0) { //MWarehouse w = MWarehouse.get(getCtx(), getM_Warehouse_ID()); line.setM_Warehouse_ID(getM_Warehouse_ID()); line.setM_Locator_ID(inTrx ? Env.ZERO : line.getMovementQty()); // default Locator needSave = true; } // Attribute Set Instance // Create an Attribute Set Instance to any receipt FIFO/LIFO if (product != null && line.getM_AttributeSetInstance_ID() == 0) { //Validate Transaction if (getMovementType().compareTo(MInOut.MOVEMENTTYPE_CustomerReturns) == 0 || getMovementType().compareTo(MInOut.MOVEMENTTYPE_VendorReceipts) == 0 ) { MAttributeSetInstance asi = null; //auto balance negative on hand MStorage[] storages = MStorage.getWarehouse(getCtx(), getM_Warehouse_ID(), line.getM_Product_ID(), 0, null, MClient.MMPOLICY_FiFo.equals(product.getMMPolicy()), false, line.getM_Locator_ID(), get_TrxName()); for (MStorage storage : storages) { if (storage.getQtyOnHand().signum() < 0) { asi = new MAttributeSetInstance(getCtx(), storage.getM_AttributeSetInstance_ID(), get_TrxName()); break; } } //always create asi so fifo/lifo work. if (asi == null) { asi = MAttributeSetInstance.create(getCtx(), product, get_TrxName()); } line.setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID()); log.config("New ASI=" + line); needSave = true; } // Create consume the Attribute Set Instance using policy FIFO/LIFO else if(getMovementType().compareTo(MInOut.MOVEMENTTYPE_VendorReturns) == 0 || getMovementType().compareTo(MInOut.MOVEMENTTYPE_CustomerShipment) == 0) { String MMPolicy = product.getMMPolicy(); Timestamp minGuaranteeDate = getMovementDate(); MStorage[] storages = MStorage.getWarehouse(getCtx(), getM_Warehouse_ID(), line.getM_Product_ID(), line.getM_AttributeSetInstance_ID(), minGuaranteeDate, MClient.MMPOLICY_FiFo.equals(MMPolicy), true, line.getM_Locator_ID(), get_TrxName()); BigDecimal qtyToDeliver = line.getMovementQty(); for (MStorage storage: storages) { if (storage.getQtyOnHand().compareTo(qtyToDeliver) >= 0) { MInOutLineMA ma = new MInOutLineMA (line, storage.getM_AttributeSetInstance_ID(), qtyToDeliver); ma.saveEx(); qtyToDeliver = Env.ZERO; } else { MInOutLineMA ma = new MInOutLineMA (line, storage.getM_AttributeSetInstance_ID(), storage.getQtyOnHand()); ma.saveEx(); qtyToDeliver = qtyToDeliver.subtract(storage.getQtyOnHand()); log.fine( ma + ", QtyToDeliver=" + qtyToDeliver); } if (qtyToDeliver.signum() == 0) break; } if (qtyToDeliver.signum() != 0) { //deliver using new asi MAttributeSetInstance asi = MAttributeSetInstance.create(getCtx(), product, get_TrxName()); int M_AttributeSetInstance_ID = asi.getM_AttributeSetInstance_ID(); MInOutLineMA ma = new MInOutLineMA (line, M_AttributeSetInstance_ID, qtyToDeliver); ma.saveEx(); log.fine("##: " + ma); } } // outgoing Trx } // attributeSetInstance if (needSave) { line.saveEx(); } } // checkMaterialPolicy /************************************************************************** * Create Counter Document * @return InOut */ private MInOut createCounterDoc() { // Is this a counter doc ? if (getRef_InOut_ID() != 0) return null; // Org Must be linked to BPartner MOrg org = MOrg.get(getCtx(), getAD_Org_ID()); int counterC_BPartner_ID = org.getLinkedC_BPartner_ID(get_TrxName()); if (counterC_BPartner_ID == 0) return null; // Business Partner needs to be linked to Org MBPartner bp = new MBPartner (getCtx(), getC_BPartner_ID(), get_TrxName()); int counterAD_Org_ID = bp.getAD_OrgBP_ID_Int(); if (counterAD_Org_ID == 0) return null; MBPartner counterBP = new MBPartner (getCtx(), counterC_BPartner_ID, null); MOrgInfo counterOrgInfo = MOrgInfo.get(getCtx(), counterAD_Org_ID, get_TrxName()); log.info("Counter BP=" + counterBP.getName()); // Document Type int C_DocTypeTarget_ID = 0; MDocTypeCounter counterDT = MDocTypeCounter.getCounterDocType(getCtx(), getC_DocType_ID()); if (counterDT != null) { log.fine(counterDT.toString()); if (!counterDT.isCreateCounter() || !counterDT.isValid()) return null; C_DocTypeTarget_ID = counterDT.getCounter_C_DocType_ID(); } else // indirect { C_DocTypeTarget_ID = MDocTypeCounter.getCounterDocType_ID(getCtx(), getC_DocType_ID()); log.fine("Indirect C_DocTypeTarget_ID=" + C_DocTypeTarget_ID); if (C_DocTypeTarget_ID <= 0) return null; } // Deep Copy MInOut counter = copyFrom(this, getMovementDate(), getDateAcct(), C_DocTypeTarget_ID, !isSOTrx(), true, get_TrxName(), true); // counter.setAD_Org_ID(counterAD_Org_ID); counter.setM_Warehouse_ID(counterOrgInfo.getM_Warehouse_ID()); // counter.setBPartner(counterBP); if ( isDropShip() ) { counter.setIsDropShip(true ); counter.setDropShip_BPartner_ID(getDropShip_BPartner_ID()); counter.setDropShip_Location_ID(getDropShip_Location_ID()); counter.setDropShip_User_ID(getDropShip_User_ID()); } // Refernces (Should not be required counter.setSalesRep_ID(getSalesRep_ID()); counter.save(get_TrxName()); String MovementType = counter.getMovementType(); boolean inTrx = MovementType.charAt(1) == '+'; // V+ Vendor Receipt // Update copied lines MInOutLine[] counterLines = counter.getLines(true); for (int i = 0; i < counterLines.length; i++) { MInOutLine counterLine = counterLines[i]; counterLine.setClientOrg(counter); counterLine.setM_Warehouse_ID(counter.getM_Warehouse_ID()); counterLine.setM_Locator_ID(0); counterLine.setM_Locator_ID(inTrx ? Env.ZERO : counterLine.getMovementQty()); // counterLine.save(get_TrxName()); } log.fine(counter.toString()); // Document Action if (counterDT != null) { if (counterDT.getDocAction() != null) { counter.setDocAction(counterDT.getDocAction()); counter.processIt(counterDT.getDocAction()); counter.save(get_TrxName()); } } return counter; } // createCounterDoc /** * Void Document. * @return true if success */ public boolean voidIt() { log.info(toString()); // Before Void m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_VOID); if (m_processMsg != null) return false; if (DOCSTATUS_Closed.equals(getDocStatus()) || DOCSTATUS_Reversed.equals(getDocStatus()) || DOCSTATUS_Voided.equals(getDocStatus())) { m_processMsg = "Document Closed: " + getDocStatus(); return false; } // Not Processed if (DOCSTATUS_Drafted.equals(getDocStatus()) || DOCSTATUS_Invalid.equals(getDocStatus()) || DOCSTATUS_InProgress.equals(getDocStatus()) || DOCSTATUS_Approved.equals(getDocStatus()) || DOCSTATUS_NotApproved.equals(getDocStatus()) ) { // Set lines to 0 MInOutLine[] lines = getLines(false); for (int i = 0; i < lines.length; i++) { MInOutLine line = lines[i]; BigDecimal old = line.getMovementQty(); if (old.signum() != 0) { line.setQty(Env.ZERO); line.addDescription("Void (" + old + ")"); line.save(get_TrxName()); } } // // Void Confirmations setDocStatus(DOCSTATUS_Voided); // need to set & save docstatus to be able to check it in MInOutConfirm.voidIt() saveEx(); voidConfirmations(); } else { return reverseCorrectIt(); } // After Void m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_VOID); if (m_processMsg != null) return false; setProcessed(true); setDocAction(DOCACTION_None); return true; } // voidIt /** * Close Document. * @return true if success */ public boolean closeIt() { log.info(toString()); // Before Close m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_CLOSE); if (m_processMsg != null) return false; setProcessed(true); setDocAction(DOCACTION_None); // After Close m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_CLOSE); if (m_processMsg != null) return false; return true; } // closeIt /** * Reverse Correction - same date * @return true if success */ public boolean reverseCorrectIt() { log.info(toString()); // Before reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REVERSECORRECT); if (m_processMsg != null) return false; MDocType dt = MDocType.get(getCtx(), getC_DocType_ID()); if (!MPeriod.isOpen(getCtx(), getDateAcct(), dt.getDocBaseType(), getAD_Org_ID())) { m_processMsg = "@PeriodClosed@"; return false; } // Reverse/Delete Matching if (!isSOTrx()) { MMatchInv[] mInv = MMatchInv.getInOut(getCtx(), getM_InOut_ID(), get_TrxName()); for (int i = 0; i < mInv.length; i++) mInv[i].deleteEx(true); MMatchPO[] mPO = MMatchPO.getInOut(getCtx(), getM_InOut_ID(), get_TrxName()); for (int i = 0; i < mPO.length; i++) { if (mPO[i].getC_InvoiceLine_ID() == 0) mPO[i].deleteEx(true); else { mPO[i].setM_InOutLine_ID(0); mPO[i].saveEx(); } } } // Deep Copy MInOut reversal = copyFrom (this, getMovementDate(), getDateAcct(), getC_DocType_ID(), isSOTrx(), false, get_TrxName(), true); if (reversal == null) { m_processMsg = "Could not create Ship Reversal"; return false; } reversal.setReversal(true); // Reverse Line Qty MInOutLine[] sLines = getLines(false); MInOutLine[] rLines = reversal.getLines(false); for (int i = 0; i < rLines.length; i++) { MInOutLine rLine = rLines[i]; rLine.setQtyEntered(rLine.getQtyEntered().negate()); rLine.setMovementQty(rLine.getMovementQty().negate()); rLine.setM_AttributeSetInstance_ID(sLines[i].getM_AttributeSetInstance_ID()); // Goodwill: store original (voided/reversed) document line rLine.setReversalLine_ID(sLines[i].getM_InOutLine_ID()); if (!rLine.save(get_TrxName())) { m_processMsg = "Could not correct Ship Reversal Line"; return false; } // We need to copy MA if (rLine.getM_AttributeSetInstance_ID() == 0) { MInOutLineMA mas[] = MInOutLineMA.get(getCtx(), sLines[i].getM_InOutLine_ID(), get_TrxName()); for (int j = 0; j < mas.length; j++) { MInOutLineMA ma = new MInOutLineMA (rLine, mas[j].getM_AttributeSetInstance_ID(), mas[j].getMovementQty().negate()); ma.saveEx(); } } // De-Activate Asset MAsset asset = MAsset.getFromShipment(getCtx(), sLines[i].getM_InOutLine_ID(), get_TrxName()); if (asset != null) { asset.setIsActive(false); asset.addDescription("(" + reversal.getDocumentNo() + " #" + rLine.getLine() + "<-)"); asset.save(); } } reversal.setC_Order_ID(getC_Order_ID()); // Set M_RMA_ID reversal.setM_RMA_ID(getM_RMA_ID()); reversal.addDescription("{->" + getDocumentNo() + ")"); //FR1948157 reversal.setReversal_ID(getM_InOut_ID()); reversal.saveEx(get_TrxName()); // if (!reversal.processIt(DocAction.ACTION_Complete) || !reversal.getDocStatus().equals(DocAction.STATUS_Completed)) { m_processMsg = "Reversal ERROR: " + reversal.getProcessMsg(); return false; } reversal.closeIt(); reversal.setProcessing (false); reversal.setDocStatus(DOCSTATUS_Reversed); reversal.setDocAction(DOCACTION_None); reversal.saveEx(get_TrxName()); // addDescription("(" + reversal.getDocumentNo() + "<-)"); // // Void Confirmations setDocStatus(DOCSTATUS_Reversed); // need to set & save docstatus to be able to check it in MInOutConfirm.voidIt() saveEx(); voidConfirmations(); // After reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REVERSECORRECT); if (m_processMsg != null) return false; m_processMsg = reversal.getDocumentNo(); //FR1948157 this.setReversal_ID(reversal.getM_InOut_ID()); setProcessed(true); setDocStatus(DOCSTATUS_Reversed); // may come from void setDocAction(DOCACTION_None); return true; } // reverseCorrectionIt /** * Reverse Accrual - none * @return false */ public boolean reverseAccrualIt() { log.info(toString()); // Before reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REVERSEACCRUAL); if (m_processMsg != null) return false; // After reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REVERSEACCRUAL); if (m_processMsg != null) return false; return false; } // reverseAccrualIt /** * Re-activate * @return false */ public boolean reActivateIt() { log.info(toString()); // Before reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REACTIVATE); if (m_processMsg != null) return false; // After reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REACTIVATE); if (m_processMsg != null) return false; return false; } // reActivateIt /************************************************************************* * Get Summary * @return Summary of Document */ public String getSummary() { StringBuffer sb = new StringBuffer(); sb.append(getDocumentNo()); // : Total Lines = 123.00 (#1) sb.append(":") // .append(Msg.translate(getCtx(),"TotalLines")).append("=").append(getTotalLines()) .append(" (#").append(getLines(false).length).append(")"); // - Description if (getDescription() != null && getDescription().length() > 0) sb.append(" - ").append(getDescription()); return sb.toString(); } // getSummary /** * Get Process Message * @return clear text error message */ public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * @return AD_User_ID */ public int getDoc_User_ID() { return getSalesRep_ID(); } // getDoc_User_ID /** * Get Document Approval Amount * @return amount */ public BigDecimal getApprovalAmt() { return Env.ZERO; } // getApprovalAmt /** * Get C_Currency_ID * @return Accounting Currency */ public int getC_Currency_ID () { return Env.getContextAsInt(getCtx(),"$C_Currency_ID"); } // getC_Currency_ID /** * Document Status is Complete or Closed * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MInOut
true
true
public String completeIt() { // Re-Check if (!m_justPrepared) { String status = prepareIt(); if (!DocAction.STATUS_InProgress.equals(status)) return status; } m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE); if (m_processMsg != null) return DocAction.STATUS_Invalid; // Outstanding (not processed) Incoming Confirmations ? MInOutConfirm[] confirmations = getConfirmations(true); for (int i = 0; i < confirmations.length; i++) { MInOutConfirm confirm = confirmations[i]; if (!confirm.isProcessed()) { if (MInOutConfirm.CONFIRMTYPE_CustomerConfirmation.equals(confirm.getConfirmType())) continue; // m_processMsg = "Open @M_InOutConfirm_ID@: " + confirm.getConfirmTypeName() + " - " + confirm.getDocumentNo(); return DocAction.STATUS_InProgress; } } // Implicit Approval if (!isApproved()) approveIt(); log.info(toString()); StringBuffer info = new StringBuffer(); // Set of shipped orders // Use this set to determine what orders are shipped on // this inout record. Set<Integer> inOutOrders = new TreeSet<Integer>(); // For all lines MInOutLine[] lines = getLines(false); for (int lineIndex = 0; lineIndex < lines.length; lineIndex++) { MInOutLine sLine = lines[lineIndex]; MProduct product = sLine.getProduct(); // Qty & Type String MovementType = getMovementType(); BigDecimal Qty = sLine.getMovementQty(); if (MovementType.charAt(1) == '-') // C- Customer Shipment - V- Vendor Return Qty = Qty.negate(); BigDecimal QtySO = Env.ZERO; BigDecimal QtyPO = Env.ZERO; // Update Order Line MOrderLine oLine = null; if (sLine.getC_OrderLine_ID() != 0) { oLine = new MOrderLine (getCtx(), sLine.getC_OrderLine_ID(), get_TrxName()); // Add order id to set of orders inOutOrders.add(oLine.getC_Order_ID()); log.fine("OrderLine - Reserved=" + oLine.getQtyReserved() + ", Delivered=" + oLine.getQtyDelivered()); if (isSOTrx()) QtySO = sLine.getMovementQty(); else QtyPO = sLine.getMovementQty(); } // Load RMA Line MRMALine rmaLine = null; if (sLine.getM_RMALine_ID() != 0) { rmaLine = new MRMALine(getCtx(), sLine.getM_RMALine_ID(), get_TrxName()); } log.info("Line=" + sLine.getLine() + " - Qty=" + sLine.getMovementQty()); // Check delivery policy MOrgInfo orgInfo = MOrgInfo.get(getCtx(), sLine.getAD_Org_ID(), get_TrxName()); boolean isStrictOrder = MClientInfo.DELIVERYPOLICY_StrictOrder.equalsIgnoreCase(orgInfo.getDeliveryPolicy()); // Stock Movement - Counterpart MOrder.reserveStock if (product != null && product.isStocked() ) { //Ignore the Material Policy when is Reverse Correction if(!isReversal()) { checkMaterialPolicy(sLine); } log.fine("Material Transaction"); MTransaction mtrx = null; //same warehouse in order and receipt? boolean sameWarehouse = true; // Reservation ASI - assume none int reservationAttributeSetInstance_ID = 0; // sLine.getM_AttributeSetInstance_ID(); if (oLine != null) { reservationAttributeSetInstance_ID = oLine.getM_AttributeSetInstance_ID(); sameWarehouse = oLine.getM_Warehouse_ID()==getM_Warehouse_ID(); } // if (sLine.getM_AttributeSetInstance_ID() == 0) { MInOutLineMA mas[] = MInOutLineMA.get(getCtx(), sLine.getM_InOutLine_ID(), get_TrxName()); for (int j = 0; j < mas.length; j++) { MInOutLineMA ma = mas[j]; BigDecimal QtyMA = ma.getMovementQty(); if (MovementType.charAt(1) == '-') // C- Customer Shipment - V- Vendor Return QtyMA = QtyMA.negate(); BigDecimal reservedDiff = Env.ZERO; BigDecimal orderedDiff = Env.ZERO; BigDecimal allocatedDiff = Env.ZERO; if (sLine.getC_OrderLine_ID() != 0) { if (isSOTrx()) { reservedDiff = ma.getMovementQty().negate(); allocatedDiff = ma.getMovementQty().negate(); } else orderedDiff = ma.getMovementQty().negate(); } // Update Storage - see also VMatch.createMatchRecord if (!MStorage.add(getCtx(), getM_Warehouse_ID(), sLine.getM_Locator_ID(), sLine.getM_Product_ID(), ma.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, QtyMA, sameWarehouse ? reservedDiff : Env.ZERO, sameWarehouse ? orderedDiff : Env.ZERO, sameWarehouse && isStrictOrder ? allocatedDiff : Env.ZERO, get_TrxName())) { m_processMsg = "Cannot correct Inventory (MA)"; return DocAction.STATUS_Invalid; } if (!sameWarehouse) { //correct qtyOrdered in warehouse of order MWarehouse wh = MWarehouse.get(getCtx(), oLine.getM_Warehouse_ID()); if (!MStorage.add(getCtx(), oLine.getM_Warehouse_ID(), wh.getDefaultLocator().getM_Locator_ID(), sLine.getM_Product_ID(), ma.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, Env.ZERO, reservedDiff, orderedDiff, allocatedDiff, get_TrxName())) { m_processMsg = "Cannot correct Inventory (MA) in order warehouse"; return DocAction.STATUS_Invalid; } } // Create Transaction mtrx = new MTransaction (getCtx(), sLine.getAD_Org_ID(), MovementType, sLine.getM_Locator_ID(), sLine.getM_Product_ID(), ma.getM_AttributeSetInstance_ID(), QtyMA, getMovementDate(), get_TrxName()); mtrx.setM_InOutLine_ID(sLine.getM_InOutLine_ID()); if (!mtrx.save()) { m_processMsg = "Could not create Material Transaction (MA)"; return DocAction.STATUS_Invalid; } } } // sLine.getM_AttributeSetInstance_ID() != 0 if (mtrx == null) { BigDecimal reservedDiff = sameWarehouse ? QtySO.negate() : Env.ZERO; BigDecimal orderedDiff = sameWarehouse ? QtyPO.negate(): Env.ZERO; BigDecimal allocatedDiff = isStrictOrder ? reservedDiff : Env.ZERO; // Fallback: Update Storage - see also VMatch.createMatchRecord if (!MStorage.add(getCtx(), getM_Warehouse_ID(), sLine.getM_Locator_ID(), sLine.getM_Product_ID(), sLine.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, Qty, reservedDiff, orderedDiff, allocatedDiff, get_TrxName())) { m_processMsg = "Cannot correct Inventory"; return DocAction.STATUS_Invalid; } if (!sameWarehouse) { //correct qtyOrdered in warehouse of order MWarehouse wh = MWarehouse.get(getCtx(), oLine.getM_Warehouse_ID()); if (!MStorage.add(getCtx(), oLine.getM_Warehouse_ID(), wh.getDefaultLocator().getM_Locator_ID(), sLine.getM_Product_ID(), sLine.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, Env.ZERO, QtySO.negate(), QtyPO.negate(), allocatedDiff, get_TrxName())) { m_processMsg = "Cannot correct Inventory"; return DocAction.STATUS_Invalid; } } // FallBack: Create Transaction mtrx = new MTransaction (getCtx(), sLine.getAD_Org_ID(), MovementType, sLine.getM_Locator_ID(), sLine.getM_Product_ID(), sLine.getM_AttributeSetInstance_ID(), Qty, getMovementDate(), get_TrxName()); mtrx.setM_InOutLine_ID(sLine.getM_InOutLine_ID()); if (!mtrx.save()) { m_processMsg = CLogger.retrieveErrorString("Could not create Material Transaction"); return DocAction.STATUS_Invalid; } } } // stock movement // Correct Order Line if (product != null && oLine != null) // other in VMatch.createMatchRecord oLine.setQtyReserved(oLine.getQtyReserved().subtract(sLine.getMovementQty())); // Update Sales Order Line if (oLine != null) { if (isSOTrx() // PO is done by Matching || sLine.getM_Product_ID() == 0) // PO Charges, empty lines { if (isSOTrx()) { oLine.setQtyDelivered(oLine.getQtyDelivered().subtract(Qty)); // Adjust allocated on order line when sales transaction if (isStrictOrder && product!=null && product.isStocked()) { oLine.setQtyAllocated(oLine.getQtyAllocated().add(Qty)); // Make sure qty allocated never goes below (zero) // which can happen when delivery rule is force if (oLine.getQtyAllocated().signum()==-1) oLine.setQtyAllocated(Env.ZERO); } } else { oLine.setQtyDelivered(oLine.getQtyDelivered().add(Qty)); // No allocation adjustment on non SO-Trx } oLine.setDateDelivered(getMovementDate()); // overwrite=last } if (!oLine.save()) { m_processMsg = "Could not update Order Line"; return DocAction.STATUS_Invalid; } else log.fine("OrderLine -> Reserved=" + oLine.getQtyReserved() + ", Delivered=" + oLine.getQtyReserved()); } // Update RMA Line Qty Delivered else if (rmaLine != null) { if (isSOTrx()) { rmaLine.setQtyDelivered(rmaLine.getQtyDelivered().add(Qty)); } else { rmaLine.setQtyDelivered(rmaLine.getQtyDelivered().subtract(Qty)); } if (!rmaLine.save()) { m_processMsg = "Could not update RMA Line"; return DocAction.STATUS_Invalid; } } // Create Asset for SO if (product != null && isSOTrx() && product.isCreateAsset() && sLine.getMovementQty().signum() > 0 && !isReversal()) { log.fine("Asset"); info.append("@A_Asset_ID@: "); int noAssets = sLine.getMovementQty().intValue(); if (!product.isOneAssetPerUOM()) noAssets = 1; for (int i = 0; i < noAssets; i++) { if (i > 0) info.append(" - "); int deliveryCount = i+1; if (!product.isOneAssetPerUOM()) deliveryCount = 0; MAsset asset = new MAsset (this, sLine, deliveryCount); if (!asset.save(get_TrxName())) { m_processMsg = "Could not create Asset"; return DocAction.STATUS_Invalid; } info.append(asset.getValue()); } } // Asset // Matching if (!isSOTrx() && sLine.getM_Product_ID() != 0 && !isReversal()) { BigDecimal matchQty = sLine.getMovementQty(); // Invoice - Receipt Match (requires Product) MInvoiceLine iLine = MInvoiceLine.getOfInOutLine (sLine); if (iLine != null && iLine.getM_Product_ID() != 0) { if (matchQty.compareTo(iLine.getQtyInvoiced())>0) matchQty = iLine.getQtyInvoiced(); MMatchInv[] matches = MMatchInv.get(getCtx(), sLine.getM_InOutLine_ID(), iLine.getC_InvoiceLine_ID(), get_TrxName()); if (matches == null || matches.length == 0) { MMatchInv inv = new MMatchInv (iLine, getMovementDate(), matchQty); if (sLine.getM_AttributeSetInstance_ID() != iLine.getM_AttributeSetInstance_ID()) { iLine.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); iLine.save(); // update matched invoice with ASI inv.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); } boolean isNewMatchInv = false; if (inv.get_ID() == 0) isNewMatchInv = true; if (!inv.save(get_TrxName())) { m_processMsg = CLogger.retrieveErrorString("Could not create Inv Matching"); return DocAction.STATUS_Invalid; } if (isNewMatchInv) addDocsPostProcess(inv); } } // Link to Order if (sLine.getC_OrderLine_ID() != 0) { log.fine("PO Matching"); // Ship - PO MMatchPO po = MMatchPO.create (null, sLine, getMovementDate(), matchQty); boolean isNewMatchPO = false; if (po.get_ID() == 0) isNewMatchPO = true; if (!po.save(get_TrxName())) { m_processMsg = "Could not create PO Matching"; return DocAction.STATUS_Invalid; } if (isNewMatchPO) addDocsPostProcess(po); // Update PO with ASI if ( oLine != null && oLine.getM_AttributeSetInstance_ID() == 0 && sLine.getMovementQty().compareTo(oLine.getQtyOrdered()) == 0) // just if full match [ 1876965 ] { oLine.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); oLine.save(get_TrxName()); } } else // No Order - Try finding links via Invoice { // Invoice has an Order Link if (iLine != null && iLine.getC_OrderLine_ID() != 0) { // Invoice is created before Shipment log.fine("PO(Inv) Matching"); // Ship - Invoice MMatchPO po = MMatchPO.create (iLine, sLine, getMovementDate(), matchQty); boolean isNewMatchPO = false; if (po.get_ID() == 0) isNewMatchPO = true; if (!po.save(get_TrxName())) { m_processMsg = "Could not create PO(Inv) Matching"; return DocAction.STATUS_Invalid; } if (isNewMatchPO) addDocsPostProcess(po); // Update PO with ASI oLine = new MOrderLine (getCtx(), po.getC_OrderLine_ID(), get_TrxName()); if ( oLine != null && oLine.getM_AttributeSetInstance_ID() == 0 && sLine.getMovementQty().compareTo(oLine.getQtyOrdered()) == 0) // just if full match [ 1876965 ] { oLine.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); oLine.save(get_TrxName()); } } } // No Order } // PO Matching } // for all lines // Counter Documents MInOut counter = createCounterDoc(); if (counter != null) info.append(" - @CounterDoc@: @M_InOut_ID@=").append(counter.getDocumentNo()); // Drop Shipments MInOut dropShipment = createDropShipment(); if (dropShipment != null) info.append(" - @DropShipment@: @M_InOut_ID@=").append(dropShipment.getDocumentNo()); // User Validation String valid = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE); if (valid != null) { m_processMsg = valid; return DocAction.STATUS_Invalid; } // Set the definite document number after completed (if needed) setDefiniteDocumentNo(); // Update IsDelivered on orders if (inOutOrders.size()>0) { MOrder order; for (Iterator<Integer> it = inOutOrders.iterator(); it.hasNext(); ) { order = new MOrder(getCtx(), it.next().intValue(), get_TrxName()); try { order.updateIsDelivered(); } catch (SQLException ee) { log.warning("Could not update isDelivered flag on order " + order.getDocumentNo() + " : " + ee.getMessage()); } order.saveEx(get_TrxName()); } } m_processMsg = info.toString(); setProcessed(true); setDocAction(DOCACTION_Close); return DocAction.STATUS_Completed; } // completeIt
public String completeIt() { // Re-Check if (!m_justPrepared) { String status = prepareIt(); if (!DocAction.STATUS_InProgress.equals(status)) return status; } m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE); if (m_processMsg != null) return DocAction.STATUS_Invalid; // Outstanding (not processed) Incoming Confirmations ? MInOutConfirm[] confirmations = getConfirmations(true); for (int i = 0; i < confirmations.length; i++) { MInOutConfirm confirm = confirmations[i]; if (!confirm.isProcessed()) { if (MInOutConfirm.CONFIRMTYPE_CustomerConfirmation.equals(confirm.getConfirmType())) continue; // m_processMsg = "Open @M_InOutConfirm_ID@: " + confirm.getConfirmTypeName() + " - " + confirm.getDocumentNo(); return DocAction.STATUS_InProgress; } } // Implicit Approval if (!isApproved()) approveIt(); log.info(toString()); StringBuffer info = new StringBuffer(); // Set of shipped orders // Use this set to determine what orders are shipped on // this inout record. Set<Integer> inOutOrders = new TreeSet<Integer>(); // For all lines MInOutLine[] lines = getLines(false); for (int lineIndex = 0; lineIndex < lines.length; lineIndex++) { MInOutLine sLine = lines[lineIndex]; MProduct product = sLine.getProduct(); // Qty & Type String MovementType = getMovementType(); BigDecimal Qty = sLine.getMovementQty(); if (MovementType.charAt(1) == '-') // C- Customer Shipment - V- Vendor Return Qty = Qty.negate(); BigDecimal QtySO = Env.ZERO; BigDecimal QtyPO = Env.ZERO; // Update Order Line MOrderLine oLine = null; if (sLine.getC_OrderLine_ID() != 0) { oLine = new MOrderLine (getCtx(), sLine.getC_OrderLine_ID(), get_TrxName()); // Add order id to set of orders inOutOrders.add(oLine.getC_Order_ID()); log.fine("OrderLine - Reserved=" + oLine.getQtyReserved() + ", Delivered=" + oLine.getQtyDelivered()); if (isSOTrx()) QtySO = sLine.getMovementQty(); else QtyPO = sLine.getMovementQty(); } // Load RMA Line MRMALine rmaLine = null; if (sLine.getM_RMALine_ID() != 0) { rmaLine = new MRMALine(getCtx(), sLine.getM_RMALine_ID(), get_TrxName()); } log.info("Line=" + sLine.getLine() + " - Qty=" + sLine.getMovementQty()); // Check delivery policy MOrgInfo orgInfo = MOrgInfo.get(getCtx(), sLine.getAD_Org_ID(), get_TrxName()); boolean isStrictOrder = MClientInfo.DELIVERYPOLICY_StrictOrder.equalsIgnoreCase(orgInfo.getDeliveryPolicy()); // Stock Movement - Counterpart MOrder.reserveStock if (product != null && product.isStocked() ) { //Ignore the Material Policy when is Reverse Correction if(!isReversal()) { checkMaterialPolicy(sLine); } log.fine("Material Transaction"); MTransaction mtrx = null; //same warehouse in order and receipt? boolean sameWarehouse = true; // Reservation ASI - assume none int reservationAttributeSetInstance_ID = 0; // sLine.getM_AttributeSetInstance_ID(); if (oLine != null) { reservationAttributeSetInstance_ID = oLine.getM_AttributeSetInstance_ID(); sameWarehouse = oLine.getM_Warehouse_ID()==getM_Warehouse_ID(); } // if (sLine.getM_AttributeSetInstance_ID() == 0) { MInOutLineMA mas[] = MInOutLineMA.get(getCtx(), sLine.getM_InOutLine_ID(), get_TrxName()); for (int j = 0; j < mas.length; j++) { MInOutLineMA ma = mas[j]; BigDecimal QtyMA = ma.getMovementQty(); if (MovementType.charAt(1) == '-') // C- Customer Shipment - V- Vendor Return QtyMA = QtyMA.negate(); BigDecimal reservedDiff = Env.ZERO; BigDecimal orderedDiff = Env.ZERO; BigDecimal allocatedDiff = Env.ZERO; if (sLine.getC_OrderLine_ID() != 0) { if (isSOTrx()) { reservedDiff = ma.getMovementQty().negate(); allocatedDiff = ma.getMovementQty().negate(); } else orderedDiff = ma.getMovementQty().negate(); } // Update Storage - see also VMatch.createMatchRecord if (!MStorage.add(getCtx(), getM_Warehouse_ID(), sLine.getM_Locator_ID(), sLine.getM_Product_ID(), ma.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, QtyMA, sameWarehouse ? reservedDiff : Env.ZERO, sameWarehouse ? orderedDiff : Env.ZERO, sameWarehouse && isStrictOrder ? allocatedDiff : Env.ZERO, get_TrxName())) { m_processMsg = "Cannot correct Inventory (MA)"; return DocAction.STATUS_Invalid; } if (!sameWarehouse) { //correct qtyOrdered in warehouse of order MWarehouse wh = MWarehouse.get(getCtx(), oLine.getM_Warehouse_ID()); if (!MStorage.add(getCtx(), oLine.getM_Warehouse_ID(), wh.getDefaultLocator().getM_Locator_ID(), sLine.getM_Product_ID(), ma.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, Env.ZERO, reservedDiff, orderedDiff, allocatedDiff, get_TrxName())) { m_processMsg = "Cannot correct Inventory (MA) in order warehouse"; return DocAction.STATUS_Invalid; } } // Create Transaction mtrx = new MTransaction (getCtx(), sLine.getAD_Org_ID(), MovementType, sLine.getM_Locator_ID(), sLine.getM_Product_ID(), ma.getM_AttributeSetInstance_ID(), QtyMA, getMovementDate(), get_TrxName()); mtrx.setM_InOutLine_ID(sLine.getM_InOutLine_ID()); if (!mtrx.save()) { m_processMsg = "Could not create Material Transaction (MA)"; return DocAction.STATUS_Invalid; } } } // sLine.getM_AttributeSetInstance_ID() != 0 if (mtrx == null) { BigDecimal reservedDiff = sameWarehouse ? QtySO.negate() : Env.ZERO; BigDecimal orderedDiff = sameWarehouse ? QtyPO.negate(): Env.ZERO; BigDecimal allocatedDiff = isStrictOrder ? reservedDiff : Env.ZERO; // Fallback: Update Storage - see also VMatch.createMatchRecord if (!MStorage.add(getCtx(), getM_Warehouse_ID(), sLine.getM_Locator_ID(), sLine.getM_Product_ID(), sLine.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, Qty, reservedDiff, orderedDiff, allocatedDiff, get_TrxName())) { m_processMsg = "Cannot correct Inventory"; return DocAction.STATUS_Invalid; } if (!sameWarehouse) { //correct qtyOrdered in warehouse of order MWarehouse wh = MWarehouse.get(getCtx(), oLine.getM_Warehouse_ID()); if (!MStorage.add(getCtx(), oLine.getM_Warehouse_ID(), wh.getDefaultLocator().getM_Locator_ID(), sLine.getM_Product_ID(), sLine.getM_AttributeSetInstance_ID(), reservationAttributeSetInstance_ID, Env.ZERO, QtySO.negate(), QtyPO.negate(), allocatedDiff, get_TrxName())) { m_processMsg = "Cannot correct Inventory"; return DocAction.STATUS_Invalid; } } // FallBack: Create Transaction mtrx = new MTransaction (getCtx(), sLine.getAD_Org_ID(), MovementType, sLine.getM_Locator_ID(), sLine.getM_Product_ID(), sLine.getM_AttributeSetInstance_ID(), Qty, getMovementDate(), get_TrxName()); mtrx.setM_InOutLine_ID(sLine.getM_InOutLine_ID()); if (!mtrx.save()) { m_processMsg = CLogger.retrieveErrorString("Could not create Material Transaction"); return DocAction.STATUS_Invalid; } } } // stock movement // Correct Order Line if (product != null && oLine != null) // other in VMatch.createMatchRecord oLine.setQtyReserved(oLine.getQtyReserved().subtract(sLine.getMovementQty())); // Update Sales Order Line if (oLine != null) { if (isSOTrx() // PO is done by Matching || sLine.getM_Product_ID() == 0) // PO Charges, empty lines { if (isSOTrx()) { oLine.setQtyDelivered(oLine.getQtyDelivered().subtract(Qty)); // Adjust allocated on order line when sales transaction if (isStrictOrder && product!=null && product.isStocked()) { oLine.setQtyAllocated(oLine.getQtyAllocated().add(Qty)); // Make sure qty allocated never goes below (zero) // which can happen when delivery rule is force if (oLine.getQtyAllocated().signum()==-1) oLine.setQtyAllocated(Env.ZERO); } } else { oLine.setQtyDelivered(oLine.getQtyDelivered().add(Qty)); // No allocation adjustment on non SO-Trx } oLine.setDateDelivered(getMovementDate()); // overwrite=last } if (!oLine.save()) { m_processMsg = "Could not update Order Line"; return DocAction.STATUS_Invalid; } else log.fine("OrderLine -> Reserved=" + oLine.getQtyReserved() + ", Delivered=" + oLine.getQtyReserved()); } // Update RMA Line Qty Delivered else if (rmaLine != null) { if (isSOTrx()) { rmaLine.setQtyDelivered(rmaLine.getQtyDelivered().add(Qty)); } else { rmaLine.setQtyDelivered(rmaLine.getQtyDelivered().subtract(Qty)); } if (!rmaLine.save()) { m_processMsg = "Could not update RMA Line"; return DocAction.STATUS_Invalid; } } // Create Asset for SO if (product != null && isSOTrx() && product.isCreateAsset() && sLine.getMovementQty().signum() > 0 && !isReversal()) { log.fine("Asset"); info.append("@A_Asset_ID@: "); int noAssets = sLine.getMovementQty().intValue(); if (!product.isOneAssetPerUOM()) noAssets = 1; for (int i = 0; i < noAssets; i++) { if (i > 0) info.append(" - "); int deliveryCount = i+1; if (!product.isOneAssetPerUOM()) deliveryCount = 0; MAsset asset = new MAsset (this, sLine, deliveryCount); if (!asset.save(get_TrxName())) { m_processMsg = "Could not create Asset"; return DocAction.STATUS_Invalid; } info.append(asset.getValue()); } } // Asset // Matching if (!isSOTrx() && sLine.getM_Product_ID() != 0 && !isReversal()) { BigDecimal matchQty = sLine.getMovementQty(); // Invoice - Receipt Match (requires Product) MInvoiceLine iLine = MInvoiceLine.getOfInOutLine (sLine); if (iLine != null && iLine.getM_Product_ID() != 0) { if (matchQty.compareTo(iLine.getQtyInvoiced())>0) matchQty = iLine.getQtyInvoiced(); MMatchInv[] matches = MMatchInv.get(getCtx(), sLine.getM_InOutLine_ID(), iLine.getC_InvoiceLine_ID(), get_TrxName()); if (matches == null || matches.length == 0) { MMatchInv inv = new MMatchInv (iLine, getMovementDate(), matchQty); if (sLine.getM_AttributeSetInstance_ID() != iLine.getM_AttributeSetInstance_ID()) { iLine.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); iLine.save(); // update matched invoice with ASI inv.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); } boolean isNewMatchInv = false; if (inv.get_ID() == 0) isNewMatchInv = true; if (!inv.save(get_TrxName())) { m_processMsg = CLogger.retrieveErrorString("Could not create Inv Matching"); return DocAction.STATUS_Invalid; } if (isNewMatchInv) addDocsPostProcess(inv); } } // Link to Order if (sLine.getC_OrderLine_ID() != 0) { log.fine("PO Matching"); // Ship - PO MMatchPO po = MMatchPO.create (null, sLine, getMovementDate(), matchQty); boolean isNewMatchPO = false; if (po.get_ID() == 0) isNewMatchPO = true; if (!po.save(get_TrxName())) { m_processMsg = "Could not create PO Matching"; return DocAction.STATUS_Invalid; } if (isNewMatchPO) addDocsPostProcess(po); // Update PO with ASI if ( oLine != null && oLine.getM_AttributeSetInstance_ID() == 0 && sLine.getMovementQty().compareTo(oLine.getQtyOrdered()) == 0) // just if full match [ 1876965 ] { oLine.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); oLine.save(get_TrxName()); } } else // No Order - Try finding links via Invoice { // Invoice has an Order Link if (iLine != null && iLine.getC_OrderLine_ID() != 0) { // Invoice is created before Shipment log.fine("PO(Inv) Matching"); // Ship - Invoice MMatchPO po = MMatchPO.create (iLine, sLine, getMovementDate(), matchQty); boolean isNewMatchPO = false; if (po.get_ID() == 0) isNewMatchPO = true; if (!po.save(get_TrxName())) { m_processMsg = "Could not create PO(Inv) Matching"; return DocAction.STATUS_Invalid; } if (isNewMatchPO) addDocsPostProcess(po); // Update PO with ASI oLine = new MOrderLine (getCtx(), po.getC_OrderLine_ID(), get_TrxName()); if ( oLine != null && oLine.getM_AttributeSetInstance_ID() == 0 && sLine.getMovementQty().compareTo(oLine.getQtyOrdered()) == 0) // just if full match [ 1876965 ] { oLine.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID()); oLine.save(get_TrxName()); } } } // No Order } // PO Matching } // for all lines // Counter Documents MInOut counter = createCounterDoc(); if (counter != null) info.append(" - @CounterDoc@: @M_InOut_ID@=").append(counter.getDocumentNo()); // Drop Shipments MInOut dropShipment = createDropShipment(); if (dropShipment != null) info.append(" - @DropShipment@: @M_InOut_ID@=").append(dropShipment.getDocumentNo()); // User Validation String valid = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE); if (valid != null) { m_processMsg = valid; return DocAction.STATUS_Invalid; } // Set the definite document number after completed (if needed) setDefiniteDocumentNo(); // Update IsDelivered on orders if (inOutOrders.size()>0) { MOrder order; for (Iterator<Integer> it = inOutOrders.iterator(); it.hasNext(); ) { order = new MOrder(getCtx(), it.next().intValue(), get_TrxName()); try { // First set Delivered=false see Morder.updateIsDelivered order.setIsDelivered(false); order.updateIsDelivered(); } catch (SQLException ee) { log.warning("Could not update isDelivered flag on order " + order.getDocumentNo() + " : " + ee.getMessage()); } order.saveEx(get_TrxName()); } } m_processMsg = info.toString(); setProcessed(true); setDocAction(DOCACTION_Close); return DocAction.STATUS_Completed; } // completeIt
diff --git a/Model/src/java/fr/cg95/cvq/util/admin/AddressBeanCreator.java b/Model/src/java/fr/cg95/cvq/util/admin/AddressBeanCreator.java index dd3a8b714..9773fccbe 100644 --- a/Model/src/java/fr/cg95/cvq/util/admin/AddressBeanCreator.java +++ b/Model/src/java/fr/cg95/cvq/util/admin/AddressBeanCreator.java @@ -1,138 +1,142 @@ package fr.cg95.cvq.util.admin; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hibernate.transform.Transformers; import org.springframework.context.support.ClassPathXmlApplicationContext; import fr.cg95.cvq.business.users.Address; import fr.cg95.cvq.dao.hibernate.GenericDAO; import fr.cg95.cvq.dao.hibernate.HibernateUtil; import fr.cg95.cvq.security.SecurityContext; import fr.cg95.cvq.service.authority.impl.LocalAuthorityRegistry; /** * @author [email protected] * */ public class AddressBeanCreator { private LocalAuthorityRegistry localAuthorityRegistry; private CustomDAO customDAO; private String forbiddenCharacters = "[\\s,;]"; private Pattern streetNumberPattern = Pattern.compile("(\\d{1,5})(.*)"); private Pattern otherFieldsPattern = Pattern.compile("(.*?)?((\\d{5})(.*?))?"); public static void main(String[] args) { ClassPathXmlApplicationContext cpxa = SpringApplicationContextLoader.loadContext(null); AddressBeanCreator addressBeanCreator = new AddressBeanCreator(); addressBeanCreator.localAuthorityRegistry = (LocalAuthorityRegistry)cpxa.getBean("localAuthorityRegistry"); addressBeanCreator.customDAO = new CustomDAO(); addressBeanCreator.localAuthorityRegistry.browseAndCallback(addressBeanCreator, "createAddressBeans", new Object[]{args[0], args[1]}); } public void createAddressBeans(String table, String field) { String localAuthorityName = SecurityContext.getCurrentSite().getName(); System.out.println(table + "'s addresses migration for : " + localAuthorityName); System.out.println(); List<BeanDTO> errors = new ArrayList<BeanDTO>(); for (BeanDTO o : customDAO.list(table, field)) { System.out.println("\tdealing with address " + o.address); if (o.address != null) { Address address = parseAddress(o.address); if (address != null) { System.out.println("\tgenerated address bean : " + address); customDAO.saveOrUpdate(address); o.address = address.getId().toString(); } else { errors.add(o); o.address = null; } customDAO.updateAddress(table, field, o); } System.out.println(); } try { File file = File.createTempFile(localAuthorityName + "_" + table + "_ambiguous_addresses_", ".txt"); FileOutputStream fos = new FileOutputStream(file); for (BeanDTO o : errors) { fos.write((o.id + " : " + o.address + "\n").getBytes()); } } catch(IOException ioe){ ioe.printStackTrace(); } } private Address parseAddress(String source) { System.out.println("\t\tParsing string : " + source); source = source.replaceAll(forbiddenCharacters, " ").trim(); System.out.println("\t\tSanitized string : " + source); String tempStreetNumber = null; Matcher streetNumberMatcher = streetNumberPattern.matcher(source); if (streetNumberMatcher.matches()) { tempStreetNumber = streetNumberMatcher.group(1); System.out.println("\t\tExtracting street number : " + tempStreetNumber); source = streetNumberMatcher.group(2).trim(); System.out.println("\t\tRemainging source : " + source); } Matcher otherFieldsMatcher = otherFieldsPattern.matcher(source); if (otherFieldsMatcher.matches()) { System.out.println("\t\tSource matches our pattern"); Address address = new Address(); address.setStreetNumber(tempStreetNumber); if (otherFieldsMatcher.group(1) != null) { address.setStreetName(otherFieldsMatcher.group(1).trim()); + if (address.getStreetName().length() > 114) + return null; } if (otherFieldsMatcher.group(3) != null) { address.setPostalCode(otherFieldsMatcher.group(3).trim()); } if (otherFieldsMatcher.group(4) != null) { address.setCity(otherFieldsMatcher.group(4).trim()); + if (address.getCity().length() > 32) + return null; } return address; } if ((tempStreetNumber + " " + source).trim().length() < 115) { System.out.println("\t\tSource doesn't match our pattern but is small enough, we put it in street name"); Address address = new Address(); address.setStreetName((tempStreetNumber + " " + source).trim()); return address; } System.out.println("\t\tCouldn't handle address !"); return null; } private static class CustomDAO extends GenericDAO { @SuppressWarnings("unchecked") public List<BeanDTO> list(String table, String field) { return (List<BeanDTO>)HibernateUtil.getSession() .createSQLQuery("select id, " + field + " as address from " + table) .addScalar("id") .addScalar("address") .setResultTransformer(Transformers.aliasToBean(BeanDTO.class)) .list(); } public void updateAddress(String table, String field, BeanDTO o) { HibernateUtil.getSession() .createSQLQuery("update " + table + " set " + field + " = :address where id = :id") .setString("address", o.address) .setLong("id", o.id) .executeUpdate(); } } public static class BeanDTO { private Long id; public String address; public void setId(BigInteger id) { this.id = id.longValue(); } } }
false
true
private Address parseAddress(String source) { System.out.println("\t\tParsing string : " + source); source = source.replaceAll(forbiddenCharacters, " ").trim(); System.out.println("\t\tSanitized string : " + source); String tempStreetNumber = null; Matcher streetNumberMatcher = streetNumberPattern.matcher(source); if (streetNumberMatcher.matches()) { tempStreetNumber = streetNumberMatcher.group(1); System.out.println("\t\tExtracting street number : " + tempStreetNumber); source = streetNumberMatcher.group(2).trim(); System.out.println("\t\tRemainging source : " + source); } Matcher otherFieldsMatcher = otherFieldsPattern.matcher(source); if (otherFieldsMatcher.matches()) { System.out.println("\t\tSource matches our pattern"); Address address = new Address(); address.setStreetNumber(tempStreetNumber); if (otherFieldsMatcher.group(1) != null) { address.setStreetName(otherFieldsMatcher.group(1).trim()); } if (otherFieldsMatcher.group(3) != null) { address.setPostalCode(otherFieldsMatcher.group(3).trim()); } if (otherFieldsMatcher.group(4) != null) { address.setCity(otherFieldsMatcher.group(4).trim()); } return address; } if ((tempStreetNumber + " " + source).trim().length() < 115) { System.out.println("\t\tSource doesn't match our pattern but is small enough, we put it in street name"); Address address = new Address(); address.setStreetName((tempStreetNumber + " " + source).trim()); return address; } System.out.println("\t\tCouldn't handle address !"); return null; }
private Address parseAddress(String source) { System.out.println("\t\tParsing string : " + source); source = source.replaceAll(forbiddenCharacters, " ").trim(); System.out.println("\t\tSanitized string : " + source); String tempStreetNumber = null; Matcher streetNumberMatcher = streetNumberPattern.matcher(source); if (streetNumberMatcher.matches()) { tempStreetNumber = streetNumberMatcher.group(1); System.out.println("\t\tExtracting street number : " + tempStreetNumber); source = streetNumberMatcher.group(2).trim(); System.out.println("\t\tRemainging source : " + source); } Matcher otherFieldsMatcher = otherFieldsPattern.matcher(source); if (otherFieldsMatcher.matches()) { System.out.println("\t\tSource matches our pattern"); Address address = new Address(); address.setStreetNumber(tempStreetNumber); if (otherFieldsMatcher.group(1) != null) { address.setStreetName(otherFieldsMatcher.group(1).trim()); if (address.getStreetName().length() > 114) return null; } if (otherFieldsMatcher.group(3) != null) { address.setPostalCode(otherFieldsMatcher.group(3).trim()); } if (otherFieldsMatcher.group(4) != null) { address.setCity(otherFieldsMatcher.group(4).trim()); if (address.getCity().length() > 32) return null; } return address; } if ((tempStreetNumber + " " + source).trim().length() < 115) { System.out.println("\t\tSource doesn't match our pattern but is small enough, we put it in street name"); Address address = new Address(); address.setStreetName((tempStreetNumber + " " + source).trim()); return address; } System.out.println("\t\tCouldn't handle address !"); return null; }
diff --git a/SimpleAndroidApp/src/org/ivan/simple/game/monster/MonsterFactory.java b/SimpleAndroidApp/src/org/ivan/simple/game/monster/MonsterFactory.java index 71bc0b5..af0ac34 100644 --- a/SimpleAndroidApp/src/org/ivan/simple/game/monster/MonsterFactory.java +++ b/SimpleAndroidApp/src/org/ivan/simple/game/monster/MonsterFactory.java @@ -1,30 +1,30 @@ package org.ivan.simple.game.monster; import org.ivan.simple.game.hero.Sprite; public class MonsterFactory { public static Monster createMonster(MonsterModel model, int gridStep) { if(model == null) return new Monster(null, null, gridStep); Sprite monsterSprite; switch(model.getMonsterId()) { case 0: monsterSprite = new Sprite("monster/dishes.png", 1, 16); break; case 1: monsterSprite = new Sprite("monster/harmonica.png", 1, 16); break; case 2: monsterSprite = new Sprite("monster/whirligig.png", 1, 16); break; case 3: - monsterSprite = new Sprite("monster/monster2.png", 2, 16); + monsterSprite = new Sprite("monster/monster.png", 1, 32); break; default: monsterSprite = new Sprite("monster/dishes.png", 1, 16); break; } monsterSprite.setAnimating(true); return new Monster(model, monsterSprite, gridStep); } }
true
true
public static Monster createMonster(MonsterModel model, int gridStep) { if(model == null) return new Monster(null, null, gridStep); Sprite monsterSprite; switch(model.getMonsterId()) { case 0: monsterSprite = new Sprite("monster/dishes.png", 1, 16); break; case 1: monsterSprite = new Sprite("monster/harmonica.png", 1, 16); break; case 2: monsterSprite = new Sprite("monster/whirligig.png", 1, 16); break; case 3: monsterSprite = new Sprite("monster/monster2.png", 2, 16); break; default: monsterSprite = new Sprite("monster/dishes.png", 1, 16); break; } monsterSprite.setAnimating(true); return new Monster(model, monsterSprite, gridStep); }
public static Monster createMonster(MonsterModel model, int gridStep) { if(model == null) return new Monster(null, null, gridStep); Sprite monsterSprite; switch(model.getMonsterId()) { case 0: monsterSprite = new Sprite("monster/dishes.png", 1, 16); break; case 1: monsterSprite = new Sprite("monster/harmonica.png", 1, 16); break; case 2: monsterSprite = new Sprite("monster/whirligig.png", 1, 16); break; case 3: monsterSprite = new Sprite("monster/monster.png", 1, 32); break; default: monsterSprite = new Sprite("monster/dishes.png", 1, 16); break; } monsterSprite.setAnimating(true); return new Monster(model, monsterSprite, gridStep); }
diff --git a/src/org/jacorb/idl/lexer.java b/src/org/jacorb/idl/lexer.java index 61bf76ba0..5fed8a57f 100644 --- a/src/org/jacorb/idl/lexer.java +++ b/src/org/jacorb/idl/lexer.java @@ -1,1847 +1,1847 @@ /* * JacORB - a free Java ORB * * Copyright (C) 1997-2002 Gerald Brose. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.jacorb.idl; import java.util.*; import java_cup.runtime.token; import java_cup.runtime.int_token; import java_cup.runtime.long_token; import java_cup.runtime.char_token; import java_cup.runtime.float_token; /** * This class implements a scanner (aka lexical analyzer or * lexer) for IDL. The scanner reads characters from a global input * stream and returns integers corresponding to the terminal number * of the next token. Once the end of input is reached the EOF token * is returned on every subsequent call.<p> * * All symbol constants are defined in sym.java which is generated by * JavaCup from parser.cup.<p> * * In addition to the scanner proper (called first via init() then * with next_token() to get each token) this class provides simple * error and warning routines and keeps a count of errors and * warnings that is publicly accessible. It also provides basic * preprocessing facilties, i.e. it does handle preprocessor * directives such as #define, #undef, #include, etc. although it * does not provide full C++ preprocessing * * This class is "static" (i.e., it has only static members and methods). * * @version $Id$ * @author Gerald Brose * */ public class lexer { /** First and second character of lookahead. */ protected static int next_char; protected static int next_char2; /** EOF constant. */ protected static final int EOF_CHAR = -1; /** * Table of keywords. Keywords are initially treated as * identifiers. Just before they are returned we look them up in * this table to see if they match one of the keywords. The * string of the name is the key here, which indexes Integer * objects holding the symbol number. */ protected static Hashtable keywords = new Hashtable(); /** Table of keywords, stored in lower case. Keys are the * lower case version of the keywords used as keys for the keywords * hash above, and the values are the case sensitive versions of * the keywords. This table is used for detecting collisions of * identifiers with keywords. */ protected static Hashtable keywords_lower_case = new Hashtable(); /** Table of Java reserved names. */ protected static Hashtable java_keywords = new Hashtable(); /** Table of single character symbols. For ease of implementation, we * store all unambiguous single character tokens in this table of Integer * objects keyed by Integer objects with the numerical value of the * appropriate char (currently Character objects have a bug which precludes * their use in tables). */ protected static Hashtable char_symbols = new Hashtable(25); /** Defined symbols (preprocessor) */ protected static Hashtable defines = new Hashtable(); protected static boolean conditionalCompilation = true; /** nested #ifdefs are pushed on this stack by the "preprocessor" */ private static java.util.Stack ifStack = new Stack(); private static java.util.Stack tokenStack = new Stack(); /** Current line number for use in error messages. */ protected static int current_line = 1; /** Current line for use in error messages. */ protected static StringBuffer line = new StringBuffer(); /** Character position in current line. */ protected static int current_position = 1; /** Have we already read a '"' ? */ protected static boolean in_string = false; /** Are we processing a wide char or string ? */ protected static boolean wide = false; /** Count of total errors detected so far. */ static int error_count = 0; /** Count of warnings issued so far */ public static int warning_count = 0; /** currently active pragma prefix */ public static String currentPragmaPrefix = "" ; /** reset the scanner state */ public static void reset() { current_position = 1; error_count = 0; warning_count = 0; currentPragmaPrefix = "" ; line = new StringBuffer(); ifStack.removeAllElements(); tokenStack.removeAllElements(); defines.clear(); } /** * Initialize the scanner. This sets up the keywords and char_symbols * tables and reads the first two characters of lookahead. * * "Object" is listed as reserved in the OMG spec. * "int" is not, but I reserved it to bar its usage as a legal integer * type. */ public static void init() throws java.io.IOException { /* set up standard symbols */ defines.put("JACORB_IDL_1_4",""); /* set up the keyword table */ keywords.put("abstract", new Integer(sym.ABSTRACT)); keywords.put("any", new Integer(sym.ANY)); keywords.put("attribute", new Integer(sym.ATTRIBUTE)); keywords.put("boolean", new Integer(sym.BOOLEAN)); keywords.put("case", new Integer(sym.CASE)); keywords.put("char", new Integer(sym.CHAR)); keywords.put("const", new Integer(sym.CONST)); keywords.put("context", new Integer(sym.CONTEXT)); keywords.put("custom", new Integer(sym.CUSTOM)); keywords.put("default", new Integer(sym.DEFAULT)); keywords.put("double", new Integer(sym.DOUBLE)); keywords.put("enum", new Integer(sym.ENUM)); keywords.put("exception", new Integer(sym.EXCEPTION)); keywords.put("factory", new Integer(sym.FACTORY)); keywords.put("FALSE", new Integer(sym.FALSE)); keywords.put("fixed", new Integer(sym.FIXED)); keywords.put("float", new Integer(sym.FLOAT)); keywords.put("in", new Integer(sym.IN)); keywords.put("inout", new Integer(sym.INOUT)); keywords.put("interface", new Integer(sym.INTERFACE)); keywords.put("local", new Integer(sym.LOCAL)); keywords.put("long", new Integer(sym.LONG)); keywords.put("module", new Integer(sym.MODULE)); keywords.put("native", new Integer(sym.NATIVE)); keywords.put("Object", new Integer(sym.OBJECT)); keywords.put("octet", new Integer(sym.OCTET)); keywords.put("oneway", new Integer(sym.ONEWAY)); keywords.put("out", new Integer(sym.OUT)); keywords.put("private", new Integer(sym.PRIVATE)); keywords.put("public", new Integer(sym.PUBLIC)); keywords.put("pseudo", new Integer(sym.PSEUDO)); keywords.put("raises", new Integer(sym.RAISES)); keywords.put("readonly", new Integer(sym.READONLY)); keywords.put("sequence", new Integer(sym.SEQUENCE)); keywords.put("short", new Integer(sym.SHORT)); keywords.put("string", new Integer(sym.STRING)); keywords.put("struct", new Integer(sym.STRUCT)); keywords.put("supports", new Integer(sym.SUPPORTS)); keywords.put("switch", new Integer(sym.SWITCH)); keywords.put("TRUE", new Integer(sym.TRUE)); keywords.put("truncatable", new Integer(sym.TRUNCATABLE)); keywords.put("typedef", new Integer(sym.TYPEDEF)); keywords.put("unsigned", new Integer(sym.UNSIGNED)); keywords.put("union", new Integer(sym.UNION)); keywords.put("ValueBase", new Integer(sym.VALUEBASE)); keywords.put("valuetype", new Integer(sym.VALUETYPE)); keywords.put("void", new Integer(sym.VOID)); keywords.put("wchar", new Integer(sym.WCHAR)); keywords.put("wstring", new Integer(sym.WSTRING)); keywords.put("int", new Integer(sym.INT)); keywords.put("::", new Integer(sym.DBLCOLON)); keywords.put("<<", new Integer(sym.LSHIFT)); keywords.put(">>", new Integer(sym.RSHIFT)); keywords.put( "L\"", new Integer(sym.LDBLQUOTE)); // setup the mapping of lower case keywords to case sensitive // keywords for ( java.util.Enumeration e = keywords.keys(); e.hasMoreElements(); ) { String keyword = (String)e.nextElement(); String keyword_lower_case = keyword.toLowerCase(); keywords_lower_case.put ( keyword_lower_case, keyword ); } /* set up the table of single character symbols */ char_symbols.put(new Integer(';'), new Integer(sym.SEMI)); char_symbols.put(new Integer(','), new Integer(sym.COMMA)); char_symbols.put(new Integer('*'), new Integer(sym.STAR)); char_symbols.put(new Integer('.'), new Integer(sym.DOT)); char_symbols.put(new Integer(':'), new Integer(sym.COLON)); char_symbols.put(new Integer('='), new Integer(sym.EQUALS)); char_symbols.put(new Integer('+'), new Integer(sym.PLUS)); char_symbols.put(new Integer('-'), new Integer(sym.MINUS)); char_symbols.put(new Integer('{'), new Integer(sym.LCBRACE)); char_symbols.put(new Integer('}'), new Integer(sym.RCBRACE)); char_symbols.put(new Integer('('), new Integer(sym.LPAREN)); char_symbols.put(new Integer(')'), new Integer(sym.RPAREN)); char_symbols.put(new Integer('['), new Integer(sym.LSBRACE)); char_symbols.put(new Integer(']'), new Integer(sym.RSBRACE)); char_symbols.put(new Integer('<'), new Integer(sym.LESSTHAN)); char_symbols.put(new Integer('>'), new Integer(sym.GREATERTHAN)); char_symbols.put(new Integer('\''), new Integer(sym.QUOTE)); char_symbols.put(new Integer('\"'), new Integer(sym.DBLQUOTE)); char_symbols.put(new Integer('\\'), new Integer(sym.BSLASH)); char_symbols.put(new Integer('^'), new Integer(sym.CIRCUM)); char_symbols.put(new Integer('&'), new Integer(sym.AMPERSAND)); char_symbols.put(new Integer('/'), new Integer(sym.SLASH)); char_symbols.put(new Integer('%'), new Integer(sym.PERCENT)); char_symbols.put(new Integer('~'), new Integer(sym.TILDE)); char_symbols.put(new Integer('|'), new Integer(sym.BAR)); /* set up reserved Java names */ java_keywords.put("abstract", ""); java_keywords.put("boolean", ""); java_keywords.put("break", ""); java_keywords.put("byte", ""); java_keywords.put("case", ""); java_keywords.put("catch", ""); java_keywords.put("char", ""); java_keywords.put("class", ""); java_keywords.put("const", ""); java_keywords.put("continue", ""); java_keywords.put("default", ""); java_keywords.put("do", ""); java_keywords.put("double", ""); java_keywords.put("else", ""); java_keywords.put("extends", ""); java_keywords.put("false", ""); java_keywords.put("final", ""); java_keywords.put("finally", ""); java_keywords.put("for", ""); java_keywords.put("float", ""); java_keywords.put("goto", ""); java_keywords.put("if", ""); java_keywords.put("implements", ""); java_keywords.put("import", ""); java_keywords.put("instanceof", ""); java_keywords.put("int", ""); java_keywords.put("interface", ""); java_keywords.put("long", ""); java_keywords.put("native", ""); java_keywords.put("new", ""); java_keywords.put("null", ""); java_keywords.put("package", ""); java_keywords.put("protected", ""); java_keywords.put("private", ""); java_keywords.put("public", ""); java_keywords.put("return", ""); java_keywords.put("short", ""); java_keywords.put("static", ""); java_keywords.put("super", ""); java_keywords.put("switch", ""); java_keywords.put("synchronized", ""); java_keywords.put("true", ""); java_keywords.put("this", ""); java_keywords.put("throw", ""); java_keywords.put("throws", ""); java_keywords.put("transient", ""); java_keywords.put("try", ""); java_keywords.put("volatile", ""); java_keywords.put("void", ""); java_keywords.put("while", ""); java_keywords.put("clone", ""); java_keywords.put("equals", ""); java_keywords.put("finalize", ""); java_keywords.put("getClass", ""); java_keywords.put("hashCode", ""); java_keywords.put("notify", ""); java_keywords.put("toString", ""); java_keywords.put("wait", ""); /* stack needs a topmost value */ ifStack.push( new Boolean(true)); /* read two characters of lookahead */ try { next_char = GlobalInputStream.read(); } catch (Exception e) { org.jacorb.idl.parser.fatal_error( "Cannot read from file " + GlobalInputStream.currentFile().getAbsolutePath() + ", please check file name.", null); } if (next_char == EOF_CHAR) next_char2 = EOF_CHAR; else next_char2 = GlobalInputStream.read(); } public static void define(String symbol, String value) { Environment.output(4,"Defining: " + symbol + " as " + value ); defines.put(symbol, value); } public static void undefine(String symbol) { Environment.output(4,"Un-defining: " + symbol); defines.remove(symbol); } public static String defined(String symbol) { return (String)defines.get(symbol); } /** record information about the last lexical scope so that it can be restored later */ public static int currentLine() { return current_line; } /** * asks the lexer to return its own */ public static PositionInfo getPosition() { return new PositionInfo( current_line, current_position, currentPragmaPrefix, line.toString() ); } public static void restorePosition(PositionInfo p) { current_line = p.line_no; currentPragmaPrefix = p.pragma_prefix; current_position = 0; } /** * Advance the scanner one character in the input stream. This moves * next_char2 to next_char and then reads a new next_char2. */ protected static void advance() throws java.io.IOException { int old_char; old_char = next_char; next_char = next_char2; next_char2 = GlobalInputStream.read(); line.append( (char)old_char ); /* count this */ current_position++; if (old_char == '\n') { current_line++; current_position = 1; line = new StringBuffer(); } //System.out.println("advance. next_char is " + next_char + " (" + (char)next_char + ")"); } /** * Emit an error message. The message will be marked with both the * current line number and the position in the line. Error messages * are printed on standard error (System.err). * @param message the message to print. * @param p_info an optional PositionInfo object */ public static void emit_error(String message) { System.err.println( GlobalInputStream.currentFile().getAbsolutePath() + ", line: "+current_line + "(" +current_position + "): " + message); System.err.println("\t" + line.toString() ); error_count++; } public static void emit_error(String message, str_token t) { if( t == null ) { emit_error( message ); } else { System.err.println( "Error in " + t.fileName + ", line:" + t.line_no + "(" + t.char_pos + "): " + message ); System.err.println("\t" + t.line_val ); error_count++; } } /** Emit a warning message. The message will be marked with both the * current line number and the position in the line. Messages are * printed on standard error (System.err). * @param message the message to print. */ public static void emit_warn(String message) { System.err.println("Warning: " + message + " at " + current_line + "(" + current_position + "): \"" + line.toString() + "\"" ); warning_count++; } public static void emit_warn( String message, str_token t) { if( t == null ) { emit_warn( message ); } else { System.err.println( "Warning at " + t.fileName + ", line:" + t.line_no + "(" + t.char_pos + "): " + message ); System.err.println("\t" + t.line_val ); warning_count++; } } /** * Determine if a character is ok to start an id. * @param ch the character in question. */ protected static boolean id_start_char(int ch) { return ( ch >= 'a' && ch <= 'z') || ( ch >= 'A' && ch <= 'Z') || ( ch == '_') ; } /** * Determine if a character is ok for the middle of an id. * @param ch the character in question. */ protected static boolean id_char(int ch) { return id_start_char(ch) || (ch == '_') || (ch >= '0' && ch <= '9'); } /** * Try to look up a single character symbol, returns -1 for not found. * @param ch the character in question. */ protected static int find_single_char(int ch) { Integer result; result = (Integer)char_symbols.get(new Integer((char)ch)); if (result == null) return -1; else return result.intValue(); } /** * Handle swallowing up a comment. Both old style C and new style C++ * comments are handled. */ protected static void swallow_comment() throws java.io.IOException { /* next_char == '/' at this point */ /* is it a traditional comment */ if (next_char2 == '*') { /* swallow the opener */ advance(); advance(); /* swallow the comment until end of comment or EOF */ for (;;) { /* if its EOF we have an error */ if (next_char == EOF_CHAR) { emit_error("Specification file ends inside a comment", null); return; } /* if we can see the closer we are done */ if (next_char == '*' && next_char2 == '/') { advance(); advance(); return; } /* otherwise swallow char and move on */ advance(); } } /* is its a new style comment */ if (next_char2 == '/') { /* swallow the opener */ advance(); advance(); /* swallow to '\n', '\f', or EOF */ while (next_char != '\n' && next_char != '\f' && next_char != '\r' && next_char!=EOF_CHAR) { advance(); } return; } /* shouldn't get here, but... if we get here we have an error */ emit_error("Malformed comment in specification -- ignored", null); advance(); } /** * Preprocessor directives are handled here. */ protected static void preprocess() throws java.io.IOException { for (;;) { /* if its EOF we have an error */ if (next_char == EOF_CHAR) { emit_error("Specification file ends inside a preprocessor directive", null); return; } else if( next_char != '#' ) { emit_error("expected #, got " + (char)next_char + " instead!", null); } else advance(); // skip '#' // the following is done to allow for # ifdef sloppiness while ( ( ' ' == next_char ) || ( '\t' == next_char ) ) advance(); String dir = get_string(); if( dir.equals("include")) { if( !conditionalCompilation) return; advance(); // skip ' ' boolean useIncludePath = ( next_char == '<' ); advance(); // skip `\"' or '<' String fname = get_string(); if( useIncludePath && ( next_char != '>' )) emit_error("Syntax error in #include directive, expecting '>'"); else if( !useIncludePath && ( next_char != '\"' )) emit_error("Syntax error in #include directive, expecting \""); /* swallow to '\n', '\f', or EOF */ while (next_char != '\n' && next_char != '\f' && next_char != '\r' && next_char!=EOF_CHAR ) { advance(); } GlobalInputStream.include( fname, (char)next_char2, useIncludePath ); current_line = 0; advance(); advance(); // System.out.println("returning from include, next_char is: " + (char)next_char); return; } else if( dir.equals("define")) { if( !conditionalCompilation) return; // advance(); // skip ' ' swallow_whitespace(); String name = get_string(); StringBuffer text = new StringBuffer(); if( next_char == ' ' ) { advance(); } while( next_char != '\n' ) { if( next_char == '\\') { advance();advance(); } text.append( (char)next_char ); advance(); } // System.out.println("#Defined symbol " + name + " as: " + text.toString() ); define( name, text.toString() ); } else if( dir.equals("error")) { if( !conditionalCompilation) return; advance(); // skip ' ' String name = get_string(); emit_error( name ); } else if( dir.equals("undef")) { if( !conditionalCompilation) return ; swallow_whitespace(); // advance(); // skip ' ' String name = get_string(); undefine(name); // System.out.println("#Undefined symbol " + name ); } else if( dir.equals("if")) { ifStack.push( new Boolean(conditionalCompilation)); if( !conditionalCompilation) return ; swallow_whitespace(); // the following snippet distinguishes between #if defined // and #if !defined boolean straightDefined = true; if ( '!' == next_char ) { advance(); straightDefined = false; } String defineStr = get_string_no_paren(); if ( ! ( defineStr.equals("defined") ) ) { emit_error("Expected \"defined\" following #if: " + dir, null); return; } swallow_whitespace(); boolean brackets = ( '(' == next_char ); if( brackets ) { advance(); // skip '(' swallow_whitespace(); // any whitespace after ( ? skip it } String name = get_string_no_paren(); if( brackets ) { swallow_whitespace(); Environment.output(4, "next char: " + next_char ); if( ')' != next_char ) { emit_error("Expected ) terminating #if defined", null); return; } advance(); } if ( straightDefined ) conditionalCompilation = (null != defined(name)); else conditionalCompilation = (null == defined(name)); } else if( dir.equals("ifdef")) { ifStack.push( new Boolean(conditionalCompilation)); if( !conditionalCompilation) return ; swallow_whitespace(); //advance(); // skip ' ' String name = get_string(); conditionalCompilation = ( defined(name) != null ); } else if( dir.equals("ifndef")) { ifStack.push( new Boolean(conditionalCompilation)); if( !conditionalCompilation) return ; swallow_whitespace();//advance(); // skip ' ' String name = get_string(); conditionalCompilation = ( defined(name) == null ); } else if( dir.equals("else")) { if( ((Boolean)ifStack.peek()).booleanValue()) conditionalCompilation = !conditionalCompilation; } else if( dir.equals("endif")) { boolean b = ((Boolean)ifStack.pop()).booleanValue(); conditionalCompilation = b; } else if( dir.equals("pragma")) { if( !conditionalCompilation) return ; advance(); // skip ' ' String name = get_string(); if( name.equals("prefix")) { advance(); // skip ' ' // if( (char)next_char != '\"' ) // emit_error("Expecting \" "); // advance(); // skip '"' String prefix = get_string(); // if( (char)next_char != '\"' ) // emit_error("Expecting \" "); // advance(); // skip '"' currentPragmaPrefix = prefix; } else if( name.equals("version")) { advance(); // skip ' ' String vname = get_string(); advance(); // skip ' ' String version = get_string(); parser.currentScopeData().versionMap.put(vname,version); } else if( name.equals("ID")) { advance(); // skip ' ' String iname = get_string(); advance(); // skip ' ' String id = get_string(); // do something with it } else if( name.equals("local")) { /* proprietary pragma of the JacORB IDL compiler */ // parser.setLocalityContraint(); } else if( name.equals("inhibit_code_generation")) { /* proprietary pragma of the JacORB IDL compiler */ parser.setInhibitionState(true); // do something with it } else emit_warn("Unknown pragma, ignoring: #pragma " + name, null); } else emit_error("Unrecognized preprocessor directive " + dir, null); /* swallow to '\n', '\f', or EOF */ while (next_char != '\n' && next_char != '\f' && next_char != '\r' && next_char!=EOF_CHAR ) { // System.out.println("Advancing after directive, next_char is: " + (char)next_char); advance(); } return; } } // the following is used for parsing the #if defined(...) construct private static String get_string_no_paren() throws java.io.IOException { StringBuffer sb = new StringBuffer(); char c = (char)next_char; while( c != ' ' && c != '\t' && c != '\r' && c != '\n' && c != '\f' && c != EOF_CHAR && c != '\"' && c != '<' && c != '>' && c != '(' && c != ')' ) { sb.append( c ); advance(); c = (char)next_char; } // System.out.println("get string returns " + sb.toString()); return sb.toString(); } private static String get_string() throws java.io.IOException { StringBuffer sb = new StringBuffer(""); if( next_char == '\"' ) { advance(); while( next_char != '\"' ) { if( next_char == EOF_CHAR ) emit_error("Unexpected EOF in string"); sb.append( (char)next_char ); advance(); } } else { while( next_char != ' ' && next_char != '\t' && next_char != '\r' && next_char != '\n' && next_char != '\f' && next_char != EOF_CHAR && next_char != '\"' && next_char != '<' && next_char != '>' ) { sb.append( (char)next_char ); advance(); } } return sb.toString(); } /** * Process an identifier. * <P> * Identifiers begin with a letter, underscore, or dollar sign, * which is followed by zero or more letters, numbers, * underscores or dollar signs. This routine returns a str_token * suitable for return by the scanner or null, if the string that * was read expanded to a symbol that was #defined. In this case, * the symbol is expanded in place */ protected static token do_symbol() throws java.io.IOException { StringBuffer result = new StringBuffer(); String result_str; Integer keyword_num = null; char buffer[] = new char[1]; /* next_char holds first character of id */ buffer[0] = (char)next_char; result.append(buffer,0,1); advance(); /* collect up characters while they fit in id */ while( id_char(next_char) ) { buffer[0] = (char)next_char; result.append(buffer,0,1); advance(); } /* extract a string */ result_str = result.toString(); /* try to look it up as a defined symbol... */ String text = defined( result_str ); if( text != null ) { char [] next = {(char)next_char,(char)next_char2}; GlobalInputStream.insert(text + ( new String(next)) ); //System.out.println("Advancing after symbol " + result_str ); advance(); // restore lookahead advance(); // restore lookahead return null; } // check if it's a keyword Environment.output(3, "Advancing after symbol " + result_str ); keyword_num = (Integer)keywords.get(result_str); if ( keyword_num != null ) { if( isScope( result_str )) { parser.openScope(); } return new token(keyword_num.intValue()); } // not a keyword, so treat as identifier after verifying // case sensitivity rules and prefacing with an _ // if it collides with a Java keyword. result_str = checkIdentifier ( result_str ); if ( null != result_str ) return new str_token( sym.ID, result_str, getPosition(), GlobalInputStream.currentFile().getName() ); else return null; } private static boolean isScope( String keyword ) { return ( keyword.equals("module") || keyword.equals("interface") || keyword.equals("struct") || keyword.equals("exception") || keyword.equals("union") // keyword.equals("valuetype") ); } /** * checks whether Identifier str is legal and returns it, * prepends an underscore if necessary to avoid clashes with * Java reserved words */ public static String checkIdentifier( String str ) { Environment.output(3, "checking identifier " + str ); /* if it is not an escaped identifier, look it up as a keyword */ if( str.charAt(0) == '_' ) { return str.substring(1); } String colliding_keyword = (String)keywords_lower_case.get(str.toLowerCase()); if ( colliding_keyword != null ) { emit_error("Identifier " + str + " collides with keyword " + colliding_keyword + "."); return null; } if( needsJavaEscape( str )) { // Environment.output(4, "checking identifier " + str + " : needs _ "); return "_" + str; } // Environment.output(4, "checking identifier " + str + " : needs no _ "); return str; } /** * Only the most general name clashes with Java keywords * are caught here. Identifiers need to be checked again * at different other places in the compiler! */ private static boolean needsJavaEscape( String s ) { return( java_keywords.containsKey(s) ); } public static boolean strictJavaEscapeCheck( String s ) { return( (!s.equals("Helper") && s.endsWith("Helper")) || (!s.equals("Holder") && s.endsWith("Holder")) || (!s.equals("Operations") && s.endsWith("Operations")) || (!s.equals("Package") && s.endsWith("Package")) || (!s.equals("POA") && s.endsWith("POA")) || (!s.equals("POATie") && s.endsWith("POATie"))); } public static boolean needsJavaEscape( Module m ) { String s = m.pack_name; Environment.output(4, "checking module name " + s ); return ( strictJavaEscapeCheck(s)); } /** * Return one token. This is the main external interface to the scanner. * It consumes sufficient characters to determine the next input token * and returns it. */ public static token next_token() throws java.io.IOException { parser.set_included( GlobalInputStream.includeState()); token result = real_next_token(); // System.out.println("# next_token() => " + result.sym); return result; } private static void swallow_whitespace() throws java.io.IOException { /* look for white space */ while (next_char == ' ' || next_char == '\t' || next_char == '\n' || next_char == '\f' || next_char == '\r' ) { /* advance past it and try the next character */ //System.out.println("Swallowing whitespace: " + next_char + (char)next_char); advance(); } } /** * The actual routine to return one token. */ protected static token real_next_token() throws java.io.IOException { int sym_num; if( !tokenStack.empty()) return (token)tokenStack.pop(); for (;;) { if( !in_string ) { swallow_whitespace(); /* look for preprocessor directives */ if( (char)next_char == '#' ) { preprocess(); continue; } /* look for a comment */ if (next_char == '/' && (next_char2 == '*' || next_char2 == '/')) { /* swallow then continue the scan */ swallow_comment(); continue; } if( !conditionalCompilation ) { advance(); if( next_char == EOF_CHAR ) { emit_error("EOF in conditional compilation!", null); return null; } else continue; } /* look for COLON or DBLCOLON */ if (next_char == ':') { if (next_char2 == ':') { advance(); advance(); return new token(sym.DBLCOLON); } else { advance(); return new token(sym.COLON); } } /* leading L for wide strings */ if (next_char == 'L' && next_char2 == '\"') { advance(); advance(); wide = true; in_string = true; return new token(sym.LDBLQUOTE); } /* look for Shifts */ if (next_char == '<') { if (next_char2 == '<') { advance(); advance(); return new token(sym.LSHIFT); } else { advance(); return new token(sym.LESSTHAN); } } if (next_char == '>') { if (next_char2 == '>') { advance(); advance(); return new token(sym.RSHIFT); } else { advance(); return new token(sym.GREATERTHAN); } } /* leading 0: */ /* Try to scan octal/hexadecimal numbers, might even find a float */ if (next_char == '0') { long l_val = 0; long l_val_old = 0; int radix = 8; int digit = 0; advance(); - if( next_char == '.' ) + if (next_char == '.') { StringBuffer f_string = new StringBuffer("0."); advance(); while( next_char >= '0' && next_char <= '9') { f_string.append( (char)next_char ); advance(); } float f_val = (new Float( f_string.toString() )).floatValue(); return new float_token(sym.FLOAT_NUMBER, f_val); } else { // See if hexadecimal value if (next_char == 'x' || next_char == 'X') { advance (); radix = 16; } - StringBuffer val = new StringBuffer (); + StringBuffer val = new StringBuffer ("0"); digit = Character.digit ((char) next_char, radix); while (digit != -1 ) { val.append ((char) next_char); advance(); digit = Character.digit((char) next_char, radix); } String str = val.toString (); try { return new int_token (sym.NUMBER, Integer.parseInt (str, radix)); } catch (NumberFormatException ex) { try { return new long_token (sym.LONG_NUMBER, Long.parseLong (str, radix)); } catch (NumberFormatException ex2) { emit_error ("Invalid octal/hex value: " + str); } } return null; } } /* Try to scan integer, floating point or fixed point literals */ if ( (next_char >= '0' && next_char <= '9') || next_char == '.' ) { StringBuffer value = new StringBuffer(); StringBuffer fraction = null; int exp = 0; /* read integer part */ while (next_char >= '0' && next_char <= '9') { value.append( (char)next_char); // System.out.println("Read integer part " + value.toString()); advance(); } /* read fraction */ if( next_char == '.' ) { fraction = new StringBuffer(); advance(); // System.out.println("Reading fraction part"); while( next_char >= '0' && next_char <= '9') { fraction.append( (char)next_char ); advance(); } } if( next_char == 'e' || next_char == 'E' ) { // System.out.println("Reading exponent"); if( fraction == null ) fraction = new StringBuffer(); fraction.append('e'); advance(); if( next_char == '-' || next_char == '+') { fraction.append( (char)next_char ); advance(); } while( next_char >= '0' && next_char <= '9') { fraction.append( (char)next_char ); advance(); } if( fraction.length() == 1 ) { emit_error("Empty exponent in float/double."); continue; } return new float_token( sym.FLOAT_NUMBER, Float.valueOf( value.toString() + "." + fraction.toString()).floatValue()); } if( next_char == 'd' || next_char == 'D' ) { advance(); if( fraction == null ) fraction = new StringBuffer(); java.math.BigDecimal bi = new java.math.BigDecimal(value.toString() + "." + fraction.toString()); return new fixed_token(sym.FIXED_NUMBER, bi); } if (fraction == null) { /* integer or long */ token tok = null; String str = value.toString (); try { tok = new int_token (sym.NUMBER, Integer.parseInt (str)); } catch (NumberFormatException ex) { try { tok = new long_token (sym.LONG_NUMBER, Long.parseLong (str)); } catch (NumberFormatException ex2) { emit_error ("Invalid long value: " + str); } } return tok; } else { try { float f = Float.valueOf( value.toString() + "." + fraction.toString()).floatValue(); return new float_token(sym.FLOAT_NUMBER, f ); } catch( NumberFormatException nf ) { emit_error("Unexpected symbol: " + value.toString() + "." + fraction.toString()); } } } /* look for a single character symbol */ sym_num = find_single_char(next_char); if( (char)next_char == '\"' ) { in_string = true; advance(); return new token(sym.DBLQUOTE); } if( (char)next_char == '\'' ) { advance(); token t = null; if (next_char == '\\') { // Now need to process escaped character. advance(); if (isDigit ((char)next_char)) { // Octal character char octal1 = '0'; char octal2 = '0'; char octal3 = (char)next_char; if (isDigit ((char)next_char2)) { advance (); octal2 = octal3; octal3 = (char)next_char; if (isDigit ((char)next_char2)) { advance (); octal1 = octal2; octal2 = octal3; octal3 = (char)next_char; } } t= new char_token ( sym.CH, (char)Integer.parseInt (new String (new char [] {octal1, octal2, octal3}), 8 ) ); } else if ((char)next_char == 'x') { // Hexadecimal character advance (); char hex1 = '0'; char hex2 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); hex1 = hex2; hex2 = (char)next_char; } else if ((char)next_char2 != '\'') { emit_error ("Illegal hex character"); return null; } t= new char_token ( sym.CH, (char)Integer.parseInt (new String (new char [] {hex1, hex2}), 16 ) ); } else if ((char)next_char == 'u') { if (wide == false) { emit_error ("Unicode characters are only legal with wide character"); return null; } else { // Hexadecimal character advance (); char uni1 = '0'; char uni2 = '0'; char uni3 = '0'; char uni4 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni3 = uni4; uni4 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni2 = uni3; uni3 = uni4; uni4 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni1 = uni2; uni2 = uni3; uni3 = uni4; uni4 = (char)next_char; } else if ((char)next_char2 != '\'') { emit_error ("Illegal unicode character"); return null; } } else if ((char)next_char2 != '\'') { emit_error ("Illegal unicode character"); return null; } } else if ((char)next_char2 != '\'') { emit_error ("Illegal unicode character"); return null; } t= new char_token ( sym.CH, (char)Integer.parseInt (new String (new char [] {uni1, uni2, uni3, uni4}), 16 ) ); } } else { switch (next_char) { case 'n': { t = new char_token(sym.CH,'\n'); break; } case 't': { t = new char_token(sym.CH,'\t'); break; } case 'v': { t = new char_token(sym.CH,'\013'); break; } case 'b': { t = new char_token(sym.CH,'\b'); break; } case 'r': { t = new char_token(sym.CH,'\r'); break; } case 'f': { t = new char_token(sym.CH,'\f'); break; } case 'a': { t = new char_token(sym.CH,'\007'); break; } case '\\': { t = new char_token(sym.CH,'\\'); break; } case '?': { t = new char_token(sym.CH,'?'); break; } case '0': { t = new char_token(sym.CH,'\0'); break; } case '\'': { t = new char_token(sym.CH,'\''); break; } case '\"': { t = new char_token(sym.CH,'\"'); break; } default: { emit_error("Invalid escape symbol \'"); return null; } } } } else { t = new char_token(sym.CH,(char)next_char); } advance(); if( (char)next_char == '\'' ) { tokenStack.push( new token(sym.QUOTE)); tokenStack.push(t); advance(); } else { emit_error("Expecting closing \'"); return null; } wide = false; return new token(sym.QUOTE); } if (sym_num != -1) { /* found one -- advance past it and return a token for it */ advance(); return new token(sym_num); } /* look for an id or keyword */ if ( id_start_char(next_char) ) { token t = do_symbol(); if( t != null ) return t; else continue; } /* look for EOF */ if (next_char == EOF_CHAR) { return new token(sym.EOF); } } else // in_string { /* empty string ? */ if( (char)next_char == '\"' ) { in_string = false; advance(); return new token(sym.DBLQUOTE); // return new org.jacorb.idl.str_token(sym.ID, "", getPosition()); } StringBuffer result = new StringBuffer(); char previous = ' '; /* collect up characters while they fit in id */ while(true) { if (next_char == '\\') { // Remap those characters that have no equivilant in java switch (next_char2) { case 'a': { result.append ("\\007"); previous = 'a'; advance(); break; } case 'v': { result.append ("\\013"); previous = 'v'; advance(); break; } case '?': { result.append ("?"); previous = '?'; advance(); break; } // Replace \xA0 by octal equivilant case 'x': { advance(); advance(); // Now next_char will be A and next_char2 will be 0 String octal = Integer.toOctalString ( Integer.parseInt ( new String ( new char [] { (char)next_char, (char)next_char2} ), 16 ) ); if (octal.length () != 3) { if (octal.length () == 1) { octal = "0" + octal; } octal = "0" + octal; } result.append ("\\" + octal); previous = (char)next_char2; advance(); break; } case 'u': { if (wide == false) { emit_error ("Unicode characters are only legal with wide strings"); return null; } else { result.append ((char)next_char); result.append ((char)next_char2); advance (); advance (); char uni1 = (char)next_char; char uni2 = '0'; char uni3 = '0'; char uni4 = '0'; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni2 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni3 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni4 = (char)next_char; } else { emit_error ("Illegal unicode character"); return null; } } else { emit_error ("Illegal unicode character"); return null; } } else { emit_error ("Illegal unicode character"); return null; } previous = uni4; result.append (uni1); result.append (uni2); result.append (uni3); result.append (uni4); } break; } default: { previous = (char)next_char; result.append ((char)next_char); } } } else { previous = (char)next_char; result.append ((char)next_char); } advance(); // Handle backslash quote but exit if just quote if (((char)next_char) == '\"'&& previous != '\\') { break; } } wide = false; // String s = checkIdentifier( result.toString() ); String s = result.toString(); /* build and return an id token with an attached string */ return new org.jacorb.idl.str_token(sym.ID, s , getPosition(), GlobalInputStream.currentFile().getName()); } /* if we get here, we have an unrecognized character */ emit_warn("Unrecognized character '" + new Character((char)next_char) + "'(" +next_char+ ") -- ignored"); /* advance past it */ advance(); } } /** * Returns true if character is US ASCII 0-9 * * @param c a value of type 'char' * @return a value of type 'boolean' */ private static boolean isDigit (char c) { boolean result = false; if (c >= '\u0030') { if (c <= '\u0039') { // Range 0030 [0] -> 0039 [9] result = true; } } return result; } /** * Returns true if character is US ASCII 0-9, a-f, A-F * * @param c a value of type 'char' * @return a value of type 'boolean' */ private static boolean isHexLetterOrDigit (char c) { boolean result = false; if (c >= '\u0030') { if (c <= '\u0039') { // Range 0030 [0] -> 0039 [9] result = true; } else { if (c >= '\u0041') { if (c <= '\u0046') { // Range 0041 [A] -> 0046 [F] result = true; } if (c >= '\u0061') { if (c <= '\u0066') { // Range 0061 [a] -> 0066 [f] result = true; } } } } } return result; } }
false
true
protected static token real_next_token() throws java.io.IOException { int sym_num; if( !tokenStack.empty()) return (token)tokenStack.pop(); for (;;) { if( !in_string ) { swallow_whitespace(); /* look for preprocessor directives */ if( (char)next_char == '#' ) { preprocess(); continue; } /* look for a comment */ if (next_char == '/' && (next_char2 == '*' || next_char2 == '/')) { /* swallow then continue the scan */ swallow_comment(); continue; } if( !conditionalCompilation ) { advance(); if( next_char == EOF_CHAR ) { emit_error("EOF in conditional compilation!", null); return null; } else continue; } /* look for COLON or DBLCOLON */ if (next_char == ':') { if (next_char2 == ':') { advance(); advance(); return new token(sym.DBLCOLON); } else { advance(); return new token(sym.COLON); } } /* leading L for wide strings */ if (next_char == 'L' && next_char2 == '\"') { advance(); advance(); wide = true; in_string = true; return new token(sym.LDBLQUOTE); } /* look for Shifts */ if (next_char == '<') { if (next_char2 == '<') { advance(); advance(); return new token(sym.LSHIFT); } else { advance(); return new token(sym.LESSTHAN); } } if (next_char == '>') { if (next_char2 == '>') { advance(); advance(); return new token(sym.RSHIFT); } else { advance(); return new token(sym.GREATERTHAN); } } /* leading 0: */ /* Try to scan octal/hexadecimal numbers, might even find a float */ if (next_char == '0') { long l_val = 0; long l_val_old = 0; int radix = 8; int digit = 0; advance(); if( next_char == '.' ) { StringBuffer f_string = new StringBuffer("0."); advance(); while( next_char >= '0' && next_char <= '9') { f_string.append( (char)next_char ); advance(); } float f_val = (new Float( f_string.toString() )).floatValue(); return new float_token(sym.FLOAT_NUMBER, f_val); } else { // See if hexadecimal value if (next_char == 'x' || next_char == 'X') { advance (); radix = 16; } StringBuffer val = new StringBuffer (); digit = Character.digit ((char) next_char, radix); while (digit != -1 ) { val.append ((char) next_char); advance(); digit = Character.digit((char) next_char, radix); } String str = val.toString (); try { return new int_token (sym.NUMBER, Integer.parseInt (str, radix)); } catch (NumberFormatException ex) { try { return new long_token (sym.LONG_NUMBER, Long.parseLong (str, radix)); } catch (NumberFormatException ex2) { emit_error ("Invalid octal/hex value: " + str); } } return null; } } /* Try to scan integer, floating point or fixed point literals */ if ( (next_char >= '0' && next_char <= '9') || next_char == '.' ) { StringBuffer value = new StringBuffer(); StringBuffer fraction = null; int exp = 0; /* read integer part */ while (next_char >= '0' && next_char <= '9') { value.append( (char)next_char); // System.out.println("Read integer part " + value.toString()); advance(); } /* read fraction */ if( next_char == '.' ) { fraction = new StringBuffer(); advance(); // System.out.println("Reading fraction part"); while( next_char >= '0' && next_char <= '9') { fraction.append( (char)next_char ); advance(); } } if( next_char == 'e' || next_char == 'E' ) { // System.out.println("Reading exponent"); if( fraction == null ) fraction = new StringBuffer(); fraction.append('e'); advance(); if( next_char == '-' || next_char == '+') { fraction.append( (char)next_char ); advance(); } while( next_char >= '0' && next_char <= '9') { fraction.append( (char)next_char ); advance(); } if( fraction.length() == 1 ) { emit_error("Empty exponent in float/double."); continue; } return new float_token( sym.FLOAT_NUMBER, Float.valueOf( value.toString() + "." + fraction.toString()).floatValue()); } if( next_char == 'd' || next_char == 'D' ) { advance(); if( fraction == null ) fraction = new StringBuffer(); java.math.BigDecimal bi = new java.math.BigDecimal(value.toString() + "." + fraction.toString()); return new fixed_token(sym.FIXED_NUMBER, bi); } if (fraction == null) { /* integer or long */ token tok = null; String str = value.toString (); try { tok = new int_token (sym.NUMBER, Integer.parseInt (str)); } catch (NumberFormatException ex) { try { tok = new long_token (sym.LONG_NUMBER, Long.parseLong (str)); } catch (NumberFormatException ex2) { emit_error ("Invalid long value: " + str); } } return tok; } else { try { float f = Float.valueOf( value.toString() + "." + fraction.toString()).floatValue(); return new float_token(sym.FLOAT_NUMBER, f ); } catch( NumberFormatException nf ) { emit_error("Unexpected symbol: " + value.toString() + "." + fraction.toString()); } } } /* look for a single character symbol */ sym_num = find_single_char(next_char); if( (char)next_char == '\"' ) { in_string = true; advance(); return new token(sym.DBLQUOTE); } if( (char)next_char == '\'' ) { advance(); token t = null; if (next_char == '\\') { // Now need to process escaped character. advance(); if (isDigit ((char)next_char)) { // Octal character char octal1 = '0'; char octal2 = '0'; char octal3 = (char)next_char; if (isDigit ((char)next_char2)) { advance (); octal2 = octal3; octal3 = (char)next_char; if (isDigit ((char)next_char2)) { advance (); octal1 = octal2; octal2 = octal3; octal3 = (char)next_char; } } t= new char_token ( sym.CH, (char)Integer.parseInt (new String (new char [] {octal1, octal2, octal3}), 8 ) ); } else if ((char)next_char == 'x') { // Hexadecimal character advance (); char hex1 = '0'; char hex2 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); hex1 = hex2; hex2 = (char)next_char; } else if ((char)next_char2 != '\'') { emit_error ("Illegal hex character"); return null; } t= new char_token ( sym.CH, (char)Integer.parseInt (new String (new char [] {hex1, hex2}), 16 ) ); } else if ((char)next_char == 'u') { if (wide == false) { emit_error ("Unicode characters are only legal with wide character"); return null; } else { // Hexadecimal character advance (); char uni1 = '0'; char uni2 = '0'; char uni3 = '0'; char uni4 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni3 = uni4; uni4 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni2 = uni3; uni3 = uni4; uni4 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni1 = uni2; uni2 = uni3; uni3 = uni4; uni4 = (char)next_char; } else if ((char)next_char2 != '\'') { emit_error ("Illegal unicode character"); return null; } } else if ((char)next_char2 != '\'') { emit_error ("Illegal unicode character"); return null; } } else if ((char)next_char2 != '\'') { emit_error ("Illegal unicode character"); return null; } t= new char_token ( sym.CH, (char)Integer.parseInt (new String (new char [] {uni1, uni2, uni3, uni4}), 16 ) ); } } else { switch (next_char) { case 'n': { t = new char_token(sym.CH,'\n'); break; } case 't': { t = new char_token(sym.CH,'\t'); break; } case 'v': { t = new char_token(sym.CH,'\013'); break; } case 'b': { t = new char_token(sym.CH,'\b'); break; } case 'r': { t = new char_token(sym.CH,'\r'); break; } case 'f': { t = new char_token(sym.CH,'\f'); break; } case 'a': { t = new char_token(sym.CH,'\007'); break; } case '\\': { t = new char_token(sym.CH,'\\'); break; } case '?': { t = new char_token(sym.CH,'?'); break; } case '0': { t = new char_token(sym.CH,'\0'); break; } case '\'': { t = new char_token(sym.CH,'\''); break; } case '\"': { t = new char_token(sym.CH,'\"'); break; } default: { emit_error("Invalid escape symbol \'"); return null; } } } } else { t = new char_token(sym.CH,(char)next_char); } advance(); if( (char)next_char == '\'' ) { tokenStack.push( new token(sym.QUOTE)); tokenStack.push(t); advance(); } else { emit_error("Expecting closing \'"); return null; } wide = false; return new token(sym.QUOTE); } if (sym_num != -1) { /* found one -- advance past it and return a token for it */ advance(); return new token(sym_num); } /* look for an id or keyword */ if ( id_start_char(next_char) ) { token t = do_symbol(); if( t != null ) return t; else continue; } /* look for EOF */ if (next_char == EOF_CHAR) { return new token(sym.EOF); } } else // in_string { /* empty string ? */ if( (char)next_char == '\"' ) { in_string = false; advance(); return new token(sym.DBLQUOTE); // return new org.jacorb.idl.str_token(sym.ID, "", getPosition()); } StringBuffer result = new StringBuffer(); char previous = ' '; /* collect up characters while they fit in id */ while(true) { if (next_char == '\\') { // Remap those characters that have no equivilant in java switch (next_char2) { case 'a': { result.append ("\\007"); previous = 'a'; advance(); break; } case 'v': { result.append ("\\013"); previous = 'v'; advance(); break; } case '?': { result.append ("?"); previous = '?'; advance(); break; } // Replace \xA0 by octal equivilant case 'x': { advance(); advance(); // Now next_char will be A and next_char2 will be 0 String octal = Integer.toOctalString ( Integer.parseInt ( new String ( new char [] { (char)next_char, (char)next_char2} ), 16 ) ); if (octal.length () != 3) { if (octal.length () == 1) { octal = "0" + octal; } octal = "0" + octal; } result.append ("\\" + octal); previous = (char)next_char2; advance(); break; } case 'u': { if (wide == false) { emit_error ("Unicode characters are only legal with wide strings"); return null; } else { result.append ((char)next_char); result.append ((char)next_char2); advance (); advance (); char uni1 = (char)next_char; char uni2 = '0'; char uni3 = '0'; char uni4 = '0'; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni2 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni3 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni4 = (char)next_char; } else { emit_error ("Illegal unicode character"); return null; } } else { emit_error ("Illegal unicode character"); return null; } } else { emit_error ("Illegal unicode character"); return null; } previous = uni4; result.append (uni1); result.append (uni2); result.append (uni3); result.append (uni4); } break; } default: { previous = (char)next_char; result.append ((char)next_char); } } } else { previous = (char)next_char; result.append ((char)next_char); } advance(); // Handle backslash quote but exit if just quote if (((char)next_char) == '\"'&& previous != '\\') { break; } } wide = false; // String s = checkIdentifier( result.toString() ); String s = result.toString(); /* build and return an id token with an attached string */ return new org.jacorb.idl.str_token(sym.ID, s , getPosition(), GlobalInputStream.currentFile().getName()); } /* if we get here, we have an unrecognized character */ emit_warn("Unrecognized character '" + new Character((char)next_char) + "'(" +next_char+ ") -- ignored"); /* advance past it */ advance(); } }
protected static token real_next_token() throws java.io.IOException { int sym_num; if( !tokenStack.empty()) return (token)tokenStack.pop(); for (;;) { if( !in_string ) { swallow_whitespace(); /* look for preprocessor directives */ if( (char)next_char == '#' ) { preprocess(); continue; } /* look for a comment */ if (next_char == '/' && (next_char2 == '*' || next_char2 == '/')) { /* swallow then continue the scan */ swallow_comment(); continue; } if( !conditionalCompilation ) { advance(); if( next_char == EOF_CHAR ) { emit_error("EOF in conditional compilation!", null); return null; } else continue; } /* look for COLON or DBLCOLON */ if (next_char == ':') { if (next_char2 == ':') { advance(); advance(); return new token(sym.DBLCOLON); } else { advance(); return new token(sym.COLON); } } /* leading L for wide strings */ if (next_char == 'L' && next_char2 == '\"') { advance(); advance(); wide = true; in_string = true; return new token(sym.LDBLQUOTE); } /* look for Shifts */ if (next_char == '<') { if (next_char2 == '<') { advance(); advance(); return new token(sym.LSHIFT); } else { advance(); return new token(sym.LESSTHAN); } } if (next_char == '>') { if (next_char2 == '>') { advance(); advance(); return new token(sym.RSHIFT); } else { advance(); return new token(sym.GREATERTHAN); } } /* leading 0: */ /* Try to scan octal/hexadecimal numbers, might even find a float */ if (next_char == '0') { long l_val = 0; long l_val_old = 0; int radix = 8; int digit = 0; advance(); if (next_char == '.') { StringBuffer f_string = new StringBuffer("0."); advance(); while( next_char >= '0' && next_char <= '9') { f_string.append( (char)next_char ); advance(); } float f_val = (new Float( f_string.toString() )).floatValue(); return new float_token(sym.FLOAT_NUMBER, f_val); } else { // See if hexadecimal value if (next_char == 'x' || next_char == 'X') { advance (); radix = 16; } StringBuffer val = new StringBuffer ("0"); digit = Character.digit ((char) next_char, radix); while (digit != -1 ) { val.append ((char) next_char); advance(); digit = Character.digit((char) next_char, radix); } String str = val.toString (); try { return new int_token (sym.NUMBER, Integer.parseInt (str, radix)); } catch (NumberFormatException ex) { try { return new long_token (sym.LONG_NUMBER, Long.parseLong (str, radix)); } catch (NumberFormatException ex2) { emit_error ("Invalid octal/hex value: " + str); } } return null; } } /* Try to scan integer, floating point or fixed point literals */ if ( (next_char >= '0' && next_char <= '9') || next_char == '.' ) { StringBuffer value = new StringBuffer(); StringBuffer fraction = null; int exp = 0; /* read integer part */ while (next_char >= '0' && next_char <= '9') { value.append( (char)next_char); // System.out.println("Read integer part " + value.toString()); advance(); } /* read fraction */ if( next_char == '.' ) { fraction = new StringBuffer(); advance(); // System.out.println("Reading fraction part"); while( next_char >= '0' && next_char <= '9') { fraction.append( (char)next_char ); advance(); } } if( next_char == 'e' || next_char == 'E' ) { // System.out.println("Reading exponent"); if( fraction == null ) fraction = new StringBuffer(); fraction.append('e'); advance(); if( next_char == '-' || next_char == '+') { fraction.append( (char)next_char ); advance(); } while( next_char >= '0' && next_char <= '9') { fraction.append( (char)next_char ); advance(); } if( fraction.length() == 1 ) { emit_error("Empty exponent in float/double."); continue; } return new float_token( sym.FLOAT_NUMBER, Float.valueOf( value.toString() + "." + fraction.toString()).floatValue()); } if( next_char == 'd' || next_char == 'D' ) { advance(); if( fraction == null ) fraction = new StringBuffer(); java.math.BigDecimal bi = new java.math.BigDecimal(value.toString() + "." + fraction.toString()); return new fixed_token(sym.FIXED_NUMBER, bi); } if (fraction == null) { /* integer or long */ token tok = null; String str = value.toString (); try { tok = new int_token (sym.NUMBER, Integer.parseInt (str)); } catch (NumberFormatException ex) { try { tok = new long_token (sym.LONG_NUMBER, Long.parseLong (str)); } catch (NumberFormatException ex2) { emit_error ("Invalid long value: " + str); } } return tok; } else { try { float f = Float.valueOf( value.toString() + "." + fraction.toString()).floatValue(); return new float_token(sym.FLOAT_NUMBER, f ); } catch( NumberFormatException nf ) { emit_error("Unexpected symbol: " + value.toString() + "." + fraction.toString()); } } } /* look for a single character symbol */ sym_num = find_single_char(next_char); if( (char)next_char == '\"' ) { in_string = true; advance(); return new token(sym.DBLQUOTE); } if( (char)next_char == '\'' ) { advance(); token t = null; if (next_char == '\\') { // Now need to process escaped character. advance(); if (isDigit ((char)next_char)) { // Octal character char octal1 = '0'; char octal2 = '0'; char octal3 = (char)next_char; if (isDigit ((char)next_char2)) { advance (); octal2 = octal3; octal3 = (char)next_char; if (isDigit ((char)next_char2)) { advance (); octal1 = octal2; octal2 = octal3; octal3 = (char)next_char; } } t= new char_token ( sym.CH, (char)Integer.parseInt (new String (new char [] {octal1, octal2, octal3}), 8 ) ); } else if ((char)next_char == 'x') { // Hexadecimal character advance (); char hex1 = '0'; char hex2 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); hex1 = hex2; hex2 = (char)next_char; } else if ((char)next_char2 != '\'') { emit_error ("Illegal hex character"); return null; } t= new char_token ( sym.CH, (char)Integer.parseInt (new String (new char [] {hex1, hex2}), 16 ) ); } else if ((char)next_char == 'u') { if (wide == false) { emit_error ("Unicode characters are only legal with wide character"); return null; } else { // Hexadecimal character advance (); char uni1 = '0'; char uni2 = '0'; char uni3 = '0'; char uni4 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni3 = uni4; uni4 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni2 = uni3; uni3 = uni4; uni4 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni1 = uni2; uni2 = uni3; uni3 = uni4; uni4 = (char)next_char; } else if ((char)next_char2 != '\'') { emit_error ("Illegal unicode character"); return null; } } else if ((char)next_char2 != '\'') { emit_error ("Illegal unicode character"); return null; } } else if ((char)next_char2 != '\'') { emit_error ("Illegal unicode character"); return null; } t= new char_token ( sym.CH, (char)Integer.parseInt (new String (new char [] {uni1, uni2, uni3, uni4}), 16 ) ); } } else { switch (next_char) { case 'n': { t = new char_token(sym.CH,'\n'); break; } case 't': { t = new char_token(sym.CH,'\t'); break; } case 'v': { t = new char_token(sym.CH,'\013'); break; } case 'b': { t = new char_token(sym.CH,'\b'); break; } case 'r': { t = new char_token(sym.CH,'\r'); break; } case 'f': { t = new char_token(sym.CH,'\f'); break; } case 'a': { t = new char_token(sym.CH,'\007'); break; } case '\\': { t = new char_token(sym.CH,'\\'); break; } case '?': { t = new char_token(sym.CH,'?'); break; } case '0': { t = new char_token(sym.CH,'\0'); break; } case '\'': { t = new char_token(sym.CH,'\''); break; } case '\"': { t = new char_token(sym.CH,'\"'); break; } default: { emit_error("Invalid escape symbol \'"); return null; } } } } else { t = new char_token(sym.CH,(char)next_char); } advance(); if( (char)next_char == '\'' ) { tokenStack.push( new token(sym.QUOTE)); tokenStack.push(t); advance(); } else { emit_error("Expecting closing \'"); return null; } wide = false; return new token(sym.QUOTE); } if (sym_num != -1) { /* found one -- advance past it and return a token for it */ advance(); return new token(sym_num); } /* look for an id or keyword */ if ( id_start_char(next_char) ) { token t = do_symbol(); if( t != null ) return t; else continue; } /* look for EOF */ if (next_char == EOF_CHAR) { return new token(sym.EOF); } } else // in_string { /* empty string ? */ if( (char)next_char == '\"' ) { in_string = false; advance(); return new token(sym.DBLQUOTE); // return new org.jacorb.idl.str_token(sym.ID, "", getPosition()); } StringBuffer result = new StringBuffer(); char previous = ' '; /* collect up characters while they fit in id */ while(true) { if (next_char == '\\') { // Remap those characters that have no equivilant in java switch (next_char2) { case 'a': { result.append ("\\007"); previous = 'a'; advance(); break; } case 'v': { result.append ("\\013"); previous = 'v'; advance(); break; } case '?': { result.append ("?"); previous = '?'; advance(); break; } // Replace \xA0 by octal equivilant case 'x': { advance(); advance(); // Now next_char will be A and next_char2 will be 0 String octal = Integer.toOctalString ( Integer.parseInt ( new String ( new char [] { (char)next_char, (char)next_char2} ), 16 ) ); if (octal.length () != 3) { if (octal.length () == 1) { octal = "0" + octal; } octal = "0" + octal; } result.append ("\\" + octal); previous = (char)next_char2; advance(); break; } case 'u': { if (wide == false) { emit_error ("Unicode characters are only legal with wide strings"); return null; } else { result.append ((char)next_char); result.append ((char)next_char2); advance (); advance (); char uni1 = (char)next_char; char uni2 = '0'; char uni3 = '0'; char uni4 = '0'; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni2 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni3 = (char)next_char; if (isHexLetterOrDigit ((char)next_char2)) { advance (); uni4 = (char)next_char; } else { emit_error ("Illegal unicode character"); return null; } } else { emit_error ("Illegal unicode character"); return null; } } else { emit_error ("Illegal unicode character"); return null; } previous = uni4; result.append (uni1); result.append (uni2); result.append (uni3); result.append (uni4); } break; } default: { previous = (char)next_char; result.append ((char)next_char); } } } else { previous = (char)next_char; result.append ((char)next_char); } advance(); // Handle backslash quote but exit if just quote if (((char)next_char) == '\"'&& previous != '\\') { break; } } wide = false; // String s = checkIdentifier( result.toString() ); String s = result.toString(); /* build and return an id token with an attached string */ return new org.jacorb.idl.str_token(sym.ID, s , getPosition(), GlobalInputStream.currentFile().getName()); } /* if we get here, we have an unrecognized character */ emit_warn("Unrecognized character '" + new Character((char)next_char) + "'(" +next_char+ ") -- ignored"); /* advance past it */ advance(); } }
diff --git a/src/klim/orthodox_calendar/Day.java b/src/klim/orthodox_calendar/Day.java index 508bfdf..2d9bc71 100755 --- a/src/klim/orthodox_calendar/Day.java +++ b/src/klim/orthodox_calendar/Day.java @@ -1,257 +1,257 @@ package klim.orthodox_calendar; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Date; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PrimaryKey; import com.google.appengine.api.datastore.Text; @PersistenceCapable(identityType = IdentityType.APPLICATION) public class Day { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private Date dayToParse; @Persistent private Date pubDate; public void setPubDate(Date pubDate) { this.pubDate = pubDate; } public Date getPubDate() { return pubDate; } public Date getDayToParse() { return dayToParse; } public void setDayToParse(Date dayToParse) { this.dayToParse = dayToParse; initAllFields(); } @NotPersistent private Calendar calendarDay; @NotPersistent private Calendar calendarNewDay; @NotPersistent private String title; @NotPersistent private String link; @NotPersistent private String comments; @Persistent private Text description; public Long getId() { return id; } public String getDescription() { return getDescription(false); } public String getDescription(boolean env) { if (env) return escapeHtml(description.getValue()); return description.getValue(); } public void setDescription(Text description) { this.description = description; } @NotPersistent private SimpleDateFormat c; @NotPersistent private SimpleDateFormat c1; @NotPersistent private SimpleDateFormat c2; @NotPersistent private Boolean isInitialized; public Day(Date day) { dayToParse = Day.cutDate(day); initAllFields(); description = new Text(parseDay(day)); this.pubDate = new Date(); } private void initAllFields() { if (this.isInitialized == null || !isInitialized.booleanValue()) { this.c=new SimpleDateFormat("MMMdd", new DateFormatSymbols(new java.util.Locale("en"))); this.c1=new SimpleDateFormat("d MMMM", new DateFormatSymbols(new java.util.Locale("ru"))); this.c2=new SimpleDateFormat("d MMMM '20'yy EEEE", new DateFormatSymbols(new java.util.Locale("ru"))); this.calendarNewDay = new GregorianCalendar(); this.calendarNewDay.setTime(dayToParse); this.calendarDay = new GregorianCalendar(); this.calendarDay.setTime(dayToParse); this.calendarDay.add(Calendar.DATE, -13); this.isInitialized=new Boolean(true); } } public String getLink() { if (this.link == null) { this.initAllFields(); this.link = "http://calendar.rop.ru/mes1/" + c.format(this.calendarDay.getTime()).toLowerCase() + ".html"; } return this.link; } public String getTitle() { if (this.title == null) { this.initAllFields(); this.title = this.c1.format( this.calendarDay.getTime()) + " / " +this.c2.format(this.calendarNewDay.getTime()); } return this.title; } public String getComments() { if (this.comments == null) { this.initAllFields(); this.comments = getLink(); } return this.comments; } public String parseDay() { return parseDay(new Date()); } public String parseDay(Date day) { String ret=new String(); setCalendarDay(day); try { this.setCalendarDay(day); String toOpen="http://calendar.rop.ru/mes1/" + c.format(getCalendarDay().getTime()).toLowerCase() + ".html"; URL url = new URL(toOpen); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); ret=""; InputStream is = connection.getInputStream(); ret += toString(is); - Pattern p=Pattern.compile("(<div[^>]*id=.block.*)<img src=\"img/line1.gif\"", Pattern.DOTALL); + Pattern p=Pattern.compile("(<div[^>]*id=.block.*)<img .*?src=\"img/line.gif\"", Pattern.DOTALL); Matcher m=p.matcher(ret); if ( m.find() ) { ret = m.group(1); ret += "</div>"; Pattern p1 = Pattern.compile("href=\"([^\"]*)\"", Pattern.DOTALL); Matcher matcher = p1.matcher(ret); StringBuffer buf = new StringBuffer(); while (matcher.find()) { String replaceStr = "href=\"http://calendar.rop.ru/mes1/" + matcher.group(1) + "\""; matcher.appendReplacement(buf, replaceStr); } matcher.appendTail(buf); ret=buf.toString(); } else ret = ""; description = new Text(ret); } catch (MalformedURLException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } return ret; } public Calendar getCalendarDay() { return this.calendarDay; } public void setCalendarDay(Date calendarDay) { Calendar tmp = new GregorianCalendar(); tmp.setTime(calendarDay); setCalendarDay(tmp); } public void setCalendarDay(Calendar calendarDay) { this.calendarNewDay = calendarDay; this.calendarDay = new GregorianCalendar(); this.calendarDay.setTime(calendarDay.getTime()); this.calendarDay.add(Calendar.DATE, -13); this.title=null; this.link=null; this.comments=null; this.description=new Text(""); } private String escapeHtml(String html) { if (html == null) { return null; } return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;") .replaceAll(">", "&gt;"); } private String toString(InputStream inputStream) throws IOException { String string; StringBuilder outputBuilder = new StringBuilder(); if (inputStream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"windows-1251"/*"UTF8"*/)); while (null != (string = reader.readLine())) { outputBuilder.append(string).append('\n'); } } return outputBuilder.toString(); } public static final Date cutDate(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); return c.getTime(); } }
true
true
public String parseDay(Date day) { String ret=new String(); setCalendarDay(day); try { this.setCalendarDay(day); String toOpen="http://calendar.rop.ru/mes1/" + c.format(getCalendarDay().getTime()).toLowerCase() + ".html"; URL url = new URL(toOpen); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); ret=""; InputStream is = connection.getInputStream(); ret += toString(is); Pattern p=Pattern.compile("(<div[^>]*id=.block.*)<img src=\"img/line1.gif\"", Pattern.DOTALL); Matcher m=p.matcher(ret); if ( m.find() ) { ret = m.group(1); ret += "</div>"; Pattern p1 = Pattern.compile("href=\"([^\"]*)\"", Pattern.DOTALL); Matcher matcher = p1.matcher(ret); StringBuffer buf = new StringBuffer(); while (matcher.find()) { String replaceStr = "href=\"http://calendar.rop.ru/mes1/" + matcher.group(1) + "\""; matcher.appendReplacement(buf, replaceStr); } matcher.appendTail(buf); ret=buf.toString(); } else ret = ""; description = new Text(ret); } catch (MalformedURLException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } return ret; }
public String parseDay(Date day) { String ret=new String(); setCalendarDay(day); try { this.setCalendarDay(day); String toOpen="http://calendar.rop.ru/mes1/" + c.format(getCalendarDay().getTime()).toLowerCase() + ".html"; URL url = new URL(toOpen); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); ret=""; InputStream is = connection.getInputStream(); ret += toString(is); Pattern p=Pattern.compile("(<div[^>]*id=.block.*)<img .*?src=\"img/line.gif\"", Pattern.DOTALL); Matcher m=p.matcher(ret); if ( m.find() ) { ret = m.group(1); ret += "</div>"; Pattern p1 = Pattern.compile("href=\"([^\"]*)\"", Pattern.DOTALL); Matcher matcher = p1.matcher(ret); StringBuffer buf = new StringBuffer(); while (matcher.find()) { String replaceStr = "href=\"http://calendar.rop.ru/mes1/" + matcher.group(1) + "\""; matcher.appendReplacement(buf, replaceStr); } matcher.appendTail(buf); ret=buf.toString(); } else ret = ""; description = new Text(ret); } catch (MalformedURLException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } return ret; }
diff --git a/rdt/org.eclipse.ptp.rdt.sync.core/src/org/eclipse/ptp/rdt/sync/core/remotemake/SyncCommandLauncher.java b/rdt/org.eclipse.ptp.rdt.sync.core/src/org/eclipse/ptp/rdt/sync/core/remotemake/SyncCommandLauncher.java index 4cf3acb2c..5e42a96d3 100644 --- a/rdt/org.eclipse.ptp.rdt.sync.core/src/org/eclipse/ptp/rdt/sync/core/remotemake/SyncCommandLauncher.java +++ b/rdt/org.eclipse.ptp.rdt.sync.core/src/org/eclipse/ptp/rdt/sync/core/remotemake/SyncCommandLauncher.java @@ -1,517 +1,517 @@ /******************************************************************************* * Copyright (c) 2009, 2010, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Jeff Overbey (Illinois) - Environment management support *******************************************************************************/ package org.eclipse.ptp.rdt.sync.core.remotemake; import java.io.IOException; import java.io.OutputStream; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.managedbuilder.core.IBuilder; import org.eclipse.cdt.managedbuilder.core.IConfiguration; import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.ptp.ems.core.EnvManagerRegistry; import org.eclipse.ptp.ems.core.EnvManagerProjectProperties; import org.eclipse.ptp.ems.core.IEnvManager; import org.eclipse.ptp.internal.rdt.core.index.IndexBuildSequenceController; import org.eclipse.ptp.internal.rdt.core.remotemake.RemoteProcessClosure; import org.eclipse.ptp.rdt.sync.core.BuildConfigurationManager; import org.eclipse.ptp.rdt.sync.core.BuildScenario; import org.eclipse.ptp.rdt.sync.core.MissingConnectionException; import org.eclipse.ptp.rdt.sync.core.RDTSyncCorePlugin; import org.eclipse.ptp.rdt.sync.core.SyncFlag; import org.eclipse.ptp.rdt.sync.core.SyncManager; import org.eclipse.ptp.remote.core.IRemoteConnection; import org.eclipse.ptp.remote.core.IRemoteFileManager; import org.eclipse.ptp.remote.core.IRemoteProcess; import org.eclipse.ptp.remote.core.IRemoteProcessBuilder; import org.eclipse.ptp.remote.core.IRemoteServices; import org.eclipse.ptp.remote.core.RemoteProcessAdapter; import org.eclipse.ptp.remote.core.exception.RemoteConnectionException; /** * <strong>EXPERIMENTAL</strong>. This class or interface has been added as part of a work in progress. There is no guarantee that * this API will work or that it will remain the same. Please do not use this API without consulting with the RDT team. * * @author crecoskie * @author Jeff Overbey */ // TODO (Jeff): Remove/replace NON_ESCAPED_ASCII_CHARS, static initializer, and escape(String) after Bug 371691 is fixed public class SyncCommandLauncher implements ICommandLauncher { /** ASCII characters that do <i>not</i> need to be escaped on a Bash command line */ private static final Set<Character> NON_ESCAPED_ASCII_CHARS; static { NON_ESCAPED_ASCII_CHARS = new HashSet<Character>(); CharacterIterator it = new StringCharacterIterator("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/._-"); //$NON-NLS-1$ for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) { NON_ESCAPED_ASCII_CHARS.add(c); } } protected IProject fProject; protected Process fProcess; protected IRemoteProcess fRemoteProcess; protected boolean fShowCommand; protected String[] fCommandArgs; protected String lineSeparator = "\r\n"; //$NON-NLS-1$ protected String fErrorMessage; protected Map<String, String> remoteEnvMap; private boolean isCleanBuild; /** * The number of milliseconds to pause between polling. */ protected static final long DELAY = 50L; /** * */ public SyncCommandLauncher() { } private boolean isCleanBuild(String[] args) { for (int i = 0; i < args.length; i++) { if (IBuilder.DEFAULT_TARGET_CLEAN.equals(args[i])) { return true; } } return false; } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.ICommandLauncher#execute(org.eclipse.core.runtime.IPath, java.lang.String[], java.lang.String[], * org.eclipse.core.runtime.IPath) */ @Override public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, final IProgressMonitor monitor) throws CoreException { isCleanBuild = isCleanBuild(args); IndexBuildSequenceController projectStatus = IndexBuildSequenceController.getIndexBuildSequenceController(getProject()); if (projectStatus != null) { projectStatus.setRuntimeBuildStatus(null); } // if there is no project associated to us then we cannot function... throw an exception if (getProject() == null) { throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "RemoteCommandLauncher has not been associated with a project.")); //$NON-NLS-1$ //$NON-NLS-2$ } // Set correct directory // For managed projects and configurations other than workspace, the directory is incorrect and needs to be fixed. IConfiguration configuration = ManagedBuildManager.getBuildInfo(getProject()).getDefaultConfiguration(); String projectLocalRoot = getProject().getLocation().toPortableString(); String projectActualRoot = BuildConfigurationManager.getInstance().getBuildScenarioForBuildConfiguration(configuration) .getLocation(getProject()); changeToDirectory = new Path(changeToDirectory.toString().replaceFirst(projectLocalRoot, projectActualRoot)); fCommandArgs = constructCommandArray(commandPath.toPortableString(), args); // Get and setup the connection and remote services for this build configuration. BuildScenario bs = BuildConfigurationManager.getInstance().getBuildScenarioForBuildConfiguration(configuration); if (bs == null) { return null; } IRemoteConnection connection; try { connection = bs.getRemoteConnection(); } catch (MissingConnectionException e2) { throw new CoreException(new Status(IStatus.CANCEL, "org.eclipse.ptp.rdt.sync.core", "Build canceled because connection does not exist")); //$NON-NLS-1$ //$NON-NLS-2$ } if (!connection.isOpen()) { try { connection.open(monitor); } catch (RemoteConnectionException e1) { // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "Error opening connection.", e1)); //$NON-NLS-1$ //$NON-NLS-2$ } } IRemoteServices remoteServices = connection.getRemoteServices(); if (remoteServices == null) { return null; } if (!remoteServices.isInitialized()) { remoteServices.initialize(); } // Set process's command and environment List<String> command = constructCommand(commandPath, args, connection, monitor); IRemoteProcessBuilder processBuilder = remoteServices.getProcessBuilder(connection, command); remoteEnvMap = processBuilder.environment(); for (String envVar : env) { - String[] splitStr = envVar.split("="); //$NON-NLS-1$ + String[] splitStr = envVar.split("=", 2); //$NON-NLS-1$ if (splitStr.length > 1) { remoteEnvMap.put(splitStr[0], splitStr[1]); } else if (splitStr.length == 1) { // Empty environment variable remoteEnvMap.put(splitStr[0], ""); //$NON-NLS-1$ } } // set the directory in which to run the command IRemoteFileManager fileManager = remoteServices.getFileManager(connection); if (changeToDirectory != null && fileManager != null) { processBuilder.directory(fileManager.getResource(changeToDirectory.toString())); } // Synchronize before building SyncManager.syncBlocking(null, getProject(), SyncFlag.FORCE, new SubProgressMonitor(monitor, 10), null); IRemoteProcess p = null; try { p = processBuilder.start(); } catch (IOException e) { if (projectStatus != null) { projectStatus.setRuntimeBuildStatus(IndexBuildSequenceController.STATUS_INCOMPLETE); } // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.sync.core", "Error launching remote process.", e)); //$NON-NLS-1$ //$NON-NLS-2$ } if (projectStatus != null) { if (!isCleanBuild) { projectStatus.setBuildRunning(); } } fRemoteProcess = p; fProcess = new RemoteProcessAdapter(p); return fProcess; } private List<String> constructCommand(IPath commandPath, String[] args, IRemoteConnection connection, IProgressMonitor monitor) throws CoreException { /* * Prior to Modules/SoftEnv support, this was the following: * * List<String> command = new LinkedList<String>(); * command.add(commandPath.toString()); * for (int k = 0; k < args.length; k++) { * command.add(args[k]); * } */ final EnvManagerProjectProperties projectProperties = new EnvManagerProjectProperties(getProject()); if (projectProperties.isEnvMgmtEnabled()) { // Environment management is enabled for the build. Issue custom Modules/SoftEnv commands to configure the environment. IEnvManager envManager = EnvManagerRegistry.getEnvManager(monitor, connection); try { // Create and execute a Bash script which will configure the environment and then execute the command final List<String> command = new LinkedList<String>(); command.add("bash"); //$NON-NLS-1$ command.add("-l"); //$NON-NLS-1$ final String bashScriptFilename = envManager.createBashScript(monitor, true, projectProperties, getCommandAsString(commandPath, args)); command.add(bashScriptFilename); return command; } catch (final Exception e) { // An error occurred creating the Bash script, so attempt to put the whole thing onto the command line RDTSyncCorePlugin.log("Error creating bash script for launch; reverting to bash -l -c", e); //$NON-NLS-1$ final List<String> command = new LinkedList<String>(); command.add("bash"); //$NON-NLS-1$ command.add("-l"); //$NON-NLS-1$ command.add("-c"); //$NON-NLS-1$ final String bashCommand = envManager.getBashConcatenation("; ", true, projectProperties, getCommandAsString(commandPath, args)); //$NON-NLS-1$ command.add(bashCommand); return command; } } else { // Environment management disabled. Execute the build command in a login shell (so the default environment is configured). final List<String> command = new LinkedList<String>(); command.add("bash"); //$NON-NLS-1$ command.add("-l"); //$NON-NLS-1$ command.add("-c"); //$NON-NLS-1$ command.add(getCommandAsString(commandPath, args)); return command; } } private static String getCommandAsString(IPath commandPath, String[] args) { final StringBuilder sb = new StringBuilder(); sb.append(escape(commandPath.toOSString())); sb.append(' '); for (int k = 0; k < args.length; k++) { sb.append(escape(args[k])); sb.append(' '); } return sb.toString(); } // See RemoteToolsProcessBuilder ctor and #charEscapify(String, Set<String>) private static String escape(String inputString) { if (inputString == null) { return null; } final StringBuilder newString = new StringBuilder(inputString.length()+16); final CharacterIterator it = new StringCharacterIterator(inputString); for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) { if (c == '\'') { newString.append("'\\\\\\''"); //$NON-NLS-1$ } else if (c > 127 || NON_ESCAPED_ASCII_CHARS.contains(c)) { // Do not escape non-ASCII characters (> 127) newString.append(c); } else { newString.append("\\" + c); //$NON-NLS-1$ } } return newString.toString(); } private String getCommandLine(String[] commandArgs) { if (fProject == null) { return null; } StringBuffer buf = new StringBuffer(); if (fCommandArgs != null) { for (String commandArg : commandArgs) { buf.append(commandArg); buf.append(' '); } buf.append(lineSeparator); } return buf.toString(); } /** * Constructs a command array that will be passed to the process */ protected String[] constructCommandArray(String command, String[] commandArgs) { String[] args = new String[1 + commandArgs.length]; args[0] = command; System.arraycopy(commandArgs, 0, args, 1, commandArgs.length); return args; } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.ICommandLauncher#getCommandLine() */ @Override public String getCommandLine() { return getCommandLine(getCommandArgs()); } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.ICommandLauncher#getCommandArgs() */ @Override public String[] getCommandArgs() { return fCommandArgs; } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.ICommandLauncher#getEnvironment() */ @Override public Properties getEnvironment() { return convertEnvMapToProperties(); } private Properties convertEnvMapToProperties() { Properties properties = new Properties(); for (String key : remoteEnvMap.keySet()) { properties.put(key, remoteEnvMap.get(key)); } return properties; } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.ICommandLauncher#getErrorMessage() */ @Override public String getErrorMessage() { return fErrorMessage; } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.ICommandLauncher#setErrorMessage(java.lang.String) */ @Override public void setErrorMessage(String error) { fErrorMessage = error; } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.ICommandLauncher#showCommand(boolean) */ @Override public void showCommand(boolean show) { fShowCommand = show; } protected void printCommandLine(OutputStream os) { if (os != null) { String cmd = getCommandLine(getCommandArgs()); try { os.write(cmd.getBytes()); os.flush(); } catch (IOException e) { // ignore; } } } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.ICommandLauncher#waitAndRead(java.io.OutputStream, java.io.OutputStream) */ @Override public int waitAndRead(OutputStream out, OutputStream err) { if (fShowCommand) { printCommandLine(out); } if (fProcess == null) { return ILLEGAL_COMMAND; } RemoteProcessClosure closure = new RemoteProcessClosure(fRemoteProcess, out, err); closure.runBlocking(); // a blocking call return OK; } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.ICommandLauncher#waitAndRead(java.io.OutputStream, java.io.OutputStream, * org.eclipse.core.runtime.IProgressMonitor) */ @Override public int waitAndRead(OutputStream output, OutputStream err, IProgressMonitor monitor) { if (fShowCommand) { printCommandLine(output); } if (fProcess == null) { return ILLEGAL_COMMAND; } RemoteProcessClosure closure = new RemoteProcessClosure(fRemoteProcess, output, err); closure.runNonBlocking(); while (!monitor.isCanceled() && closure.isRunning()) { try { Thread.sleep(DELAY); } catch (InterruptedException ie) { // ignore } } // Poorly named function - actually closes streams and resets variables closure.isAlive(); int state = OK; final IndexBuildSequenceController projectStatus = IndexBuildSequenceController .getIndexBuildSequenceController(getProject()); // Operation canceled by the user, terminate abnormally. if (monitor.isCanceled()) { closure.terminate(); state = COMMAND_CANCELED; setErrorMessage(CCorePlugin.getResourceString("CommandLauncher.error.commandCanceled")); //$NON-NLS-1$ if (projectStatus != null) { projectStatus.setRuntimeBuildStatus(IndexBuildSequenceController.STATUS_INCOMPLETE); } } try { fProcess.waitFor(); } catch (InterruptedException e) { // ignore } try { // Do not allow the cancel of the refresh, since the // builder is external // to Eclipse, files may have been created/modified // and we will be out-of-sync. // The caveat is that for huge projects, it may take a while getProject().refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { // this should never happen because we should never be building from a // state where ressource changes are disallowed } if (projectStatus != null) { if (isCleanBuild) { projectStatus.setBuildInCompletedForCleanBuild(); } else { if (projectStatus.isIndexAfterBuildSet()) { projectStatus.invokeIndex(); } else { projectStatus.setFinalBuildStatus(); } } } return state; } @Override public IProject getProject() { return fProject; } @Override public void setProject(IProject project) { fProject = project; } }
true
true
public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, final IProgressMonitor monitor) throws CoreException { isCleanBuild = isCleanBuild(args); IndexBuildSequenceController projectStatus = IndexBuildSequenceController.getIndexBuildSequenceController(getProject()); if (projectStatus != null) { projectStatus.setRuntimeBuildStatus(null); } // if there is no project associated to us then we cannot function... throw an exception if (getProject() == null) { throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "RemoteCommandLauncher has not been associated with a project.")); //$NON-NLS-1$ //$NON-NLS-2$ } // Set correct directory // For managed projects and configurations other than workspace, the directory is incorrect and needs to be fixed. IConfiguration configuration = ManagedBuildManager.getBuildInfo(getProject()).getDefaultConfiguration(); String projectLocalRoot = getProject().getLocation().toPortableString(); String projectActualRoot = BuildConfigurationManager.getInstance().getBuildScenarioForBuildConfiguration(configuration) .getLocation(getProject()); changeToDirectory = new Path(changeToDirectory.toString().replaceFirst(projectLocalRoot, projectActualRoot)); fCommandArgs = constructCommandArray(commandPath.toPortableString(), args); // Get and setup the connection and remote services for this build configuration. BuildScenario bs = BuildConfigurationManager.getInstance().getBuildScenarioForBuildConfiguration(configuration); if (bs == null) { return null; } IRemoteConnection connection; try { connection = bs.getRemoteConnection(); } catch (MissingConnectionException e2) { throw new CoreException(new Status(IStatus.CANCEL, "org.eclipse.ptp.rdt.sync.core", "Build canceled because connection does not exist")); //$NON-NLS-1$ //$NON-NLS-2$ } if (!connection.isOpen()) { try { connection.open(monitor); } catch (RemoteConnectionException e1) { // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "Error opening connection.", e1)); //$NON-NLS-1$ //$NON-NLS-2$ } } IRemoteServices remoteServices = connection.getRemoteServices(); if (remoteServices == null) { return null; } if (!remoteServices.isInitialized()) { remoteServices.initialize(); } // Set process's command and environment List<String> command = constructCommand(commandPath, args, connection, monitor); IRemoteProcessBuilder processBuilder = remoteServices.getProcessBuilder(connection, command); remoteEnvMap = processBuilder.environment(); for (String envVar : env) { String[] splitStr = envVar.split("="); //$NON-NLS-1$ if (splitStr.length > 1) { remoteEnvMap.put(splitStr[0], splitStr[1]); } else if (splitStr.length == 1) { // Empty environment variable remoteEnvMap.put(splitStr[0], ""); //$NON-NLS-1$ } } // set the directory in which to run the command IRemoteFileManager fileManager = remoteServices.getFileManager(connection); if (changeToDirectory != null && fileManager != null) { processBuilder.directory(fileManager.getResource(changeToDirectory.toString())); } // Synchronize before building SyncManager.syncBlocking(null, getProject(), SyncFlag.FORCE, new SubProgressMonitor(monitor, 10), null); IRemoteProcess p = null; try { p = processBuilder.start(); } catch (IOException e) { if (projectStatus != null) { projectStatus.setRuntimeBuildStatus(IndexBuildSequenceController.STATUS_INCOMPLETE); } // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.sync.core", "Error launching remote process.", e)); //$NON-NLS-1$ //$NON-NLS-2$ } if (projectStatus != null) { if (!isCleanBuild) { projectStatus.setBuildRunning(); } } fRemoteProcess = p; fProcess = new RemoteProcessAdapter(p); return fProcess; }
public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, final IProgressMonitor monitor) throws CoreException { isCleanBuild = isCleanBuild(args); IndexBuildSequenceController projectStatus = IndexBuildSequenceController.getIndexBuildSequenceController(getProject()); if (projectStatus != null) { projectStatus.setRuntimeBuildStatus(null); } // if there is no project associated to us then we cannot function... throw an exception if (getProject() == null) { throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "RemoteCommandLauncher has not been associated with a project.")); //$NON-NLS-1$ //$NON-NLS-2$ } // Set correct directory // For managed projects and configurations other than workspace, the directory is incorrect and needs to be fixed. IConfiguration configuration = ManagedBuildManager.getBuildInfo(getProject()).getDefaultConfiguration(); String projectLocalRoot = getProject().getLocation().toPortableString(); String projectActualRoot = BuildConfigurationManager.getInstance().getBuildScenarioForBuildConfiguration(configuration) .getLocation(getProject()); changeToDirectory = new Path(changeToDirectory.toString().replaceFirst(projectLocalRoot, projectActualRoot)); fCommandArgs = constructCommandArray(commandPath.toPortableString(), args); // Get and setup the connection and remote services for this build configuration. BuildScenario bs = BuildConfigurationManager.getInstance().getBuildScenarioForBuildConfiguration(configuration); if (bs == null) { return null; } IRemoteConnection connection; try { connection = bs.getRemoteConnection(); } catch (MissingConnectionException e2) { throw new CoreException(new Status(IStatus.CANCEL, "org.eclipse.ptp.rdt.sync.core", "Build canceled because connection does not exist")); //$NON-NLS-1$ //$NON-NLS-2$ } if (!connection.isOpen()) { try { connection.open(monitor); } catch (RemoteConnectionException e1) { // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "Error opening connection.", e1)); //$NON-NLS-1$ //$NON-NLS-2$ } } IRemoteServices remoteServices = connection.getRemoteServices(); if (remoteServices == null) { return null; } if (!remoteServices.isInitialized()) { remoteServices.initialize(); } // Set process's command and environment List<String> command = constructCommand(commandPath, args, connection, monitor); IRemoteProcessBuilder processBuilder = remoteServices.getProcessBuilder(connection, command); remoteEnvMap = processBuilder.environment(); for (String envVar : env) { String[] splitStr = envVar.split("=", 2); //$NON-NLS-1$ if (splitStr.length > 1) { remoteEnvMap.put(splitStr[0], splitStr[1]); } else if (splitStr.length == 1) { // Empty environment variable remoteEnvMap.put(splitStr[0], ""); //$NON-NLS-1$ } } // set the directory in which to run the command IRemoteFileManager fileManager = remoteServices.getFileManager(connection); if (changeToDirectory != null && fileManager != null) { processBuilder.directory(fileManager.getResource(changeToDirectory.toString())); } // Synchronize before building SyncManager.syncBlocking(null, getProject(), SyncFlag.FORCE, new SubProgressMonitor(monitor, 10), null); IRemoteProcess p = null; try { p = processBuilder.start(); } catch (IOException e) { if (projectStatus != null) { projectStatus.setRuntimeBuildStatus(IndexBuildSequenceController.STATUS_INCOMPLETE); } // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.sync.core", "Error launching remote process.", e)); //$NON-NLS-1$ //$NON-NLS-2$ } if (projectStatus != null) { if (!isCleanBuild) { projectStatus.setBuildRunning(); } } fRemoteProcess = p; fProcess = new RemoteProcessAdapter(p); return fProcess; }
diff --git a/community/web2/core/src/test/java/org/geoserver/web/wicket/EnvelopePanelTest.java b/community/web2/core/src/test/java/org/geoserver/web/wicket/EnvelopePanelTest.java index 0fbae959a..ad60f93b5 100644 --- a/community/web2/core/src/test/java/org/geoserver/web/wicket/EnvelopePanelTest.java +++ b/community/web2/core/src/test/java/org/geoserver/web/wicket/EnvelopePanelTest.java @@ -1,51 +1,51 @@ package org.geoserver.web.wicket; import org.apache.wicket.Component; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.util.tester.FormTester; import org.geoserver.web.FormTestPage; import org.geoserver.web.GeoServerWicketTestSupport; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.crs.DefaultGeographicCRS; import com.vividsolutions.jts.geom.Envelope; public class EnvelopePanelTest extends GeoServerWicketTestSupport { ReferencedEnvelope e; @Override protected void setUpInternal() throws Exception { super.setUpInternal(); e = new ReferencedEnvelope(-180,180,-90,90, DefaultGeographicCRS.WGS84); tester.startPage(new FormTestPage(new FormTestPage.ComponentBuilder() { public Component buildComponent(String id) { return new EnvelopePanel(id, e); } })); } public void test() throws Exception { tester.assertComponent( "form", Form.class ); FormTester ft = tester.newFormTester( "form"); - assertEquals( "-180", ft.getTextComponentValue( "content:minX") ); - assertEquals( "-90", ft.getTextComponentValue( "content:minY") ); - assertEquals( "180", ft.getTextComponentValue( "content:maxX") ); - assertEquals( "90", ft.getTextComponentValue( "content:maxY") ); + assertEquals( "-180", ft.getTextComponentValue( "panel:minX") ); + assertEquals( "-90", ft.getTextComponentValue( "panel:minY") ); + assertEquals( "180", ft.getTextComponentValue( "panel:maxX") ); + assertEquals( "90", ft.getTextComponentValue( "panel:maxY") ); - EnvelopePanel ep = (EnvelopePanel) tester.getComponentFromLastRenderedPage("form:content"); + EnvelopePanel ep = (EnvelopePanel) tester.getComponentFromLastRenderedPage("form:panel"); assertEquals( e, ep.getModelObject() ); - ft.setValue( "content:minX", "-2"); - ft.setValue( "content:minY", "-2"); - ft.setValue( "content:maxX", "2"); - ft.setValue( "content:maxY", "2"); + ft.setValue( "panel:minX", "-2"); + ft.setValue( "panel:minY", "-2"); + ft.setValue( "panel:maxX", "2"); + ft.setValue( "panel:maxY", "2"); ft.submit(); assertEquals( new Envelope(-2,2,-2,2), ep.getModelObject() ); } }
false
true
public void test() throws Exception { tester.assertComponent( "form", Form.class ); FormTester ft = tester.newFormTester( "form"); assertEquals( "-180", ft.getTextComponentValue( "content:minX") ); assertEquals( "-90", ft.getTextComponentValue( "content:minY") ); assertEquals( "180", ft.getTextComponentValue( "content:maxX") ); assertEquals( "90", ft.getTextComponentValue( "content:maxY") ); EnvelopePanel ep = (EnvelopePanel) tester.getComponentFromLastRenderedPage("form:content"); assertEquals( e, ep.getModelObject() ); ft.setValue( "content:minX", "-2"); ft.setValue( "content:minY", "-2"); ft.setValue( "content:maxX", "2"); ft.setValue( "content:maxY", "2"); ft.submit(); assertEquals( new Envelope(-2,2,-2,2), ep.getModelObject() ); }
public void test() throws Exception { tester.assertComponent( "form", Form.class ); FormTester ft = tester.newFormTester( "form"); assertEquals( "-180", ft.getTextComponentValue( "panel:minX") ); assertEquals( "-90", ft.getTextComponentValue( "panel:minY") ); assertEquals( "180", ft.getTextComponentValue( "panel:maxX") ); assertEquals( "90", ft.getTextComponentValue( "panel:maxY") ); EnvelopePanel ep = (EnvelopePanel) tester.getComponentFromLastRenderedPage("form:panel"); assertEquals( e, ep.getModelObject() ); ft.setValue( "panel:minX", "-2"); ft.setValue( "panel:minY", "-2"); ft.setValue( "panel:maxX", "2"); ft.setValue( "panel:maxY", "2"); ft.submit(); assertEquals( new Envelope(-2,2,-2,2), ep.getModelObject() ); }
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/WordUtil.java b/plugins/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/WordUtil.java index ed05063c4..65cb1aaca 100644 --- a/plugins/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/WordUtil.java +++ b/plugins/org.eclipse.birt.report.engine.emitter.wpml/src/org/eclipse/birt/report/engine/emitter/wpml/WordUtil.java @@ -1,422 +1,427 @@ /******************************************************************************* * Copyright (c) 2006 Inetsoft Technology Corp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Inetsoft Technology Corp - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.emitter.wpml; import java.util.HashSet; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.report.engine.content.IAutoTextContent; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants; import org.eclipse.birt.report.engine.ir.DimensionType; public class WordUtil { private static final String LINESTYLE_SOLID = "solid"; private static final String LINESTYLE_DASH = "dash"; private static final String LINESTYLE_DOT = "dot"; private static final String LINESTYLE_SINGLE = "single"; private static Logger logger = Logger.getLogger( WordUtil.class.getName( ) ); private static HashSet<Character> splitChar = new HashSet<Character>( ); static { splitChar.add( new Character( ' ' ) ); splitChar.add( new Character( '\r' ) ); splitChar.add( new Character( '\n' ) ); }; private static double Temp_PX; public final static double INCH_PX; static { try { Temp_PX = java.awt.Toolkit .getDefaultToolkit( ) .getScreenResolution( ); } catch ( Exception e ) { Temp_PX = 96; } INCH_PX = Temp_PX; } public final static double INCH_PT = 72; public final static double PT_TWIPS = 20; public final static double INCH_TWIPS = INCH_PT * PT_TWIPS; public final static double PX_TWIPS = INCH_TWIPS / INCH_PX; public final static double PX_PT = INCH_PT / INCH_PX; // Bookmark names must begin with a letter and can contain numbers. // spaces can not be included in a bookmark name, // but the underscore character can be used to separate words public static String validBookmarkName( String name ) { String bookmark = name.replaceAll( " ", "_" ); bookmark = bookmark.replaceAll( "\"", "_" ); return bookmark; } // convert from DimensionType to twips according to prefValue public static int convertTo( DimensionType value, int prefValue ) { if ( value == null ) { return prefValue; } if ( DimensionType.UNITS_PERCENTAGE .equalsIgnoreCase( value.getUnits( ) ) ) { return (int) ( prefValue * value.getMeasure( ) / 100 ); } return (int) convertTo( value ); } public static double convertTo( DimensionType value ) { if ( value == null || DimensionType.UNITS_PERCENTAGE.equalsIgnoreCase( value .getUnits( ) ) ) { return -1; } if ( DimensionType.UNITS_PX.equalsIgnoreCase( value.getUnits( ) ) ) { return value.getMeasure( ) * PX_TWIPS; } // FIXME: We should use font size to calculate the EM/EX if ( DimensionType.UNITS_EM.equalsIgnoreCase( value.getUnits( ) ) || DimensionType.UNITS_EX.equalsIgnoreCase( value.getUnits( ) ) ) { return value.getMeasure( ) * 12 * PT_TWIPS; } // The conversion is between absolute // the units should be one of the absolute units(CM, IN, MM, PT,PC). double val = value.convertTo( DimensionType.UNITS_IN ); return val * INCH_TWIPS; } // convert image's size from DimensionType to pt according to ref public static double convertImageSize( DimensionType value, int ref ) { if ( value == null ) { return ref * PX_PT; } if ( DimensionType.UNITS_PX.equalsIgnoreCase( value.getUnits( ) ) ) { return value.getMeasure( ) * PX_PT; } else if ( DimensionType.UNITS_PERCENTAGE.equalsIgnoreCase( value .getUnits( ) ) ) { return ( value.getMeasure( ) / 100 ) * ref * PX_PT; } else { return value.convertTo( DimensionType.UNITS_IN ) * INCH_PT; } } public static double twipToPt( double t ) { return t / PT_TWIPS; } // unit change from milliPt to twips public static int parseSpacing( float floatValue ) { return (int) ( Math.round( floatValue / 1000 ) * PT_TWIPS ); } // unit change from milliPt to half a point public static int parseFontSize( float value ) { return Math.round( value / 500 ); } public static String capitalize( String text ) { boolean capitalizeNextChar = true; char[] array = text.toCharArray( ); for ( int i = 0; i < array.length; i++ ) { Character c = new Character( text.charAt( i ) ); if ( splitChar.contains( c ) ) capitalizeNextChar = true; else if ( capitalizeNextChar ) { array[i] = Character.toUpperCase( array[i] ); capitalizeNextChar = false; } } return new String( array ); } // convert valid color format from "rgb(0,0,0)" to "000000" public static String parseColor( String color ) { - if ( "transparent".equalsIgnoreCase( color ) || color == null ) + if ( "transparent".equalsIgnoreCase( color ) || color == null + || color.length( ) == 0 ) { return null; } + if ( color.startsWith( "#" ) ) + { + return color.substring( 1, Math.min( color.length( ), 7 ) ); + } else if ( color.equalsIgnoreCase( "Black" ) ) return "000000"; else if ( color.equalsIgnoreCase( "Gray" ) ) return "121212"; else if ( color.equalsIgnoreCase( "White" ) ) return "ffffff"; else if ( color.equalsIgnoreCase( "Red" ) ) return "ff0000"; else if ( color.equalsIgnoreCase( "Green" ) ) return "00ff00"; else if ( color.equalsIgnoreCase( "Yellow" ) ) return "ffff00"; else if ( color.equalsIgnoreCase( "Blue" ) ) return "0000ff"; else if ( color.equalsIgnoreCase( "Teal" ) ) return "008080"; else if ( color.equalsIgnoreCase( "Aqua" ) ) return "00FFFF"; else if ( color.equalsIgnoreCase( "Silver" ) ) return "C0C0C0"; else if ( color.equalsIgnoreCase( "Navy" ) ) return "000080"; else if ( color.equalsIgnoreCase( "Lime" ) ) return "00FF00"; else if ( color.equalsIgnoreCase( "Olive" ) ) return "808000"; else if ( color.equalsIgnoreCase( "Purple" ) ) return "800080"; else if ( color.equalsIgnoreCase( "Fuchsia" ) ) return "FF00FF"; else if ( color.equalsIgnoreCase( "Maroon" ) ) return "800000"; String[] values = color.substring( color.indexOf( "(" ) + 1, color.length( ) - 1 ).split( "," ); String value = ""; for ( int i = 0; i < values.length; i++ ) { try { String s = Integer.toHexString( ( Integer.parseInt( values[i] .trim( ) ) ) ); if ( s.length( ) == 1 ) { s = "0" + s; } value += s; } catch ( Exception e ) { logger.log( Level.WARNING, e.getMessage( ), e ); value = null; } } return value; } // run border, paragraph borders, table borders, table cell borders // birt accept:solid, dotted, dashed, double // doc and docx accept: single, dotted, dashed, double public static String parseBorderStyle( String style ) { if ( CSSConstants.CSS_SOLID_VALUE.equalsIgnoreCase( style ) ) { return LINESTYLE_SINGLE; } return style; } // image borders style // birt accept: solid, dotted, dashed, double // doc and docx accept in vml: single, dot, dash, double public static String parseImageBorderStyle( String style ) { if ( CSSConstants.CSS_DOTTED_VALUE.equalsIgnoreCase( style ) ) { return LINESTYLE_DOT; } if ( CSSConstants.CSS_DASHED_VALUE.equalsIgnoreCase( style ) ) { return LINESTYLE_DASH; } if ( CSSConstants.CSS_SOLID_VALUE.equalsIgnoreCase( style ) ) { return LINESTYLE_SINGLE; } return style; } // align: bottom, middle, top // doc and docx accept: bottom, center, top public static String parseVerticalAlign( String align ) { if ( CSSConstants.CSS_MIDDLE_VALUE.equals( align ) ) { return "center"; } return align; } public static String removeQuote( String val ) { if ( val.charAt( 0 ) == '"' && val.charAt( val.length( ) - 1 ) == '"' ) { return val.substring( 1, val.length( ) - 1 ); } return val; } // unit: eights of a point public static int parseBorderSize( float size ) { int w = Math.round( size ); return ( 8 * w ) / 750; } public static String parseLineStyle( String style ) { if ( CSSConstants.CSS_DOTTED_VALUE.equalsIgnoreCase( style ) ) { return LINESTYLE_DOT; } if ( CSSConstants.CSS_DASHED_VALUE.equalsIgnoreCase( style ) ) { return LINESTYLE_DASH; } if ( CSSConstants.CSS_DOUBLE_VALUE.equalsIgnoreCase( style ) ) { return LINESTYLE_SOLID; } return style; } public static String[] parseBackgroundSize( String height, String width, int imageWidth, int imageHeight, double pageWidth, double pageHeight ) { String actualHeight = height; String actualWidth = width; if ( height == null || "auto".equalsIgnoreCase( height ) ) actualHeight = String.valueOf( pageHeight )+"pt"; if ( width == null || "auto".equalsIgnoreCase( width ) ) actualWidth = String.valueOf( pageWidth ) + "pt"; actualHeight = actualHeight.trim( ); actualWidth = actualWidth.trim( ); if ( "contain".equalsIgnoreCase( actualWidth ) || ( "contain" ).equalsIgnoreCase( actualHeight ) ) { double rh = imageHeight / pageHeight; double rw = imageWidth / pageWidth; if ( rh > rw ) { actualHeight = String.valueOf( pageHeight ) + "pt"; actualWidth = String.valueOf( imageWidth * pageHeight / imageHeight ) + "pt"; } else { actualWidth = String.valueOf( pageWidth ) + "pt"; actualHeight = String.valueOf( imageHeight * pageWidth / imageWidth ) + "pt"; } } else if ( "cover".equals( actualWidth ) || "cover".equals( actualHeight ) ) { double rh = imageHeight / pageHeight; double rw = imageWidth / pageWidth; if ( rh > rw ) { actualWidth = String.valueOf( pageWidth ) + "pt"; actualHeight = String.valueOf( imageHeight * pageWidth / imageWidth ) + "pt"; } else { actualHeight = String.valueOf( pageHeight ) + "pt"; actualWidth = String.valueOf( imageWidth * pageHeight / imageHeight ) + "pt"; } } if ( height != null && height.endsWith( "%" ) ) { actualHeight = getPercentValue( height, pageHeight ) + "pt"; } if ( width != null && width.endsWith( "%" ) ) { actualWidth = getPercentValue( width, pageWidth ) + "pt"; } return new String[]{actualHeight, actualWidth}; } private static String getPercentValue( String height, double pageHeight ) { String value = null; try { String percent = height.substring( 0, height.length( ) - 1 ); int percentValue = Integer.valueOf( percent ).intValue( ); value = String.valueOf( pageHeight * percentValue / 100 ); } catch ( NumberFormatException e ) { value = height; } return value; } public static boolean isField( int autoTextType ) { return autoTextType == IAutoTextContent.PAGE_NUMBER || autoTextType == IAutoTextContent.TOTAL_PAGE; } public static boolean isField( IContent content ) { if ( content.getContentType( ) == IContent.AUTOTEXT_CONTENT ) { IAutoTextContent autoText = (IAutoTextContent) content; int type = autoText.getType( ); return isField( type ); } return false; } }
false
true
public static String parseColor( String color ) { if ( "transparent".equalsIgnoreCase( color ) || color == null ) { return null; } else if ( color.equalsIgnoreCase( "Black" ) ) return "000000"; else if ( color.equalsIgnoreCase( "Gray" ) ) return "121212"; else if ( color.equalsIgnoreCase( "White" ) ) return "ffffff"; else if ( color.equalsIgnoreCase( "Red" ) ) return "ff0000"; else if ( color.equalsIgnoreCase( "Green" ) ) return "00ff00"; else if ( color.equalsIgnoreCase( "Yellow" ) ) return "ffff00"; else if ( color.equalsIgnoreCase( "Blue" ) ) return "0000ff"; else if ( color.equalsIgnoreCase( "Teal" ) ) return "008080"; else if ( color.equalsIgnoreCase( "Aqua" ) ) return "00FFFF"; else if ( color.equalsIgnoreCase( "Silver" ) ) return "C0C0C0"; else if ( color.equalsIgnoreCase( "Navy" ) ) return "000080"; else if ( color.equalsIgnoreCase( "Lime" ) ) return "00FF00"; else if ( color.equalsIgnoreCase( "Olive" ) ) return "808000"; else if ( color.equalsIgnoreCase( "Purple" ) ) return "800080"; else if ( color.equalsIgnoreCase( "Fuchsia" ) ) return "FF00FF"; else if ( color.equalsIgnoreCase( "Maroon" ) ) return "800000"; String[] values = color.substring( color.indexOf( "(" ) + 1, color.length( ) - 1 ).split( "," ); String value = ""; for ( int i = 0; i < values.length; i++ ) { try { String s = Integer.toHexString( ( Integer.parseInt( values[i] .trim( ) ) ) ); if ( s.length( ) == 1 ) { s = "0" + s; } value += s; } catch ( Exception e ) { logger.log( Level.WARNING, e.getMessage( ), e ); value = null; } } return value; }
public static String parseColor( String color ) { if ( "transparent".equalsIgnoreCase( color ) || color == null || color.length( ) == 0 ) { return null; } if ( color.startsWith( "#" ) ) { return color.substring( 1, Math.min( color.length( ), 7 ) ); } else if ( color.equalsIgnoreCase( "Black" ) ) return "000000"; else if ( color.equalsIgnoreCase( "Gray" ) ) return "121212"; else if ( color.equalsIgnoreCase( "White" ) ) return "ffffff"; else if ( color.equalsIgnoreCase( "Red" ) ) return "ff0000"; else if ( color.equalsIgnoreCase( "Green" ) ) return "00ff00"; else if ( color.equalsIgnoreCase( "Yellow" ) ) return "ffff00"; else if ( color.equalsIgnoreCase( "Blue" ) ) return "0000ff"; else if ( color.equalsIgnoreCase( "Teal" ) ) return "008080"; else if ( color.equalsIgnoreCase( "Aqua" ) ) return "00FFFF"; else if ( color.equalsIgnoreCase( "Silver" ) ) return "C0C0C0"; else if ( color.equalsIgnoreCase( "Navy" ) ) return "000080"; else if ( color.equalsIgnoreCase( "Lime" ) ) return "00FF00"; else if ( color.equalsIgnoreCase( "Olive" ) ) return "808000"; else if ( color.equalsIgnoreCase( "Purple" ) ) return "800080"; else if ( color.equalsIgnoreCase( "Fuchsia" ) ) return "FF00FF"; else if ( color.equalsIgnoreCase( "Maroon" ) ) return "800000"; String[] values = color.substring( color.indexOf( "(" ) + 1, color.length( ) - 1 ).split( "," ); String value = ""; for ( int i = 0; i < values.length; i++ ) { try { String s = Integer.toHexString( ( Integer.parseInt( values[i] .trim( ) ) ) ); if ( s.length( ) == 1 ) { s = "0" + s; } value += s; } catch ( Exception e ) { logger.log( Level.WARNING, e.getMessage( ), e ); value = null; } } return value; }
diff --git a/src/main/java/org/apache/commons/jexl/util/ListGetExecutor.java b/src/main/java/org/apache/commons/jexl/util/ListGetExecutor.java index 55827e28..23856901 100644 --- a/src/main/java/org/apache/commons/jexl/util/ListGetExecutor.java +++ b/src/main/java/org/apache/commons/jexl/util/ListGetExecutor.java @@ -1,90 +1,90 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.jexl.util; import java.util.List; import java.lang.reflect.Array; /** * Specialized executor to get a property from a List or array. */ public final class ListGetExecutor extends AbstractExecutor.Get { /** The java.lang.reflect.Array.get method used as an active marker in ListGet. */ private static final java.lang.reflect.Method ARRAY_GET = initMarker(Array.class, "get", Object.class, Integer.TYPE); /** The java.util.list.get method used as an active marker in ListGet. */ private static final java.lang.reflect.Method LIST_GET = initMarker(List.class, "get", Integer.TYPE); /** The property. */ private final Integer property; /** * Creates an instance checking for the List interface or Array capability. * @param is the introspector * @param clazz the class to introspect * @param index the index to use in list.get(index) */ public ListGetExecutor(Introspector is, Class<?> clazz, Integer index) { super(clazz, discover(clazz)); property = index; } /** * Get the property from the list or array. * @param list the List/array. * @return list.get(index) */ @Override public Object execute(final Object list) { if (method == ARRAY_GET) { return java.lang.reflect.Array.get(list, property.intValue()); } else { return ((List<?>) list).get(property.intValue()); } } /** {@inheritDoc} */ @Override public Object tryExecute(final Object list, Object index) { if (method == discover(list.getClass()) && objectClass.equals(list.getClass()) && index instanceof Integer) { if (method == ARRAY_GET) { - return java.lang.reflect.Array.get(list, property.intValue()); + return java.lang.reflect.Array.get(list, (Integer) index); } else { - return ((List<?>) list).get(property.intValue()); + return ((List<?>) list).get((Integer) index); } } return TRY_FAILED; } /** * Finds the method to perform the get on a list of array. * @param clazz the class to introspect * @return a marker method, list.get or array.get */ static java.lang.reflect.Method discover(Class<?> clazz) { //return discoverList(false, clazz, property); if (clazz.isArray()) { return ARRAY_GET; } if (List.class.isAssignableFrom(clazz)) { return LIST_GET; } return null; } }
false
true
public Object tryExecute(final Object list, Object index) { if (method == discover(list.getClass()) && objectClass.equals(list.getClass()) && index instanceof Integer) { if (method == ARRAY_GET) { return java.lang.reflect.Array.get(list, property.intValue()); } else { return ((List<?>) list).get(property.intValue()); } } return TRY_FAILED; }
public Object tryExecute(final Object list, Object index) { if (method == discover(list.getClass()) && objectClass.equals(list.getClass()) && index instanceof Integer) { if (method == ARRAY_GET) { return java.lang.reflect.Array.get(list, (Integer) index); } else { return ((List<?>) list).get((Integer) index); } } return TRY_FAILED; }
diff --git a/src/edu/brown/cs32/MFTG/gui/EndGamePanel.java b/src/edu/brown/cs32/MFTG/gui/EndGamePanel.java index e97ad6d..6a2fe68 100644 --- a/src/edu/brown/cs32/MFTG/gui/EndGamePanel.java +++ b/src/edu/brown/cs32/MFTG/gui/EndGamePanel.java @@ -1,209 +1,209 @@ package edu.brown.cs32.MFTG.gui; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.event.MouseInputAdapter; import edu.brown.cs32.MFTG.gui.gameboard.Board; public class EndGamePanel extends JPanel{ private ImagePanel _backLite, _backDark, _viewLite, _viewDark; private BufferedImage _winner, _loser, _foreground; private Point _backLoc, _goLoc, _viewLoc; private MonopolyGui _main; private List<String> _names; private boolean _winning; private JLabel _name1, _name2, _name3, _name4; private final int BUTTON_HEIGHT=Constants.FULL_PANEL_HEIGHT/8; private final int BUTTON_WIDTH=2*Constants.FULL_PANEL_HEIGHT/3; private final int START_HEIGHT=Constants.FULL_PANEL_HEIGHT/8; private final int START_WIDTH=Constants.FULL_WIDTH/6; private Font _nameFont; private Board _board; public EndGamePanel(MonopolyGui main, Board board) { try { _board=board; _main=main; java.awt.Dimension size = new java.awt.Dimension(Constants.FULL_WIDTH,Constants.FULL_PANEL_HEIGHT); this.setPreferredSize(size); this.setSize(size); this.setBackground(Color.GRAY); this.setLayout(null); _winner = Helper.resize(ImageIO.read(new File("images/Winner2.png")),this.getWidth(),this.getHeight()); _loser = Helper.resize(ImageIO.read(new File("images/Loser.png")),this.getWidth(),this.getHeight()); _foreground = Helper.resize(ImageIO.read(new File("images/WinnerColumns.png")),this.getWidth(),this.getHeight()); _backLite = new ImagePanel(Helper.resize(ImageIO.read(new File("images/MainMenuLite.png")), 130, 50)); _backDark = new ImagePanel(Helper.resize(ImageIO.read(new File("images/MainMenuDark.png")), 130, 50)); _backLoc= new Point(this.getWidth()-_backLite.getWidth()-50, this.getHeight()-_backDark.getHeight()-40); _backLite.setLocation(_backLoc); _backDark.setLocation(_backLoc); _backDark.setVisible(false); _viewLite = new ImagePanel(Helper.resize(ImageIO.read(new File("images/ViewLite.png")), 110, 50)); _viewDark = new ImagePanel(Helper.resize(ImageIO.read(new File("images/ViewDark.png")), 110, 50)); _viewLoc= new Point(this.getWidth()-_backLite.getWidth()-40, this.getHeight()-_viewLite.getHeight()-_backDark.getHeight()-50); _viewLite.setLocation(_viewLoc); _viewDark.setLocation(_viewLoc); _viewDark.setVisible(false); _winning=false; addMouseListener(new MyMouseListener()); _nameFont = new Font("nameFont", Font.BOLD, 16); _names = new ArrayList<>(); _name1 = new JLabel("<html>First Place</html>"); _name2 = new JLabel("<html>Second Place</html>"); _name3 = new JLabel("<html>Third Place</html>"); _name4 = new JLabel("<html>Last Place</html>"); Dimension nameSize = new Dimension(120,50); _name1.setSize(nameSize); _name1.setPreferredSize(nameSize); _name2.setSize(nameSize); _name2.setPreferredSize(nameSize); _name3.setSize(nameSize); _name3.setPreferredSize(nameSize); _name4.setSize(nameSize); _name4.setPreferredSize(nameSize); - _name1.setLocation(10,245); - _name2.setLocation(140,380); - _name3.setLocation(260,560); - _name4.setLocation(390,770); + _name1.setLocation(10,250); + _name2.setLocation(145,385); + _name3.setLocation(275,570); + _name4.setLocation(415,810); _name1.setFont(_nameFont); _name2.setFont(_nameFont); _name3.setFont(_nameFont); _name4.setFont(_nameFont); add(_backLite); add(_backDark); add(_viewLite); add(_viewDark); add(_name1); add(_name2); add(_name3); add(_name4); } catch (IOException e) { System.out.println("ERROR: "+e.getMessage()); System.exit(1); } } /** * sets if player won * @param didWin */ public void setWinner(boolean didWin, String[] names) { _winning=didWin; if(names.length>0)_name1.setText("<html>"+names[0]+"</html>"); if(names.length>1)_name2.setText("<html>"+names[1]+"</html>"); if(names.length>2)_name3.setText("<html>"+names[2]+"</html>"); if(names.length>3)_name4.setText("<html>"+names[3]+"</html>"); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D brush = (Graphics2D) g; brush.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if(_winning)brush.drawImage(_winner, 0, 0, null); else brush.drawImage(_loser, 0, 0, null); brush.drawImage(_foreground, 0, 0, null); } private class MyMouseListener extends MouseInputAdapter{ public MyMouseListener() { super(); } @Override public void mousePressed(MouseEvent e) { int xloc=e.getX(); int yloc=e.getY(); if(intersects(xloc,yloc,_backLite,_backLoc)) { _backLite.setVisible(false); _backDark.setVisible(true); repaint(); } if(intersects(xloc,yloc,_viewLite,_viewLoc)) { _viewLite.setVisible(false); _viewDark.setVisible(true); repaint(); } } @Override public void mouseReleased(MouseEvent e) { int xloc=e.getX(); int yloc=e.getY(); if(intersects(xloc,yloc,_backLite,_backLoc)) { if(_backDark.isVisible()) { fixPanels(); _main.switchPanels("greet"); } else { fixPanels(); } } else if(intersects(xloc,yloc,_viewLite,_viewLoc)) { if(_viewDark.isVisible()) { fixPanels(); _board.switchToEndGameMenu(); _main.switchPanels("board"); } else { fixPanels(); } } else { fixPanels(); } } private void fixPanels() { _backDark.setVisible(false); _backLite.setVisible(true); _viewDark.setVisible(false); _viewLite.setVisible(true); repaint(); } private boolean intersects(int xloc, int yloc, JPanel img, Point loc) { if(xloc>=loc.x && xloc<=loc.x+img.getWidth() && yloc>=loc.y && yloc<=loc.y+img.getHeight()) { return true; } return false; } } }
true
true
public EndGamePanel(MonopolyGui main, Board board) { try { _board=board; _main=main; java.awt.Dimension size = new java.awt.Dimension(Constants.FULL_WIDTH,Constants.FULL_PANEL_HEIGHT); this.setPreferredSize(size); this.setSize(size); this.setBackground(Color.GRAY); this.setLayout(null); _winner = Helper.resize(ImageIO.read(new File("images/Winner2.png")),this.getWidth(),this.getHeight()); _loser = Helper.resize(ImageIO.read(new File("images/Loser.png")),this.getWidth(),this.getHeight()); _foreground = Helper.resize(ImageIO.read(new File("images/WinnerColumns.png")),this.getWidth(),this.getHeight()); _backLite = new ImagePanel(Helper.resize(ImageIO.read(new File("images/MainMenuLite.png")), 130, 50)); _backDark = new ImagePanel(Helper.resize(ImageIO.read(new File("images/MainMenuDark.png")), 130, 50)); _backLoc= new Point(this.getWidth()-_backLite.getWidth()-50, this.getHeight()-_backDark.getHeight()-40); _backLite.setLocation(_backLoc); _backDark.setLocation(_backLoc); _backDark.setVisible(false); _viewLite = new ImagePanel(Helper.resize(ImageIO.read(new File("images/ViewLite.png")), 110, 50)); _viewDark = new ImagePanel(Helper.resize(ImageIO.read(new File("images/ViewDark.png")), 110, 50)); _viewLoc= new Point(this.getWidth()-_backLite.getWidth()-40, this.getHeight()-_viewLite.getHeight()-_backDark.getHeight()-50); _viewLite.setLocation(_viewLoc); _viewDark.setLocation(_viewLoc); _viewDark.setVisible(false); _winning=false; addMouseListener(new MyMouseListener()); _nameFont = new Font("nameFont", Font.BOLD, 16); _names = new ArrayList<>(); _name1 = new JLabel("<html>First Place</html>"); _name2 = new JLabel("<html>Second Place</html>"); _name3 = new JLabel("<html>Third Place</html>"); _name4 = new JLabel("<html>Last Place</html>"); Dimension nameSize = new Dimension(120,50); _name1.setSize(nameSize); _name1.setPreferredSize(nameSize); _name2.setSize(nameSize); _name2.setPreferredSize(nameSize); _name3.setSize(nameSize); _name3.setPreferredSize(nameSize); _name4.setSize(nameSize); _name4.setPreferredSize(nameSize); _name1.setLocation(10,245); _name2.setLocation(140,380); _name3.setLocation(260,560); _name4.setLocation(390,770); _name1.setFont(_nameFont); _name2.setFont(_nameFont); _name3.setFont(_nameFont); _name4.setFont(_nameFont); add(_backLite); add(_backDark); add(_viewLite); add(_viewDark); add(_name1); add(_name2); add(_name3); add(_name4); } catch (IOException e) { System.out.println("ERROR: "+e.getMessage()); System.exit(1); } }
public EndGamePanel(MonopolyGui main, Board board) { try { _board=board; _main=main; java.awt.Dimension size = new java.awt.Dimension(Constants.FULL_WIDTH,Constants.FULL_PANEL_HEIGHT); this.setPreferredSize(size); this.setSize(size); this.setBackground(Color.GRAY); this.setLayout(null); _winner = Helper.resize(ImageIO.read(new File("images/Winner2.png")),this.getWidth(),this.getHeight()); _loser = Helper.resize(ImageIO.read(new File("images/Loser.png")),this.getWidth(),this.getHeight()); _foreground = Helper.resize(ImageIO.read(new File("images/WinnerColumns.png")),this.getWidth(),this.getHeight()); _backLite = new ImagePanel(Helper.resize(ImageIO.read(new File("images/MainMenuLite.png")), 130, 50)); _backDark = new ImagePanel(Helper.resize(ImageIO.read(new File("images/MainMenuDark.png")), 130, 50)); _backLoc= new Point(this.getWidth()-_backLite.getWidth()-50, this.getHeight()-_backDark.getHeight()-40); _backLite.setLocation(_backLoc); _backDark.setLocation(_backLoc); _backDark.setVisible(false); _viewLite = new ImagePanel(Helper.resize(ImageIO.read(new File("images/ViewLite.png")), 110, 50)); _viewDark = new ImagePanel(Helper.resize(ImageIO.read(new File("images/ViewDark.png")), 110, 50)); _viewLoc= new Point(this.getWidth()-_backLite.getWidth()-40, this.getHeight()-_viewLite.getHeight()-_backDark.getHeight()-50); _viewLite.setLocation(_viewLoc); _viewDark.setLocation(_viewLoc); _viewDark.setVisible(false); _winning=false; addMouseListener(new MyMouseListener()); _nameFont = new Font("nameFont", Font.BOLD, 16); _names = new ArrayList<>(); _name1 = new JLabel("<html>First Place</html>"); _name2 = new JLabel("<html>Second Place</html>"); _name3 = new JLabel("<html>Third Place</html>"); _name4 = new JLabel("<html>Last Place</html>"); Dimension nameSize = new Dimension(120,50); _name1.setSize(nameSize); _name1.setPreferredSize(nameSize); _name2.setSize(nameSize); _name2.setPreferredSize(nameSize); _name3.setSize(nameSize); _name3.setPreferredSize(nameSize); _name4.setSize(nameSize); _name4.setPreferredSize(nameSize); _name1.setLocation(10,250); _name2.setLocation(145,385); _name3.setLocation(275,570); _name4.setLocation(415,810); _name1.setFont(_nameFont); _name2.setFont(_nameFont); _name3.setFont(_nameFont); _name4.setFont(_nameFont); add(_backLite); add(_backDark); add(_viewLite); add(_viewDark); add(_name1); add(_name2); add(_name3); add(_name4); } catch (IOException e) { System.out.println("ERROR: "+e.getMessage()); System.exit(1); } }
diff --git a/src/main/java/be/Balor/Manager/Commands/Player/Experience.java b/src/main/java/be/Balor/Manager/Commands/Player/Experience.java index 090d754f..cbaed874 100644 --- a/src/main/java/be/Balor/Manager/Commands/Player/Experience.java +++ b/src/main/java/be/Balor/Manager/Commands/Player/Experience.java @@ -1,190 +1,179 @@ /************************************************************************ * This file is part of AdminCmd. * * AdminCmd is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AdminCmd is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AdminCmd. If not, see <http://www.gnu.org/licenses/>. ************************************************************************/ package be.Balor.Manager.Commands.Player; import java.util.HashMap; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.ExperienceOrb; import org.bukkit.entity.Player; import be.Balor.Manager.Commands.CommandArgs; import be.Balor.Manager.Exceptions.PlayerNotFound; import be.Balor.Manager.Permissions.ActionNotPermitedException; import be.Balor.Tools.Utils; import be.Balor.bukkit.AdminCmd.ACPluginManager; /** * @author Lathanael (aka Philippe Leipold) * */ public class Experience extends PlayerCommand { public Experience() { permNode = "admincmd.player.experience"; cmdName = "bal_exp"; other = true; } /* * (non-Javadoc) * * @see * be.Balor.Manager.ACCommands#execute(org.bukkit.command.CommandSender, * java.lang.String[]) */ @Override public void execute(final CommandSender sender, final CommandArgs args) throws ActionNotPermitedException, PlayerNotFound { float amount = 0; Player target = null; final HashMap<String, String> replace = new HashMap<String, String>(); boolean self = false; - if (0 < args.length && args.length < 2) { - if (Utils.isPlayer(sender, true)) { - target = (Player) sender; - self = true; - if (!args.hasFlag('t')) { - try { - amount = args.getFloat(0); - } catch (final NumberFormatException e) { - replace.put("number", args.getString(0)); - Utils.I18n("NaN", replace); - return; - } - } - } else { - return; - } - } else if (args.length >= 2) { - target = Utils.getPlayer(args.getString(0)); + if (args.hasFlag('p')) { + target = Utils.getPlayer(args.getValueFlag('p')); + } else { + target = (Player) sender; + self = true; + } + if (0 < args.length) { if (!args.hasFlag('t')) { try { - amount = args.getFloat(1); + amount = args.getFloat(0); } catch (final NumberFormatException e) { replace.put("number", args.getString(0)); Utils.I18n("NaN", replace); return; } } } else { if (Utils.isPlayer(sender, true)) { if (args.hasFlag('t')) { target = (Player) sender; replace.put("exp", String.valueOf(target.getTotalExperience())); sender.sendMessage(Utils.I18n("expTotal", replace)); return; } } else { return; } } if (target == null) { return; } replace.put("amount", String.valueOf(amount)); final Player taskTarget = target; final float amountXp = amount; if (args.hasFlag('d')) { final Location loc = target.getLocation(); loc.setX(loc.getX() + 2); ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.getLocation().getWorld() .spawn(loc, ExperienceOrb.class) .setExperience((int) amountXp); } }); if (self) { target.sendMessage(Utils.I18n("expDropped", replace)); } else { replace.put("target", Utils.getPlayerName(target)); target.sendMessage(Utils.I18n("expDropped", replace)); sender.sendMessage(Utils.I18n("expDroppedTarget", replace)); } } else if (args.hasFlag('a')) { ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.giveExp((int) amountXp); } }); if (self) { target.sendMessage(Utils.I18n("expAdded", replace)); } else { replace.put("target", Utils.getPlayerName(target)); sender.sendMessage(Utils.I18n("expAddedTarget", replace)); target.sendMessage(Utils.I18n("expAdded", replace)); } - } else if (args.hasFlag('p')) { + } else if (args.hasFlag('b')) { final float exp = (amount > 1 ? 1 : amount); ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.setExp(exp); } }); replace.put("amount", String.valueOf(exp * 100.0F)); if (self) { target.sendMessage(Utils.I18n("expProgressionSet", replace)); } else { replace.put("target", Utils.getPlayerName(target)); target.sendMessage(Utils.I18n("expProgressionSet", replace)); sender.sendMessage(Utils.I18n("expProgressionSetTarget", replace)); } } else if (args.hasFlag('l')) { ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.setLevel((int) amountXp); } }); if (self) { target.sendMessage(Utils.I18n("expLevelSet", replace)); } else { replace.put("target", Utils.getPlayerName(target)); target.sendMessage(Utils.I18n("expLevelSet", replace)); sender.sendMessage(Utils.I18n("expLevelSetTarget", replace)); } } else if (args.hasFlag('t')) { replace.put("exp", String.valueOf(target.getTotalExperience())); if (self) { sender.sendMessage(Utils.I18n("expTotal", replace)); } else { replace.put("target", Utils.getPlayerName(target)); sender.sendMessage(Utils.I18n("expTotalTarget", replace)); } } } /* * (non-Javadoc) * * @see be.Balor.Manager.ACCommands#argsCheck(java.lang.String[]) */ @Override public boolean argsCheck(final String... args) { return args != null && args.length >= 1; } }
false
true
public void execute(final CommandSender sender, final CommandArgs args) throws ActionNotPermitedException, PlayerNotFound { float amount = 0; Player target = null; final HashMap<String, String> replace = new HashMap<String, String>(); boolean self = false; if (0 < args.length && args.length < 2) { if (Utils.isPlayer(sender, true)) { target = (Player) sender; self = true; if (!args.hasFlag('t')) { try { amount = args.getFloat(0); } catch (final NumberFormatException e) { replace.put("number", args.getString(0)); Utils.I18n("NaN", replace); return; } } } else { return; } } else if (args.length >= 2) { target = Utils.getPlayer(args.getString(0)); if (!args.hasFlag('t')) { try { amount = args.getFloat(1); } catch (final NumberFormatException e) { replace.put("number", args.getString(0)); Utils.I18n("NaN", replace); return; } } } else { if (Utils.isPlayer(sender, true)) { if (args.hasFlag('t')) { target = (Player) sender; replace.put("exp", String.valueOf(target.getTotalExperience())); sender.sendMessage(Utils.I18n("expTotal", replace)); return; } } else { return; } } if (target == null) { return; } replace.put("amount", String.valueOf(amount)); final Player taskTarget = target; final float amountXp = amount; if (args.hasFlag('d')) { final Location loc = target.getLocation(); loc.setX(loc.getX() + 2); ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.getLocation().getWorld() .spawn(loc, ExperienceOrb.class) .setExperience((int) amountXp); } }); if (self) { target.sendMessage(Utils.I18n("expDropped", replace)); } else { replace.put("target", Utils.getPlayerName(target)); target.sendMessage(Utils.I18n("expDropped", replace)); sender.sendMessage(Utils.I18n("expDroppedTarget", replace)); } } else if (args.hasFlag('a')) { ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.giveExp((int) amountXp); } }); if (self) { target.sendMessage(Utils.I18n("expAdded", replace)); } else { replace.put("target", Utils.getPlayerName(target)); sender.sendMessage(Utils.I18n("expAddedTarget", replace)); target.sendMessage(Utils.I18n("expAdded", replace)); } } else if (args.hasFlag('p')) { final float exp = (amount > 1 ? 1 : amount); ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.setExp(exp); } }); replace.put("amount", String.valueOf(exp * 100.0F)); if (self) { target.sendMessage(Utils.I18n("expProgressionSet", replace)); } else { replace.put("target", Utils.getPlayerName(target)); target.sendMessage(Utils.I18n("expProgressionSet", replace)); sender.sendMessage(Utils.I18n("expProgressionSetTarget", replace)); } } else if (args.hasFlag('l')) { ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.setLevel((int) amountXp); } }); if (self) { target.sendMessage(Utils.I18n("expLevelSet", replace)); } else { replace.put("target", Utils.getPlayerName(target)); target.sendMessage(Utils.I18n("expLevelSet", replace)); sender.sendMessage(Utils.I18n("expLevelSetTarget", replace)); } } else if (args.hasFlag('t')) { replace.put("exp", String.valueOf(target.getTotalExperience())); if (self) { sender.sendMessage(Utils.I18n("expTotal", replace)); } else { replace.put("target", Utils.getPlayerName(target)); sender.sendMessage(Utils.I18n("expTotalTarget", replace)); } } }
public void execute(final CommandSender sender, final CommandArgs args) throws ActionNotPermitedException, PlayerNotFound { float amount = 0; Player target = null; final HashMap<String, String> replace = new HashMap<String, String>(); boolean self = false; if (args.hasFlag('p')) { target = Utils.getPlayer(args.getValueFlag('p')); } else { target = (Player) sender; self = true; } if (0 < args.length) { if (!args.hasFlag('t')) { try { amount = args.getFloat(0); } catch (final NumberFormatException e) { replace.put("number", args.getString(0)); Utils.I18n("NaN", replace); return; } } } else { if (Utils.isPlayer(sender, true)) { if (args.hasFlag('t')) { target = (Player) sender; replace.put("exp", String.valueOf(target.getTotalExperience())); sender.sendMessage(Utils.I18n("expTotal", replace)); return; } } else { return; } } if (target == null) { return; } replace.put("amount", String.valueOf(amount)); final Player taskTarget = target; final float amountXp = amount; if (args.hasFlag('d')) { final Location loc = target.getLocation(); loc.setX(loc.getX() + 2); ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.getLocation().getWorld() .spawn(loc, ExperienceOrb.class) .setExperience((int) amountXp); } }); if (self) { target.sendMessage(Utils.I18n("expDropped", replace)); } else { replace.put("target", Utils.getPlayerName(target)); target.sendMessage(Utils.I18n("expDropped", replace)); sender.sendMessage(Utils.I18n("expDroppedTarget", replace)); } } else if (args.hasFlag('a')) { ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.giveExp((int) amountXp); } }); if (self) { target.sendMessage(Utils.I18n("expAdded", replace)); } else { replace.put("target", Utils.getPlayerName(target)); sender.sendMessage(Utils.I18n("expAddedTarget", replace)); target.sendMessage(Utils.I18n("expAdded", replace)); } } else if (args.hasFlag('b')) { final float exp = (amount > 1 ? 1 : amount); ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.setExp(exp); } }); replace.put("amount", String.valueOf(exp * 100.0F)); if (self) { target.sendMessage(Utils.I18n("expProgressionSet", replace)); } else { replace.put("target", Utils.getPlayerName(target)); target.sendMessage(Utils.I18n("expProgressionSet", replace)); sender.sendMessage(Utils.I18n("expProgressionSetTarget", replace)); } } else if (args.hasFlag('l')) { ACPluginManager.scheduleSyncTask(new Runnable() { @Override public void run() { taskTarget.setLevel((int) amountXp); } }); if (self) { target.sendMessage(Utils.I18n("expLevelSet", replace)); } else { replace.put("target", Utils.getPlayerName(target)); target.sendMessage(Utils.I18n("expLevelSet", replace)); sender.sendMessage(Utils.I18n("expLevelSetTarget", replace)); } } else if (args.hasFlag('t')) { replace.put("exp", String.valueOf(target.getTotalExperience())); if (self) { sender.sendMessage(Utils.I18n("expTotal", replace)); } else { replace.put("target", Utils.getPlayerName(target)); sender.sendMessage(Utils.I18n("expTotalTarget", replace)); } } }
diff --git a/server/standalone/src/main/java/de/matrixweb/smaller/internal/Main.java b/server/standalone/src/main/java/de/matrixweb/smaller/internal/Main.java index 7839e7e..0e50548 100644 --- a/server/standalone/src/main/java/de/matrixweb/smaller/internal/Main.java +++ b/server/standalone/src/main/java/de/matrixweb/smaller/internal/Main.java @@ -1,132 +1,133 @@ package de.matrixweb.smaller.internal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.io.IOUtils; /** * @author markusw */ public final class Main { private Main() { } /** * @param args */ public static void main(final String[] args) { try { ClassLoader cl = Main.class.getClassLoader(); final String classpath = System.getProperty("java.class.path"); if (!classpath.contains(":")) { cl = prepareClassPath(classpath); } Class.forName("de.matrixweb.smaller.internal.Server", true, cl) .getMethod("main", String[].class).invoke(null, (Object) args); } catch (final IOException e) { throw new FatalServerException("Fatal Server Error", e); } catch (final IllegalAccessException e) { throw new FatalServerException("Fatal Server Error", e); } catch (final InvocationTargetException e) { throw new FatalServerException("Fatal Server Error", e); } catch (final NoSuchMethodException e) { throw new FatalServerException("Fatal Server Error", e); } catch (final ClassNotFoundException e) { throw new FatalServerException("Fatal Server Error", e); } } private static ClassLoader prepareClassPath(final String classpath) throws IOException { final JarFile jar = new JarFile(classpath); try { final List<URL> urls = copyJarEntries(jar, createTempStorage()); urls.add(new URL("file:" + classpath)); return new URLClassLoader(urls.toArray(new URL[urls.size()]), null); } finally { jar.close(); } } private static List<URL> copyJarEntries(final JarFile jar, final File temp) throws IOException { final List<URL> urls = new LinkedList<URL>(); final Enumeration<JarEntry> e = jar.entries(); while (e.hasMoreElements()) { final JarEntry entry = e.nextElement(); if (entry.getName().endsWith(".jar")) { final File file = copyFile(jar, entry, temp); urls.add(new URL("file:" + file.getAbsolutePath())); } } return urls; } private static File copyFile(final JarFile jar, final JarEntry entry, final File temp) throws IOException { final File file = new File(temp, entry.getName()); InputStream is = null; try { is = jar.getInputStream(entry); FileOutputStream os = null; try { + file.getParentFile().mkdirs(); os = new FileOutputStream(file); final byte[] buf = new byte[1024]; int len = is.read(buf); while (len > -1) { os.write(buf, 0, len); len = is.read(buf); } } finally { IOUtils.closeQuietly(os); } } finally { IOUtils.closeQuietly(is); } return file; } private static File createTempStorage() throws IOException { final File temp = File.createTempFile("smaller-classpath-", ".dir"); temp.delete(); temp.mkdirs(); temp.deleteOnExit(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { for (final File file : temp.listFiles()) { file.delete(); } temp.delete(); } }); return temp; } private static class FatalServerException extends RuntimeException { private static final long serialVersionUID = 4541747502527240103L; /** * @param message * @param cause */ public FatalServerException(final String message, final Throwable cause) { super(message, cause); } } }
true
true
private static File copyFile(final JarFile jar, final JarEntry entry, final File temp) throws IOException { final File file = new File(temp, entry.getName()); InputStream is = null; try { is = jar.getInputStream(entry); FileOutputStream os = null; try { os = new FileOutputStream(file); final byte[] buf = new byte[1024]; int len = is.read(buf); while (len > -1) { os.write(buf, 0, len); len = is.read(buf); } } finally { IOUtils.closeQuietly(os); } } finally { IOUtils.closeQuietly(is); } return file; }
private static File copyFile(final JarFile jar, final JarEntry entry, final File temp) throws IOException { final File file = new File(temp, entry.getName()); InputStream is = null; try { is = jar.getInputStream(entry); FileOutputStream os = null; try { file.getParentFile().mkdirs(); os = new FileOutputStream(file); final byte[] buf = new byte[1024]; int len = is.read(buf); while (len > -1) { os.write(buf, 0, len); len = is.read(buf); } } finally { IOUtils.closeQuietly(os); } } finally { IOUtils.closeQuietly(is); } return file; }
diff --git a/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/services/site/SiteBean.java b/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/services/site/SiteBean.java index 0b25154..34c9382 100644 --- a/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/services/site/SiteBean.java +++ b/tool/sakai-sdata-impl/src/main/java/org/sakaiproject/sdata/services/site/SiteBean.java @@ -1,328 +1,324 @@ /********************************************************************************** * $URL: https://source.sakaiproject.org/contrib/tfd/trunk/sdata/sdata-tool/impl/src/java/org/sakaiproject/sdata/tool/JCRDumper.java $ * $Id: JCRDumper.java 45207 2008-02-01 19:01:06Z [email protected] $ *********************************************************************************** * * Copyright (c) 2008 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.sdata.services.site; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.AuthzGroupService; import org.sakaiproject.authz.api.Role; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.sdata.tool.api.ServiceDefinition; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.api.SiteService.SelectionType; import org.sakaiproject.site.api.SiteService.SortType; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.tool.api.Tool; /** * TODO Javadoc * * @author */ public class SiteBean implements ServiceDefinition { private List<Site> mysites; private Session currentSession; private List<Map> MyMappedSites = new ArrayList<Map>(); private Map<String, Object> map2 = new HashMap<String, Object>();; private static final Log log = LogFactory.getLog(SiteBean.class); /** * TODO Javadoc * * @param sessionManager * @param siteService */ public SiteBean(SessionManager sessionManager, SiteService siteService, AuthzGroupService authzGroupService, String siteId) { boolean siteExists = true; String status = "900"; ArrayList<HashMap<String, Object>> arlpages = new ArrayList<HashMap<String, Object>>(); String curUser = sessionManager.getCurrentSessionUserId(); /* * Determine the sites the current user is a member of */ setCurrentSession(sessionManager.getCurrentSession()); setMysites((List<Site>) siteService.getSites(SelectionType.ACCESS, null, null, null, SortType.TITLE_ASC, null)); try { mysites.add(0, (siteService.getSite(siteService.getUserSiteId(currentSession .getUserId())))); } catch (IdUnusedException e) { e.printStackTrace(); } - for (Site site : mysites) - { - log.error(site.getTitle() + " - " + site.getId()); - } /* * See whether the user is allowed to see this page */ try { Site theSite = siteService.getSite(siteId); boolean member = false; map2.put("title", theSite.getTitle()); map2.put("id", siteId); if (!theSite.isPublished()) { status = "903"; } for (Site site : mysites) { if (site.getId().equals(siteId)) { member = true; } } if (member == false) { status = "902"; if (theSite.isAllowed(curUser, "read")) { status = "904"; member = true; } else if (theSite.isJoinable()) { status = "905"; } } int number = 0; if (member) { List<SitePage> pages = (List<SitePage>) theSite.getOrderedPages(); for (SitePage page : pages) { number++; HashMap<String, Object> mpages = new HashMap<String, Object>(); mpages.put("name", page.getTitle()); mpages.put("layout", page.getLayoutTitle()); mpages.put("number", number); mpages.put("popup", page.isPopUp()); ArrayList<HashMap<String, Object>> arltools = new ArrayList<HashMap<String, Object>>(); List<ToolConfiguration> lst = (List<ToolConfiguration>) page .getTools(); mpages.put("iconclass", "icon-" + lst.get(0).getToolId().replaceAll("[.]", "-")); for (ToolConfiguration conf : lst) { HashMap<String, Object> tool = new HashMap<String, Object>(); tool.put("url", conf.getId()); Tool t = conf.getTool(); if (t != null && t.getId() != null) { tool.put("title", conf.getTool().getTitle()); } else { tool.put("title", page.getTitle()); } arltools.add(tool); } mpages.put("tools", arltools); arlpages.add(mpages); } ArrayList<HashMap<String, String>> roles = new ArrayList<HashMap<String, String>>(); try { AuthzGroup group = authzGroupService.getAuthzGroup("/site/" + siteId); for (Object o : group.getRoles()) { Role r = (Role) o; HashMap<String, String> map = new HashMap<String, String>(); map.put("id", r.getId()); map.put("description", r.getDescription()); roles.add(map); } map2.put("roles", roles); } catch (Exception ex) { log.info("Roles undefined for " + siteId); } } } catch (IdUnusedException e) { status = "901"; e.printStackTrace(); } map2.put("status", status); map2.put("pages", arlpages); } protected class SDataSiteRole { private String id; private String description; public void setId(String id) { this.id = id; } public String getId() { return id; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } } /** * TODO Javadoc * * @param mysites */ public void setMysites(List<Site> mysites) { this.mysites = mysites; } /** * TODO Javadoc * * @return */ public List<Site> getMysites() { return mysites; } /** * TODO Javadoc * * @param currentSession */ public void setCurrentSession(Session currentSession) { this.currentSession = currentSession; } /** * TODO Javadoc * * @return */ public Session getCurrentSession() { return currentSession; } /* * (non-Javadoc) * * @see org.sakaiproject.sdata.tool.api.ServiceDefinition#getResponseMap() */ public Map<String, Object> getResponseMap() { return map2; } /** * TODO Javadoc * * @param myMappedSites */ public void setMyMappedSites(List<Map> myMappedSites) { MyMappedSites = myMappedSites; } /** * TODO Javadoc * * @return */ public List<Map> getMyMappedSites() { return MyMappedSites; } }
true
true
public SiteBean(SessionManager sessionManager, SiteService siteService, AuthzGroupService authzGroupService, String siteId) { boolean siteExists = true; String status = "900"; ArrayList<HashMap<String, Object>> arlpages = new ArrayList<HashMap<String, Object>>(); String curUser = sessionManager.getCurrentSessionUserId(); /* * Determine the sites the current user is a member of */ setCurrentSession(sessionManager.getCurrentSession()); setMysites((List<Site>) siteService.getSites(SelectionType.ACCESS, null, null, null, SortType.TITLE_ASC, null)); try { mysites.add(0, (siteService.getSite(siteService.getUserSiteId(currentSession .getUserId())))); } catch (IdUnusedException e) { e.printStackTrace(); } for (Site site : mysites) { log.error(site.getTitle() + " - " + site.getId()); } /* * See whether the user is allowed to see this page */ try { Site theSite = siteService.getSite(siteId); boolean member = false; map2.put("title", theSite.getTitle()); map2.put("id", siteId); if (!theSite.isPublished()) { status = "903"; } for (Site site : mysites) { if (site.getId().equals(siteId)) { member = true; } } if (member == false) { status = "902"; if (theSite.isAllowed(curUser, "read")) { status = "904"; member = true; } else if (theSite.isJoinable()) { status = "905"; } } int number = 0; if (member) { List<SitePage> pages = (List<SitePage>) theSite.getOrderedPages(); for (SitePage page : pages) { number++; HashMap<String, Object> mpages = new HashMap<String, Object>(); mpages.put("name", page.getTitle()); mpages.put("layout", page.getLayoutTitle()); mpages.put("number", number); mpages.put("popup", page.isPopUp()); ArrayList<HashMap<String, Object>> arltools = new ArrayList<HashMap<String, Object>>(); List<ToolConfiguration> lst = (List<ToolConfiguration>) page .getTools(); mpages.put("iconclass", "icon-" + lst.get(0).getToolId().replaceAll("[.]", "-")); for (ToolConfiguration conf : lst) { HashMap<String, Object> tool = new HashMap<String, Object>(); tool.put("url", conf.getId()); Tool t = conf.getTool(); if (t != null && t.getId() != null) { tool.put("title", conf.getTool().getTitle()); } else { tool.put("title", page.getTitle()); } arltools.add(tool); } mpages.put("tools", arltools); arlpages.add(mpages); } ArrayList<HashMap<String, String>> roles = new ArrayList<HashMap<String, String>>(); try { AuthzGroup group = authzGroupService.getAuthzGroup("/site/" + siteId); for (Object o : group.getRoles()) { Role r = (Role) o; HashMap<String, String> map = new HashMap<String, String>(); map.put("id", r.getId()); map.put("description", r.getDescription()); roles.add(map); } map2.put("roles", roles); } catch (Exception ex) { log.info("Roles undefined for " + siteId); } } } catch (IdUnusedException e) { status = "901"; e.printStackTrace(); } map2.put("status", status); map2.put("pages", arlpages); }
public SiteBean(SessionManager sessionManager, SiteService siteService, AuthzGroupService authzGroupService, String siteId) { boolean siteExists = true; String status = "900"; ArrayList<HashMap<String, Object>> arlpages = new ArrayList<HashMap<String, Object>>(); String curUser = sessionManager.getCurrentSessionUserId(); /* * Determine the sites the current user is a member of */ setCurrentSession(sessionManager.getCurrentSession()); setMysites((List<Site>) siteService.getSites(SelectionType.ACCESS, null, null, null, SortType.TITLE_ASC, null)); try { mysites.add(0, (siteService.getSite(siteService.getUserSiteId(currentSession .getUserId())))); } catch (IdUnusedException e) { e.printStackTrace(); } /* * See whether the user is allowed to see this page */ try { Site theSite = siteService.getSite(siteId); boolean member = false; map2.put("title", theSite.getTitle()); map2.put("id", siteId); if (!theSite.isPublished()) { status = "903"; } for (Site site : mysites) { if (site.getId().equals(siteId)) { member = true; } } if (member == false) { status = "902"; if (theSite.isAllowed(curUser, "read")) { status = "904"; member = true; } else if (theSite.isJoinable()) { status = "905"; } } int number = 0; if (member) { List<SitePage> pages = (List<SitePage>) theSite.getOrderedPages(); for (SitePage page : pages) { number++; HashMap<String, Object> mpages = new HashMap<String, Object>(); mpages.put("name", page.getTitle()); mpages.put("layout", page.getLayoutTitle()); mpages.put("number", number); mpages.put("popup", page.isPopUp()); ArrayList<HashMap<String, Object>> arltools = new ArrayList<HashMap<String, Object>>(); List<ToolConfiguration> lst = (List<ToolConfiguration>) page .getTools(); mpages.put("iconclass", "icon-" + lst.get(0).getToolId().replaceAll("[.]", "-")); for (ToolConfiguration conf : lst) { HashMap<String, Object> tool = new HashMap<String, Object>(); tool.put("url", conf.getId()); Tool t = conf.getTool(); if (t != null && t.getId() != null) { tool.put("title", conf.getTool().getTitle()); } else { tool.put("title", page.getTitle()); } arltools.add(tool); } mpages.put("tools", arltools); arlpages.add(mpages); } ArrayList<HashMap<String, String>> roles = new ArrayList<HashMap<String, String>>(); try { AuthzGroup group = authzGroupService.getAuthzGroup("/site/" + siteId); for (Object o : group.getRoles()) { Role r = (Role) o; HashMap<String, String> map = new HashMap<String, String>(); map.put("id", r.getId()); map.put("description", r.getDescription()); roles.add(map); } map2.put("roles", roles); } catch (Exception ex) { log.info("Roles undefined for " + siteId); } } } catch (IdUnusedException e) { status = "901"; e.printStackTrace(); } map2.put("status", status); map2.put("pages", arlpages); }
diff --git a/src/org/opensolaris/opengrok/history/ClearCaseRepository.java b/src/org/opensolaris/opengrok/history/ClearCaseRepository.java index ab47605..fadf356 100644 --- a/src/org/opensolaris/opengrok/history/ClearCaseRepository.java +++ b/src/org/opensolaris/opengrok/history/ClearCaseRepository.java @@ -1,328 +1,330 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ package org.opensolaris.opengrok.history; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.logging.Level; import org.opensolaris.opengrok.OpenGrokLogger; /** * Access to a ClearCase repository. * */ public class ClearCaseRepository extends Repository { private boolean verbose; /** * Creates a new instance of ClearCaseRepository */ public ClearCaseRepository() { } /** * Get the name of the ClearCase command that should be used * @return the name of the cleartool command in use */ private String getCommand() { return System.getProperty("org.opensolaris.opengrok.history.ClearCase", "cleartool"); } /** * Use verbose log messages, or just the summary * @return true if verbose log messages are used for this repository */ public boolean isVerbose() { return verbose; } /** * Specify if verbose log messages or just the summary should be used * @param verbose set to true if verbose messages should be used */ public void setVerbose(boolean verbose) { this.verbose = verbose; } Process getHistoryLogProcess(File file) throws IOException { String abs = file.getAbsolutePath(); String filename = ""; String directoryName = getDirectoryName(); if (abs.length() > directoryName.length()) { filename = abs.substring(directoryName.length() + 1); } ArrayList<String> argv = new ArrayList<String>(); argv.add(getCommand()); argv.add("lshistory"); if (file.isDirectory()) { argv.add("-dir"); } argv.add("-fmt"); argv.add("%e\n%Nd\n%Fu (%u)\n%Vn\n%Nc\n.\n"); argv.add(filename); ProcessBuilder pb = new ProcessBuilder(argv); File directory = new File(getDirectoryName()); pb.directory(directory); return pb.start(); } public InputStream getHistoryGet(String parent, String basename, String rev) { InputStream ret = null; String directoryName = getDirectoryName(); File directory = new File(directoryName); String filename = (new File(parent, basename)).getAbsolutePath().substring(directoryName.length() + 1); Process process = null; try { final File tmp = File.createTempFile("opengrok", "tmp"); String tmpName = tmp.getAbsolutePath(); // cleartool can't get to a previously existing file if (tmp.exists()) { if (!tmp.delete()) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to remove temporary file used by history cache"); } } String decorated = filename + "@@" + rev; String argv[] = {getCommand(), "get", "-to", tmpName, decorated}; process = Runtime.getRuntime().exec(argv, null, directory); drainStream(process.getInputStream()); - process.exitValue(); + if(waitFor(process) != 0) { + return null; + } ret = new BufferedInputStream(new FileInputStream(tmp) { public void close() throws IOException { super.close(); // delete the temporary file on close if (!tmp.delete()) { // failed, lets do the next best thing then .. // delete it on JVM exit tmp.deleteOnExit(); } } }); } catch (Exception exp) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp); } finally { // Clean up zombie-processes... if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException exp) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; } /** * Drain all data from a stream and close it. * @param in the stream to drain * @throws IOException if an I/O error occurs */ private static void drainStream(InputStream in) throws IOException { while (true) { long skipped = in.skip(32768L); if (skipped == 0) { // No bytes skipped, check if we've reached EOF with read() if (in.read() == -1) { break; } } } in.close(); } public Class<? extends HistoryParser> getHistoryParser() { return ClearCaseHistoryParser.class; } public Class<? extends HistoryParser> getDirectoryHistoryParser() { return ClearCaseHistoryParser.class; } /** * Annotate the specified file/revision. * * @param file file to annotate * @param revision revision to annotate * @return file annotation */ public Annotation annotate(File file, String revision) throws Exception { ArrayList<String> argv = new ArrayList<String>(); argv.add(getCommand()); argv.add("annotate"); argv.add("-nheader"); argv.add("-out"); argv.add("-"); argv.add("-f"); argv.add("-fmt"); argv.add("%u|%Vn|"); if (revision != null) { argv.add(revision); } argv.add(file.getName()); ProcessBuilder pb = new ProcessBuilder(argv); pb.directory(file.getParentFile()); Process process = null; BufferedReader in = null; try { process = pb.start(); in = new BufferedReader(new InputStreamReader(process.getInputStream())); Annotation a = new Annotation(file.getName()); String line; int lineno = 0; while ((line = in.readLine()) != null) { ++lineno; String parts[] = line.split("\\|"); String aAuthor = parts[0]; String aRevision = parts[1]; aRevision = aRevision.replace('\\', '/'); a.addLine(aRevision, aAuthor, true); } return a; } finally { if (in != null) { try { in.close(); } catch (IOException exp) { // ignore } } if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException e) { process.destroy(); } } } } public boolean fileHasAnnotation(File file) { return true; } public boolean isCacheable() { return true; } private int waitFor(Process process) { do { try { return process.waitFor(); } catch (InterruptedException exp) { } } while (true); } public void update() throws Exception { Process process = null; BufferedReader in = null; try { File directory = new File(getDirectoryName()); // Check if this is a snapshot view String[] argv = {getCommand(), "catcs"}; process = Runtime.getRuntime().exec(argv, null, directory); in = new BufferedReader(new InputStreamReader(process.getInputStream())); boolean snapshot = false; String line; while (!snapshot && (line = in.readLine()) != null) { snapshot = line.startsWith("load"); } if (waitFor(process) != 0) { return; } in.close(); in = null; // To avoid double close in finally clause if (snapshot) { // It is a snapshot view, we need to update it manually argv = new String[]{getCommand(), "update", "-overwrite", "-f"}; process = Runtime.getRuntime().exec(argv, null, directory); in = new BufferedReader(new InputStreamReader(process.getInputStream())); // consume output while ((line = in.readLine()) != null) { // do nothing } if (waitFor(process) != 0) { return; } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException e) { process.destroy(); } } } } public boolean fileHasHistory(File file) { // Todo: is there a cheap test for whether ClearCase has history // available for a file? // Otherwise, this is harmless, since ClearCase's commands will just // print nothing if there is no history. return true; } @Override boolean isRepositoryFor( File file) { // if the parent contains a file named "view.dat" or // the parent is named "vobs" File f = new File(file, "view.dat"); if (f.exists() && f.isDirectory()) { return true; } else { return file.isDirectory() && file.getName().equalsIgnoreCase("vobs"); } } }
true
true
public InputStream getHistoryGet(String parent, String basename, String rev) { InputStream ret = null; String directoryName = getDirectoryName(); File directory = new File(directoryName); String filename = (new File(parent, basename)).getAbsolutePath().substring(directoryName.length() + 1); Process process = null; try { final File tmp = File.createTempFile("opengrok", "tmp"); String tmpName = tmp.getAbsolutePath(); // cleartool can't get to a previously existing file if (tmp.exists()) { if (!tmp.delete()) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to remove temporary file used by history cache"); } } String decorated = filename + "@@" + rev; String argv[] = {getCommand(), "get", "-to", tmpName, decorated}; process = Runtime.getRuntime().exec(argv, null, directory); drainStream(process.getInputStream()); process.exitValue(); ret = new BufferedInputStream(new FileInputStream(tmp) { public void close() throws IOException { super.close(); // delete the temporary file on close if (!tmp.delete()) { // failed, lets do the next best thing then .. // delete it on JVM exit tmp.deleteOnExit(); } } }); } catch (Exception exp) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp); } finally { // Clean up zombie-processes... if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException exp) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; }
public InputStream getHistoryGet(String parent, String basename, String rev) { InputStream ret = null; String directoryName = getDirectoryName(); File directory = new File(directoryName); String filename = (new File(parent, basename)).getAbsolutePath().substring(directoryName.length() + 1); Process process = null; try { final File tmp = File.createTempFile("opengrok", "tmp"); String tmpName = tmp.getAbsolutePath(); // cleartool can't get to a previously existing file if (tmp.exists()) { if (!tmp.delete()) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to remove temporary file used by history cache"); } } String decorated = filename + "@@" + rev; String argv[] = {getCommand(), "get", "-to", tmpName, decorated}; process = Runtime.getRuntime().exec(argv, null, directory); drainStream(process.getInputStream()); if(waitFor(process) != 0) { return null; } ret = new BufferedInputStream(new FileInputStream(tmp) { public void close() throws IOException { super.close(); // delete the temporary file on close if (!tmp.delete()) { // failed, lets do the next best thing then .. // delete it on JVM exit tmp.deleteOnExit(); } } }); } catch (Exception exp) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp); } finally { // Clean up zombie-processes... if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException exp) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; }
diff --git a/com/mraof/minestuck/client/model/ModelGristWidget.java b/com/mraof/minestuck/client/model/ModelGristWidget.java index d990cd91..d09cf45e 100644 --- a/com/mraof/minestuck/client/model/ModelGristWidget.java +++ b/com/mraof/minestuck/client/model/ModelGristWidget.java @@ -1,36 +1,36 @@ package com.mraof.minestuck.client.model; import net.minecraft.client.model.ModelRenderer; public class ModelGristWidget extends ModelMachine { //fields ModelRenderer Base; public ModelGristWidget() { textureWidth = 128; textureHeight = 128; Base = new ModelRenderer(this, 0, 0); - Base.addBox(0F, -1F, 8F, 32, 8, 16); + Base.addBox(0F, 0F, 8F, 32, 8, 16); Base.setRotationPoint(0F, -8F, 0F); Base.setTextureSize(128, 128); Base.mirror = true; setRotation(Base, 0F, 0F, 0F); } @Override public void render(float scale) { Base.render(scale); } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } }
true
true
public ModelGristWidget() { textureWidth = 128; textureHeight = 128; Base = new ModelRenderer(this, 0, 0); Base.addBox(0F, -1F, 8F, 32, 8, 16); Base.setRotationPoint(0F, -8F, 0F); Base.setTextureSize(128, 128); Base.mirror = true; setRotation(Base, 0F, 0F, 0F); }
public ModelGristWidget() { textureWidth = 128; textureHeight = 128; Base = new ModelRenderer(this, 0, 0); Base.addBox(0F, 0F, 8F, 32, 8, 16); Base.setRotationPoint(0F, -8F, 0F); Base.setTextureSize(128, 128); Base.mirror = true; setRotation(Base, 0F, 0F, 0F); }
diff --git a/alertscape/install-wizard/src/com/alertscape/wizard/client/Wizard.java b/alertscape/install-wizard/src/com/alertscape/wizard/client/Wizard.java index fca96f5..e173d9a 100644 --- a/alertscape/install-wizard/src/com/alertscape/wizard/client/Wizard.java +++ b/alertscape/install-wizard/src/com/alertscape/wizard/client/Wizard.java @@ -1,167 +1,171 @@ /** * */ package com.alertscape.wizard.client; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DecoratorPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Tree; import com.google.gwt.user.client.ui.TreeItem; import com.google.gwt.user.client.ui.TreeListener; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * @author josh * */ public class Wizard extends Composite implements WizardStateListener { private List<WizardStep> steps; private SimplePanel stepContentPanel; private Tree stepsTree; private Map<TreeItem, WizardStep> treeItemToStep; private int currentStep = -1; private Button prevButton; private Button nextButton; public Wizard(List<WizardStep> steps) { VerticalPanel mainPanel = new VerticalPanel(); initWidget(mainPanel); nextButton = new Button("Next", new ClickListener() { public void onClick(Widget sender) { + if(currentStep == Wizard.this.steps.size()-1) { + // Finish + return; + } currentStep++; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); prevButton = new Button("Previous", new ClickListener() { public void onClick(Widget sender) { currentStep--; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); stepContentPanel = new SimplePanel(); stepsTree = new Tree(); stepsTree.addTreeListener(new WizardTreeListener()); HorizontalPanel contentPanel = new HorizontalPanel(); contentPanel.add(stepsTree); DecoratorPanel contentDecorator = new DecoratorPanel(); contentDecorator.setWidget(stepContentPanel); contentPanel.add(contentDecorator); mainPanel.add(contentPanel); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.add(prevButton); buttonPanel.add(nextButton); mainPanel.add(buttonPanel); treeItemToStep = new HashMap<TreeItem, WizardStep>(); setSteps(steps); stepsTree.setSelectedItem(stepsTree.getItem(0)); } /** * @return the steps */ public List<WizardStep> getSteps() { return steps; } /** * @param steps * the steps to set */ public void setSteps(List<WizardStep> steps) { this.steps = steps; if (this.steps != null) { for (int i = 0; i < steps.size(); i++) { WizardStep wizardStep = steps.get(i); wizardStep.getContent().setWizardStateListener(this); TreeItem treeItem = stepsTree.addItem((i + 1) + ". " + wizardStep.getLabel()); treeItemToStep.put(treeItem, wizardStep); } } else { stepsTree.removeItems(); } currentStep = 0; } /** * @return the contentPanel */ public SimplePanel getStepContentPanel() { return stepContentPanel; } /** * @param contentPanel * the contentPanel to set */ public void setStepContentPanel(SimplePanel contentPanel) { this.stepContentPanel = contentPanel; } public void handeNotProceedable() { nextButton.setEnabled(false); } public void handleProceedable() { nextButton.setEnabled(true); } /** * @author josh * */ private final class WizardTreeListener implements TreeListener { public void onTreeItemSelected(TreeItem item) { WizardStep step = treeItemToStep.get(item); if (step != null) { if(stepContentPanel.getWidget() == step.getContent()) { return; } int stepIndex = steps.indexOf(step); currentStep = stepIndex; if (currentStep == 0) { prevButton.setEnabled(false); } else { prevButton.setEnabled(true); } if(currentStep == steps.size() - 1) { nextButton.setText("Finish"); } else { nextButton.setText("Next"); } nextButton.setEnabled(false); stepContentPanel.setWidget(step.getContent()); step.getContent().onShow(); } else { stepContentPanel.setWidget(new HTML("&nbsp;")); } } public void onTreeItemStateChanged(TreeItem item) { } } }
true
true
public Wizard(List<WizardStep> steps) { VerticalPanel mainPanel = new VerticalPanel(); initWidget(mainPanel); nextButton = new Button("Next", new ClickListener() { public void onClick(Widget sender) { currentStep++; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); prevButton = new Button("Previous", new ClickListener() { public void onClick(Widget sender) { currentStep--; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); stepContentPanel = new SimplePanel(); stepsTree = new Tree(); stepsTree.addTreeListener(new WizardTreeListener()); HorizontalPanel contentPanel = new HorizontalPanel(); contentPanel.add(stepsTree); DecoratorPanel contentDecorator = new DecoratorPanel(); contentDecorator.setWidget(stepContentPanel); contentPanel.add(contentDecorator); mainPanel.add(contentPanel); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.add(prevButton); buttonPanel.add(nextButton); mainPanel.add(buttonPanel); treeItemToStep = new HashMap<TreeItem, WizardStep>(); setSteps(steps); stepsTree.setSelectedItem(stepsTree.getItem(0)); }
public Wizard(List<WizardStep> steps) { VerticalPanel mainPanel = new VerticalPanel(); initWidget(mainPanel); nextButton = new Button("Next", new ClickListener() { public void onClick(Widget sender) { if(currentStep == Wizard.this.steps.size()-1) { // Finish return; } currentStep++; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); prevButton = new Button("Previous", new ClickListener() { public void onClick(Widget sender) { currentStep--; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); stepContentPanel = new SimplePanel(); stepsTree = new Tree(); stepsTree.addTreeListener(new WizardTreeListener()); HorizontalPanel contentPanel = new HorizontalPanel(); contentPanel.add(stepsTree); DecoratorPanel contentDecorator = new DecoratorPanel(); contentDecorator.setWidget(stepContentPanel); contentPanel.add(contentDecorator); mainPanel.add(contentPanel); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.add(prevButton); buttonPanel.add(nextButton); mainPanel.add(buttonPanel); treeItemToStep = new HashMap<TreeItem, WizardStep>(); setSteps(steps); stepsTree.setSelectedItem(stepsTree.getItem(0)); }
diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/RunTestsLocallyAction.java b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/RunTestsLocallyAction.java index 61c0746..7a3b9f3 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/RunTestsLocallyAction.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/RunTestsLocallyAction.java @@ -1,467 +1,464 @@ package fi.helsinki.cs.tmc.actions; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fi.helsinki.cs.tmc.data.Exercise; import fi.helsinki.cs.tmc.data.TestCaseResult; import fi.helsinki.cs.tmc.model.CourseDb; import fi.helsinki.cs.tmc.model.ProjectMediator; import fi.helsinki.cs.tmc.model.TmcProjectInfo; import fi.helsinki.cs.tmc.testrunner.StackTraceSerializer; import fi.helsinki.cs.tmc.testrunner.TestCase; import fi.helsinki.cs.tmc.testrunner.TestCaseList; import fi.helsinki.cs.tmc.testscanner.TestMethod; import fi.helsinki.cs.tmc.testscanner.TestScanner; import fi.helsinki.cs.tmc.ui.ConvenientDialogDisplayer; import fi.helsinki.cs.tmc.ui.TestResultDisplayer; import fi.helsinki.cs.tmc.utilities.BgTask; import fi.helsinki.cs.tmc.utilities.BgTaskListener; import fi.helsinki.cs.tmc.utilities.ExceptionUtils; import fi.helsinki.cs.tmc.utilities.maven.MavenRunBuilder; import fi.helsinki.cs.tmc.utilities.process.ProcessResult; import fi.helsinki.cs.tmc.utilities.process.ProcessRunner; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.logging.Logger; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.tools.ant.module.api.support.ActionUtils; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.platform.JavaPlatform; import org.netbeans.api.project.Project; import org.netbeans.spi.java.classpath.ClassPathProvider; import org.netbeans.spi.java.classpath.support.ClassPathSupport; import org.openide.execution.ExecutorTask; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.nodes.Node; import org.openide.util.NbBundle.Messages; import org.openide.windows.IOProvider; import org.openide.windows.InputOutput; @Messages("CTL_RunTestsLocallyExerciseAction=Run &tests locally") public class RunTestsLocallyAction extends AbstractExerciseSensitiveAction { private static final String MAVEN_TEST_RUN_GOAL = "fi.helsinki.cs.tmc:tmc-maven-plugin:1.3:test"; private static final Logger log = Logger.getLogger(RunTestsLocallyAction.class.getName()); private CourseDb courseDb; private ProjectMediator projectMediator; private TestResultDisplayer resultDisplayer; private ConvenientDialogDisplayer dialogDisplayer; private SubmitExerciseAction submitAction; public RunTestsLocallyAction() { this.courseDb = CourseDb.getInstance(); this.projectMediator = ProjectMediator.getInstance(); this.resultDisplayer = TestResultDisplayer.getInstance(); this.dialogDisplayer = ConvenientDialogDisplayer.getDefault(); this.submitAction = new SubmitExerciseAction(); putValue("noIconInMenu", Boolean.TRUE); } @Override protected CourseDb getCourseDb() { return courseDb; } @Override protected ProjectMediator getProjectMediator() { return projectMediator; } @Override protected void performAction(Node[] nodes) { performAction(projectsFromNodes(nodes).toArray(new Project[0])); } private void performAction(Project ... projects) { projectMediator.saveAllFiles(); for (final Project project : projects) { final TmcProjectInfo projectInfo = projectMediator.wrapProject(project); BgTask.start("Compiling project", startCompilingProject(projectInfo), new BgTaskListener<Integer>() { @Override public void bgTaskReady(Integer result) { if (result == 0) { startRunningTests(projectInfo); } else { dialogDisplayer.displayError("The code did not compile."); } } @Override public void bgTaskFailed(Throwable ex) { dialogDisplayer.displayError("Failed to compile the code."); } @Override public void bgTaskCancelled() { } }); } } private Callable<Integer> executorTaskToCallable(final ExecutorTask et) { return new Callable<Integer>() { @Override public Integer call() throws Exception { return et.result(); } }; } private Callable<Integer> startCompilingProject(TmcProjectInfo projectInfo) { switch (projectInfo.getProjectType()) { case JAVA_SIMPLE: return startCompilingAntProject(projectInfo); case JAVA_MAVEN: return startCompilingMavenProject(projectInfo); default: throw new IllegalArgumentException("Unknown project type: " + projectInfo.getProjectType()); } } private Callable<Integer> startCompilingAntProject(TmcProjectInfo projectInfo) { Project project = projectInfo.getProject(); FileObject buildScript = project.getProjectDirectory().getFileObject("build.xml"); if (buildScript == null) { throw new RuntimeException("Project has no build.xml"); } ExecutorTask task; try { task = ActionUtils.runTarget(buildScript, new String[] { "compile-test" }, null); return executorTaskToCallable(task); } catch (IOException ex) { throw ExceptionUtils.toRuntimeException(ex); } } private Callable<Integer> startCompilingMavenProject(TmcProjectInfo projectInfo) { File projectDir = projectInfo.getProjectDirAsFile(); String goal = "test-compile"; final InputOutput inOut = IOProvider.getDefault().getIO(projectInfo.getProjectName(), false); final ProcessRunner runner = new MavenRunBuilder() .setProjectDir(projectDir) .addGoal(goal) .setIO(inOut) .createProcessRunner(); return new Callable<Integer>() { @Override public Integer call() throws Exception { try { ProcessResult result = runner.call(); int ret = result.statusCode; if (ret != 0) { inOut.select(); } return ret; } catch (Exception ex) { inOut.select(); throw ex; } } }; } private void startRunningTests(TmcProjectInfo projectInfo) { switch (projectInfo.getProjectType()) { case JAVA_SIMPLE: startRunningSimpleProjectTests(projectInfo); break; case JAVA_MAVEN: startRunningMavenProjectTests(projectInfo); break; default: throw new IllegalArgumentException("Unknown project type: " + projectInfo.getProjectType()); } } private void startRunningSimpleProjectTests(TmcProjectInfo projectInfo) { FileObject testDir = findTestDir(projectInfo); if (testDir == null) { dialogDisplayer.displayError("No test directory in project"); return; } List<TestMethod> tests = findProjectTests(projectInfo, testDir); startRunningSimpleProjectTests(projectInfo, testDir, tests); } private void startRunningMavenProjectTests(final TmcProjectInfo projectInfo) { final File projectDir = projectInfo.getProjectDirAsFile(); String goal = MAVEN_TEST_RUN_GOAL; Map<String, String> props = new HashMap<String, String>(); InputOutput inOut = getIoTab(); Integer memLimit = getMemoryLimit(projectInfo.getProject()); if (memLimit != null) { props.put("tmc.test.jvmOpts", "-Xmx" + memLimit + "m"); } final ProcessRunner runner = new MavenRunBuilder() .setProjectDir(projectDir) .addGoal(goal) .setProperties(props) .setIO(inOut) .createProcessRunner(); BgTask.start("Running tests", runner, new BgTaskListener<ProcessResult>() { @Override public void bgTaskReady(ProcessResult processResult) { File resultPath = new File( projectDir.getPath() + File.separator + "target" + File.separator + "test_output.txt" ); List<TestCaseResult> results; try { String resultJson = FileUtils.readFileToString(resultPath); results = parseTestResults(resultJson); } catch (Exception ex) { dialogDisplayer.displayError("Failed to read test results", ex); return; } if (resultDisplayer.showLocalRunResult(results)) { submitAction.performAction(projectInfo.getProject()); } } @Override public void bgTaskCancelled() { } @Override public void bgTaskFailed(Throwable ex) { dialogDisplayer.displayError("Failed to run tests:\n" + ex.getMessage()); } }); } private List<TestMethod> findProjectTests(TmcProjectInfo projectInfo, FileObject testDir) { TestScanner scanner = new TestScanner(); scanner.setClassPath(getTestClassPath(projectInfo, testDir).toString(ClassPath.PathConversionMode.WARN)); scanner.addSource(FileUtil.toFile(testDir)); return scanner.findTests(); } private FileObject findTestDir(TmcProjectInfo projectInfo) { // Ideally we'd get these paths from NB, but let's assume the conventional ones for now. FileObject root = projectInfo.getProjectDir(); switch (projectInfo.getProjectType()) { case JAVA_SIMPLE: return root.getFileObject("test"); case JAVA_MAVEN: return getSubdir(root, "src", "test", "java"); default: throw new IllegalArgumentException("Unknown project type"); } } private FileObject getSubdir(FileObject fo, String ... subdirs) { for (String s : subdirs) { if (fo == null) { return null; } fo = fo.getFileObject(s); } return fo; } private void startRunningSimpleProjectTests(TmcProjectInfo projectInfo, FileObject testDir, List<TestMethod> testMethods) { final Project project = projectInfo.getProject(); File tempFile; try { tempFile = File.createTempFile("tmc_test_results", ".txt"); } catch (IOException ex) { dialogDisplayer.displayError("Failed to create temporary file for test results.", ex); return; } try { ArrayList<String> args = new ArrayList<String>(); args.add("-Dtmc.test_class_dir=" + FileUtil.toFile(testDir).getAbsolutePath()); args.add("-Dtmc.results_file=" + tempFile.getAbsolutePath()); Integer memoryLimit = getMemoryLimit(project); if (memoryLimit != null) { args.add("-Xmx" + memoryLimit + "M"); } args.add("fi.helsinki.cs.tmc.testrunner.Main"); for (int i = 0; i < testMethods.size(); ++i) { args.add(testMethods.get(i).toString()); } InputOutput inOut = getIoTab(); final File tempFileAsFinal = tempFile; ClassPath classPath = getTestClassPath(projectInfo, testDir); runJavaProcessInProject(projectInfo, classPath, "Running tests", args, inOut, new BgTaskListener<ProcessResult>() { @Override public void bgTaskReady(ProcessResult result) { log.info("Test run standard output:"); log.info(result.output); log.info("Test run error output:"); log.info(result.errorOutput); if (result.statusCode != 0) { log.info("Failed to run tests. Status code: " + result.statusCode); dialogDisplayer.displayError("Failed to run tests.\n" + result.errorOutput); tempFileAsFinal.delete(); return; } String resultJson; try { resultJson = FileUtils.readFileToString(tempFileAsFinal, "UTF-8"); } catch (IOException ex) { dialogDisplayer.displayError("Failed to read test results", ex); return; } finally { tempFileAsFinal.delete(); } List<TestCaseResult> results; try { results = parseTestResults(resultJson); - if (resultDisplayer.showLocalRunResult(results)) { - submitAction.performAction(project); - } } catch (Exception e) { dialogDisplayer.displayError("Failed to read test results:\n" + e.getMessage()); return; } if (resultDisplayer.showLocalRunResult(results)) { submitAction.performAction(project); } } @Override public void bgTaskCancelled() { tempFileAsFinal.delete(); } @Override public void bgTaskFailed(Throwable ex) { tempFileAsFinal.delete(); dialogDisplayer.displayError("Failed to run tests", ex); } }); } catch (Exception ex) { tempFile.delete(); dialogDisplayer.displayError("Failed to run tests", ex); } } private List<TestCaseResult> parseTestResults(String json) { Gson gson = new GsonBuilder() .registerTypeAdapter(StackTraceElement.class, new StackTraceSerializer()) .create(); TestCaseList testCaseRecords = gson.fromJson(json, TestCaseList.class); if (testCaseRecords == null) { String msg = "Empty result from test runner"; log.warning(msg); throw new IllegalArgumentException(msg); } List<TestCaseResult> results = new ArrayList<TestCaseResult>(); for (TestCase tc : testCaseRecords) { results.add(TestCaseResult.fromTestCaseRecord(tc)); } return results; } private void runJavaProcessInProject(TmcProjectInfo projectInfo, ClassPath classPath, String taskName, List<String> args, InputOutput inOut, BgTaskListener<ProcessResult> listener) { FileObject projectDir = projectInfo.getProjectDir(); JavaPlatform platform = JavaPlatform.getDefault(); // Should probably use project's configured platform instead FileObject javaExe = platform.findTool("java"); if (javaExe == null) { throw new IllegalArgumentException(); } // TMC server packages this with every exercise for our convenience. // True even for Maven exercises, at least until NB's Maven API is published. ClassPath testRunnerClassPath = getTestRunnerClassPath(projectInfo); if (testRunnerClassPath != null) { classPath = ClassPathSupport.createProxyClassPath(classPath, testRunnerClassPath); } String[] command = new String[3 + args.size()]; command[0] = FileUtil.toFile(javaExe).getAbsolutePath(); command[1] = "-cp"; command[2] = classPath.toString(ClassPath.PathConversionMode.WARN); System.arraycopy(args.toArray(new String[args.size()]), 0, command, 3, args.size()); log.info(StringUtils.join(command, ' ')); ProcessRunner runner = new ProcessRunner(command, FileUtil.toFile(projectDir), inOut); BgTask.start(taskName, runner, listener); } private ClassPath getTestClassPath(TmcProjectInfo projectInfo, FileObject testDir) { ClassPathProvider classPathProvider = projectInfo.getProject().getLookup().lookup(ClassPathProvider.class); ClassPath cp = classPathProvider.findClassPath(testDir, ClassPath.EXECUTE); if (cp == null) { throw new RuntimeException("Failed to get 'execute' classpath for project's tests"); } return cp; } private ClassPath getTestRunnerClassPath(TmcProjectInfo projectInfo) { FileObject projectDir = projectInfo.getProjectDir(); FileObject testrunnerDir = projectDir.getFileObject("lib/testrunner"); if (testrunnerDir != null) { FileObject[] files = testrunnerDir.getChildren(); ArrayList<URL> urls = new ArrayList<URL>(); for (FileObject file : files) { URL url = FileUtil.urlForArchiveOrDir(FileUtil.toFile(file)); if (url != null) { urls.add(url); } } return ClassPathSupport.createClassPath(urls.toArray(new URL[0])); } else { return null; } } private Integer getMemoryLimit(Project project) { Exercise ex = projectMediator.tryGetExerciseForProject(projectMediator.wrapProject(project), courseDb); if (ex != null) { return ex.getMemoryLimit(); } else { return null; } } @Override public String getName() { return "Run &tests locally"; } @Override protected String iconResource() { // The setting in layer.xml doesn't work with NodeAction return "org/netbeans/modules/project/ui/resources/testProject.png"; } private InputOutput getIoTab() { InputOutput inOut = IOProvider.getDefault().getIO("Test output", false); if (inOut.isClosed()) { inOut.select(); } return inOut; } }
true
true
private void startRunningSimpleProjectTests(TmcProjectInfo projectInfo, FileObject testDir, List<TestMethod> testMethods) { final Project project = projectInfo.getProject(); File tempFile; try { tempFile = File.createTempFile("tmc_test_results", ".txt"); } catch (IOException ex) { dialogDisplayer.displayError("Failed to create temporary file for test results.", ex); return; } try { ArrayList<String> args = new ArrayList<String>(); args.add("-Dtmc.test_class_dir=" + FileUtil.toFile(testDir).getAbsolutePath()); args.add("-Dtmc.results_file=" + tempFile.getAbsolutePath()); Integer memoryLimit = getMemoryLimit(project); if (memoryLimit != null) { args.add("-Xmx" + memoryLimit + "M"); } args.add("fi.helsinki.cs.tmc.testrunner.Main"); for (int i = 0; i < testMethods.size(); ++i) { args.add(testMethods.get(i).toString()); } InputOutput inOut = getIoTab(); final File tempFileAsFinal = tempFile; ClassPath classPath = getTestClassPath(projectInfo, testDir); runJavaProcessInProject(projectInfo, classPath, "Running tests", args, inOut, new BgTaskListener<ProcessResult>() { @Override public void bgTaskReady(ProcessResult result) { log.info("Test run standard output:"); log.info(result.output); log.info("Test run error output:"); log.info(result.errorOutput); if (result.statusCode != 0) { log.info("Failed to run tests. Status code: " + result.statusCode); dialogDisplayer.displayError("Failed to run tests.\n" + result.errorOutput); tempFileAsFinal.delete(); return; } String resultJson; try { resultJson = FileUtils.readFileToString(tempFileAsFinal, "UTF-8"); } catch (IOException ex) { dialogDisplayer.displayError("Failed to read test results", ex); return; } finally { tempFileAsFinal.delete(); } List<TestCaseResult> results; try { results = parseTestResults(resultJson); if (resultDisplayer.showLocalRunResult(results)) { submitAction.performAction(project); } } catch (Exception e) { dialogDisplayer.displayError("Failed to read test results:\n" + e.getMessage()); return; } if (resultDisplayer.showLocalRunResult(results)) { submitAction.performAction(project); } } @Override public void bgTaskCancelled() { tempFileAsFinal.delete(); } @Override public void bgTaskFailed(Throwable ex) { tempFileAsFinal.delete(); dialogDisplayer.displayError("Failed to run tests", ex); } }); } catch (Exception ex) { tempFile.delete(); dialogDisplayer.displayError("Failed to run tests", ex); } }
private void startRunningSimpleProjectTests(TmcProjectInfo projectInfo, FileObject testDir, List<TestMethod> testMethods) { final Project project = projectInfo.getProject(); File tempFile; try { tempFile = File.createTempFile("tmc_test_results", ".txt"); } catch (IOException ex) { dialogDisplayer.displayError("Failed to create temporary file for test results.", ex); return; } try { ArrayList<String> args = new ArrayList<String>(); args.add("-Dtmc.test_class_dir=" + FileUtil.toFile(testDir).getAbsolutePath()); args.add("-Dtmc.results_file=" + tempFile.getAbsolutePath()); Integer memoryLimit = getMemoryLimit(project); if (memoryLimit != null) { args.add("-Xmx" + memoryLimit + "M"); } args.add("fi.helsinki.cs.tmc.testrunner.Main"); for (int i = 0; i < testMethods.size(); ++i) { args.add(testMethods.get(i).toString()); } InputOutput inOut = getIoTab(); final File tempFileAsFinal = tempFile; ClassPath classPath = getTestClassPath(projectInfo, testDir); runJavaProcessInProject(projectInfo, classPath, "Running tests", args, inOut, new BgTaskListener<ProcessResult>() { @Override public void bgTaskReady(ProcessResult result) { log.info("Test run standard output:"); log.info(result.output); log.info("Test run error output:"); log.info(result.errorOutput); if (result.statusCode != 0) { log.info("Failed to run tests. Status code: " + result.statusCode); dialogDisplayer.displayError("Failed to run tests.\n" + result.errorOutput); tempFileAsFinal.delete(); return; } String resultJson; try { resultJson = FileUtils.readFileToString(tempFileAsFinal, "UTF-8"); } catch (IOException ex) { dialogDisplayer.displayError("Failed to read test results", ex); return; } finally { tempFileAsFinal.delete(); } List<TestCaseResult> results; try { results = parseTestResults(resultJson); } catch (Exception e) { dialogDisplayer.displayError("Failed to read test results:\n" + e.getMessage()); return; } if (resultDisplayer.showLocalRunResult(results)) { submitAction.performAction(project); } } @Override public void bgTaskCancelled() { tempFileAsFinal.delete(); } @Override public void bgTaskFailed(Throwable ex) { tempFileAsFinal.delete(); dialogDisplayer.displayError("Failed to run tests", ex); } }); } catch (Exception ex) { tempFile.delete(); dialogDisplayer.displayError("Failed to run tests", ex); } }
diff --git a/src/api/user/Stats.java b/src/api/user/Stats.java index b13e7a3..4b9089f 100644 --- a/src/api/user/Stats.java +++ b/src/api/user/Stats.java @@ -1,113 +1,113 @@ package api.user; /** * User's stats. * * @author Tim */ public class Stats { /** The downloaded. */ private Number downloaded; /** The joined date. */ private String joinedDate; /** The last access. */ private String lastAccess; /** The ratio from the api. Must be a string to handle the case where ratio is infinity */ private String ratio; /** * When getRatio is called for the first time we parse the ratio string into this number * and then return it for future calls */ private Number r = null; /** The required ratio. */ private Number requiredRatio; /** The uploaded. */ private Number uploaded; /** * Gets the downloaded. * * @return the downloaded */ public Number getDownloaded() { return this.downloaded; } /** * Gets the joined date. * * @return the joined date */ public String getJoinedDate() { return this.joinedDate; } /** * Gets the last access. * * @return the last access */ public String getLastAccess() { return this.lastAccess; } /** * Gets the ratio. * * @return the ratio */ public Number getRatio() { //If the ratio was the infinity character change it to Infinity //so that it can be parsed - if (r == null){ + if (r == null && ratio != null){ if (ratio.equalsIgnoreCase("\u221e")){ ratio = "Infinity"; } r = Double.parseDouble(ratio); } return r; } /** * Gets the required ratio. * * @return the required ratio */ public Number getRequiredRatio() { return this.requiredRatio; } /** * Gets the uploaded. * * @return the uploaded */ public Number getUploaded() { return this.uploaded; } /** * Gets the buffer. * * @return the buffer */ public double getBuffer() { if (getUploaded() != null && getDownloaded() != null) return getUploaded().doubleValue() - getDownloaded().doubleValue(); else return 0; } @Override public String toString() { return "Stats [getDownloaded=" + getDownloaded() + ", getJoinedDate=" + getJoinedDate() + ", getLastAccess=" + getLastAccess() + ", getRatio=" + getRatio() + ", getRequiredRatio=" + getRequiredRatio() + ", getUploaded=" + getUploaded() + ", getBuffer=" + getBuffer() + "]"; } }
true
true
public Number getRatio() { //If the ratio was the infinity character change it to Infinity //so that it can be parsed if (r == null){ if (ratio.equalsIgnoreCase("\u221e")){ ratio = "Infinity"; } r = Double.parseDouble(ratio); } return r; }
public Number getRatio() { //If the ratio was the infinity character change it to Infinity //so that it can be parsed if (r == null && ratio != null){ if (ratio.equalsIgnoreCase("\u221e")){ ratio = "Infinity"; } r = Double.parseDouble(ratio); } return r; }
diff --git a/src/main/java/org/esa/beam/meris/icol/graphgen/GraphGenMain.java b/src/main/java/org/esa/beam/meris/icol/graphgen/GraphGenMain.java index ac71fee..5dc1261 100644 --- a/src/main/java/org/esa/beam/meris/icol/graphgen/GraphGenMain.java +++ b/src/main/java/org/esa/beam/meris/icol/graphgen/GraphGenMain.java @@ -1,84 +1,85 @@ /* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.beam.meris.icol.graphgen; import org.esa.beam.framework.dataio.ProductIO; import org.esa.beam.framework.datamodel.Product; import org.esa.beam.framework.gpf.GPF; import org.esa.beam.framework.gpf.Operator; import org.esa.beam.meris.icol.meris.MerisOp; import org.esa.beam.meris.icol.tm.TmOp; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * Test tool for the {@link GraphGen} class. * <pre> * Usage: GraphGenMain <productPath> <graphmlPath> 'meris'|'landsat' [[<hideBands>] <hideProducts>] * </pre> * * @author Thomas Storm * @author Norman Fomferra */ public class GraphGenMain { static { GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis(); } public static void main(String[] args) throws IOException { if (args.length < 3) { System.out.println("Usage: GraphGenMain <productPath> <graphmlPath> 'meris'|'landsat' [[<hideBands>] <hideProducts>]"); + System.exit(1); } String productPath = args[0]; String graphmlPath = args[1]; String opSelector = args[2]; String hideBandsArg = args.length > 3 ? args[3] : null; String hideProductsArg = args.length > 4 ? args[4] : null; Operator op; if (opSelector.equalsIgnoreCase("meris")) { op = new MerisOp(); } else if (opSelector.equalsIgnoreCase("landsat")) { op = new TmOp(); } else { throw new IllegalArgumentException("argument 3 must be 'meris' or 'landsat'."); } final Product sourceProduct = ProductIO.readProduct(new File(productPath)); op.setSourceProduct(sourceProduct); final Product targetProduct = op.getTargetProduct(); FileWriter fileWriter = new FileWriter(new File(graphmlPath)); BufferedWriter writer = new BufferedWriter(fileWriter); final GraphGen graphGen = new GraphGen(); boolean hideBands = hideBandsArg != null && Boolean.parseBoolean(hideBandsArg); final boolean hideProducts = hideProductsArg != null && Boolean.parseBoolean(hideProductsArg); if (hideProducts) { hideBands = true; } GraphMLHandler handler = new GraphMLHandler(writer, hideBands, hideProducts); graphGen.generateGraph(targetProduct, handler); writer.close(); } }
true
true
public static void main(String[] args) throws IOException { if (args.length < 3) { System.out.println("Usage: GraphGenMain <productPath> <graphmlPath> 'meris'|'landsat' [[<hideBands>] <hideProducts>]"); } String productPath = args[0]; String graphmlPath = args[1]; String opSelector = args[2]; String hideBandsArg = args.length > 3 ? args[3] : null; String hideProductsArg = args.length > 4 ? args[4] : null; Operator op; if (opSelector.equalsIgnoreCase("meris")) { op = new MerisOp(); } else if (opSelector.equalsIgnoreCase("landsat")) { op = new TmOp(); } else { throw new IllegalArgumentException("argument 3 must be 'meris' or 'landsat'."); } final Product sourceProduct = ProductIO.readProduct(new File(productPath)); op.setSourceProduct(sourceProduct); final Product targetProduct = op.getTargetProduct(); FileWriter fileWriter = new FileWriter(new File(graphmlPath)); BufferedWriter writer = new BufferedWriter(fileWriter); final GraphGen graphGen = new GraphGen(); boolean hideBands = hideBandsArg != null && Boolean.parseBoolean(hideBandsArg); final boolean hideProducts = hideProductsArg != null && Boolean.parseBoolean(hideProductsArg); if (hideProducts) { hideBands = true; } GraphMLHandler handler = new GraphMLHandler(writer, hideBands, hideProducts); graphGen.generateGraph(targetProduct, handler); writer.close(); }
public static void main(String[] args) throws IOException { if (args.length < 3) { System.out.println("Usage: GraphGenMain <productPath> <graphmlPath> 'meris'|'landsat' [[<hideBands>] <hideProducts>]"); System.exit(1); } String productPath = args[0]; String graphmlPath = args[1]; String opSelector = args[2]; String hideBandsArg = args.length > 3 ? args[3] : null; String hideProductsArg = args.length > 4 ? args[4] : null; Operator op; if (opSelector.equalsIgnoreCase("meris")) { op = new MerisOp(); } else if (opSelector.equalsIgnoreCase("landsat")) { op = new TmOp(); } else { throw new IllegalArgumentException("argument 3 must be 'meris' or 'landsat'."); } final Product sourceProduct = ProductIO.readProduct(new File(productPath)); op.setSourceProduct(sourceProduct); final Product targetProduct = op.getTargetProduct(); FileWriter fileWriter = new FileWriter(new File(graphmlPath)); BufferedWriter writer = new BufferedWriter(fileWriter); final GraphGen graphGen = new GraphGen(); boolean hideBands = hideBandsArg != null && Boolean.parseBoolean(hideBandsArg); final boolean hideProducts = hideProductsArg != null && Boolean.parseBoolean(hideProductsArg); if (hideProducts) { hideBands = true; } GraphMLHandler handler = new GraphMLHandler(writer, hideBands, hideProducts); graphGen.generateGraph(targetProduct, handler); writer.close(); }
diff --git a/code/app/com/feth/play/module/pa/PlayAuthenticate.java b/code/app/com/feth/play/module/pa/PlayAuthenticate.java index a4b43f2..1055f7d 100644 --- a/code/app/com/feth/play/module/pa/PlayAuthenticate.java +++ b/code/app/com/feth/play/module/pa/PlayAuthenticate.java @@ -1,557 +1,562 @@ package com.feth.play.module.pa; import java.util.Date; import play.Configuration; import play.Logger; import play.Play; import play.i18n.Messages; import play.mvc.Call; import play.mvc.Controller; import play.mvc.Http; import play.mvc.Http.Context; import play.mvc.Http.Session; import play.mvc.Result; import com.feth.play.module.pa.exceptions.AccessDeniedException; import com.feth.play.module.pa.exceptions.AuthException; import com.feth.play.module.pa.providers.AuthProvider; import com.feth.play.module.pa.service.UserService; import com.feth.play.module.pa.user.AuthUser; public abstract class PlayAuthenticate { private static final String SETTING_KEY_PLAY_AUTHENTICATE = "play-authenticate"; private static final String SETTING_KEY_AFTER_AUTH_FALLBACK = "afterAuthFallback"; private static final String SETTING_KEY_AFTER_LOGOUT_FALLBACK = "afterLogoutFallback"; private static final String SETTING_KEY_ACCOUNT_MERGE_ENABLED = "accountMergeEnabled"; private static final String SETTING_KEY_ACCOUNT_AUTO_LINK = "accountAutoLink"; private static final String SETTING_KEY_ACCOUNT_AUTO_MERGE = "accountAutoMerge"; public abstract static class Resolver { /** * This is the route to your login page * * @return */ public abstract Call login(); /** * Route to redirect to after authentication has been finished. * Only used if no original URL was stored. * If you return null here, the user will get redirected to the URL of * the setting * afterAuthFallback * You can use this to redirect to an external URL for example. * * @return */ public abstract Call afterAuth(); /** * This should usually point to the route where you registered * com.feth.play.module.pa.controllers.AuthenticateController. * authenticate(String) * however you might provide your own authentication implementation if * you want to * and point it there * * @param provider * The provider ID matching one of your registered providers * in play.plugins * * @return a Call to follow */ public abstract Call auth(final String provider); /** * If you set the accountAutoMerge setting to true, you might return * null for this. * * @return */ public abstract Call askMerge(); /** * If you set the accountAutoLink setting to true, you might return null * for this * * @return */ public abstract Call askLink(); /** * Route to redirect to after logout has been finished. * If you return null here, the user will get redirected to the URL of * the setting * afterLogoutFallback * You can use this to redirect to an external URL for example. * * @return */ public abstract Call afterLogout(); } private static Resolver resolver; public static void setResolver(Resolver res) { resolver = res; } public static Resolver getResolver() { return resolver; } private static UserService userService; public static void setUserService(final UserService service) { userService = service; } public static UserService getUserService() { if (userService == null) { throw new RuntimeException( Messages.get("playauthenticate.core.exception.no_user_service")); } return userService; } private static final String ORIGINAL_URL = "pa.url.orig"; private static final String USER_KEY = "pa.u.id"; private static final String PROVIDER_KEY = "pa.p.id"; private static final String EXPIRES_KEY = "pa.u.exp"; private static final String SESSION_ID_KEY = "pa.s.id"; public static Configuration getConfiguration() { return Play.application().configuration() .getConfig(SETTING_KEY_PLAY_AUTHENTICATE); } public static final Long TIMEOUT = 10l * 1000; private static final String MERGE_USER_KEY = null; private static final String LINK_USER_KEY = null; public static String getOriginalUrl(final Http.Context context) { return context.session().remove(PlayAuthenticate.ORIGINAL_URL); } public static String storeOriginalUrl(final Http.Context context) { String loginUrl = null; if (PlayAuthenticate.getResolver().login() != null) { loginUrl = PlayAuthenticate.getResolver().login().url(); } else { Logger.warn("You should define a login call in the resolver"); } if (context.request().method().equals("GET") && !context.request().path().equals(loginUrl)) { Logger.debug("Path where we are coming from (" + context.request().uri() + ") is different than the login URL (" + loginUrl + ")"); context.session().put(PlayAuthenticate.ORIGINAL_URL, context.request().uri()); } else { Logger.debug("The path we are coming from is the Login URL - delete jumpback"); context.session().remove(PlayAuthenticate.ORIGINAL_URL); } return context.session().get(ORIGINAL_URL); } public static void storeUser(final Session session, final AuthUser u) { session.put(PlayAuthenticate.USER_KEY, u.getId()); session.put(PlayAuthenticate.PROVIDER_KEY, u.getProvider()); if (u.expires() != AuthUser.NO_EXPIRATION) { session.put(EXPIRES_KEY, Long.toString(u.expires())); } else { session.remove(EXPIRES_KEY); } } public static boolean isLoggedIn(final Session session) { boolean ret = session.containsKey(USER_KEY) // user is set && session.containsKey(PROVIDER_KEY); // provider is set ret &= AuthProvider.Registry.hasProvider(session.get(PROVIDER_KEY)); // this // provider // is // active if (session.containsKey(EXPIRES_KEY)) { // expiration is set final long expires = getExpiration(session); if (expires != AuthUser.NO_EXPIRATION) { ret &= (new Date()).getTime() < expires; // and the session // expires after now } } return ret; } public static Result logout(final Session session) { session.remove(USER_KEY); session.remove(PROVIDER_KEY); session.remove(EXPIRES_KEY); // shouldn't be in any more, but just in case lets kill it from the // cookie session.remove(ORIGINAL_URL); return Controller.redirect(getUrl(getResolver().afterLogout(), SETTING_KEY_AFTER_LOGOUT_FALLBACK)); } public static String peekOriginalUrl(final Context context) { return context.session().get(ORIGINAL_URL); } public static boolean hasUserService() { return userService != null; } private static long getExpiration(final Session session) { long expires; if (session.containsKey(EXPIRES_KEY)) { try { expires = Long.parseLong(session.get(EXPIRES_KEY)); } catch (final NumberFormatException nfe) { expires = AuthUser.NO_EXPIRATION; } } else { expires = AuthUser.NO_EXPIRATION; } return expires; } public static AuthUser getUser(final Session session) { final String provider = session.get(PROVIDER_KEY); final String id = session.get(USER_KEY); final long expires = getExpiration(session); if (provider != null && id != null) { return getProvider(provider).getSessionAuthUser(id, expires); } else { return null; } } public static AuthUser getUser(final Context context) { return getUser(context.session()); } public static boolean isAccountAutoMerge() { return getConfiguration().getBoolean(SETTING_KEY_ACCOUNT_AUTO_MERGE, false); } public static boolean isAccountAutoLink() { return getConfiguration().getBoolean(SETTING_KEY_ACCOUNT_AUTO_LINK, false); } public static boolean isAccountMergeEnabled() { return getConfiguration().getBoolean(SETTING_KEY_ACCOUNT_MERGE_ENABLED, true); } private static String getPlayAuthSessionId(final Session session) { // Generate a unique id String uuid = session.get(SESSION_ID_KEY); if (uuid == null) { uuid = java.util.UUID.randomUUID().toString(); session.put(SESSION_ID_KEY, uuid); } return uuid; } private static void storeUserInCache(final Session session, final String key, final AuthUser identity) { play.cache.Cache.set(getCacheKey(session, key), identity); } private static void removeFromCache(final Session session, final String key) { play.cache.Cache.remove(getCacheKey(session, key)); } private static String getCacheKey(final Session session, final String key) { final String id = getPlayAuthSessionId(session); return id + "_" + key; } private static AuthUser getUserFromCache(final Session session, final String key) { final Object o = play.cache.Cache.get(getCacheKey(session, key)); if (o != null && o instanceof AuthUser) { return (AuthUser) o; } return null; } public static void storeMergeUser(final AuthUser identity, final Session session) { // TODO the cache is not ideal for this, because it might get cleared // any time storeUserInCache(session, MERGE_USER_KEY, identity); } public static AuthUser getMergeUser(final Session session) { return getUserFromCache(session, MERGE_USER_KEY); } public static void removeMergeUser(final Session session) { removeFromCache(session, MERGE_USER_KEY); } public static void storeLinkUser(final AuthUser identity, final Session session) { // TODO the cache is not ideal for this, because it might get cleared // any time storeUserInCache(session, LINK_USER_KEY, identity); } public static AuthUser getLinkUser(final Session session) { return getUserFromCache(session, LINK_USER_KEY); } public static void removeLinkUser(final Session session) { removeFromCache(session, LINK_USER_KEY); } private static String getJumpUrl(final Context ctx) { final String originalUrl = getOriginalUrl(ctx); if (originalUrl != null) { return originalUrl; } else { return getUrl(getResolver().afterAuth(), SETTING_KEY_AFTER_AUTH_FALLBACK); } } private static String getUrl(final Call c, final String settingFallback) { // this can be null if the user did not correctly define the // resolver if (c != null) { return c.url(); } else { // go to root instead, but log this Logger.warn("Resolver did not contain information about where to go - redirecting to /"); final String afterAuthFallback = getConfiguration().getString( settingFallback); if (afterAuthFallback != null && !afterAuthFallback.equals("")) { return afterAuthFallback; } // Not even the config setting was there or valid...meh Logger.error("Config setting '" + settingFallback + "' was not present!"); return "/"; } } public static Result link(final Context context, final boolean link) { final AuthUser linkUser = getLinkUser(context.session()); if (linkUser == null) { return Controller.forbidden(); } final AuthUser loginUser; if (link) { // User accepted link - add account to existing local user loginUser = getUserService().link(getUser(context.session()), linkUser); } else { // User declined link - create new user try { loginUser = signupUser(linkUser); } catch (final AuthException e) { return Controller.internalServerError(e.getMessage()); } } removeLinkUser(context.session()); return loginAndRedirect(context, loginUser); } public static Result loginAndRedirect(final Context context, final AuthUser loginUser) { storeUser(context.session(), loginUser); return Controller.redirect(getJumpUrl(context)); } public static Result merge(final Context context, final boolean merge) { final AuthUser mergeUser = getMergeUser(context.session()); if (mergeUser == null) { return Controller.forbidden(); } final AuthUser loginUser; if (merge) { // User accepted merge, so do it loginUser = getUserService().merge(mergeUser, getUser(context.session())); } else { // User declined merge, so log out the old user, and log out with // the new one loginUser = mergeUser; } removeMergeUser(context.session()); return loginAndRedirect(context, loginUser); } private static AuthUser signupUser(final AuthUser u) throws AuthException { final AuthUser loginUser; final Object id = getUserService().save(u); if (id == null) { throw new AuthException( Messages.get("playauthenticate.core.exception.singupuser_failed")); } loginUser = u; return loginUser; } public static Result handleAuthentication(final String provider, final Context context, final Object payload) { final AuthProvider ap = getProvider(provider); if (ap == null) { // Provider wasn't found and/or user was fooling with our stuff - // tell him off: return Controller.notFound(Messages.get( "playauthenticate.core.exception.provider_not_found", provider)); } try { final Object o = ap.authenticate(context, payload); if (o instanceof String) { return Controller.redirect((String) o); } else if (o instanceof AuthUser) { final AuthUser newUser = (AuthUser) o; final Session session = context.session(); // We might want to do merging here: // Adapted from: // http://stackoverflow.com/questions/6666267/architecture-for-merging-multiple-user-accounts-together // 1. The account is linked to a local account and no session // cookie is present --> Login // 2. The account is linked to a local account and a session // cookie is present --> Merge // 3. The account is not linked to a local account and no // session cookie is present --> Signup // 4. The account is not linked to a local account and a session // cookie is present --> Linking Additional account // get the user with which we are logged in - is null if we // are // not logged in (does NOT check expiration) AuthUser oldUser = getUser(session); // checks if the user is logged in (also checks the expiration!) boolean isLoggedIn = isLoggedIn(session); Object oldIdentity = null; // check if local user still exists - it might have been // deactivated/deleted, // so this is a signup, not a link if (isLoggedIn) { oldIdentity = getUserService().getLocalIdentity(oldUser); isLoggedIn &= oldIdentity != null; if (!isLoggedIn) { // if isLoggedIn is false here, then the local user has // been deleted/deactivated // so kill the session logout(session); oldUser = null; } } final Object loginIdentity = getUserService().getLocalIdentity( newUser); final boolean isLinked = loginIdentity != null; final AuthUser loginUser; if (isLinked && !isLoggedIn) { // 1. -> Login // User logged in once more - wanna make some updates? loginUser = getUserService().update(newUser); } else if (isLinked && isLoggedIn) { // 2. -> Merge // merge the two identities and return the AuthUser we want // to use for the log in if (isAccountMergeEnabled() && !loginIdentity.equals(oldIdentity)) { // account merge is enabled // and // The currently logged in user and the one to log in // are not the same, so shall we merge? if (isAccountAutoMerge()) { // Account auto merging is enabled loginUser = getUserService() .merge(newUser, oldUser); } else { // Account auto merging is disabled - forward user // to merge request page final Call c = getResolver().askMerge(); if (c == null) { throw new RuntimeException( Messages.get( "playauthenticate.core.exception.merge.controller_undefined", SETTING_KEY_ACCOUNT_AUTO_MERGE)); } storeMergeUser(newUser, session); return Controller.redirect(c); } } else { // the currently logged in user and the new login belong // to the same local user, // or Account merge is disabled, so just change the log // in to the new user loginUser = newUser; } } else if (!isLinked && !isLoggedIn) { // 3. -> Signup loginUser = signupUser(newUser); } else { // !isLinked && isLoggedIn: // 4. -> Link additional if (isAccountAutoLink()) { // Account auto linking is enabled loginUser = getUserService().link(oldUser, newUser); } else { // Account auto linking is disabled - forward user to // link suggestion page final Call c = getResolver().askLink(); if (c == null) { throw new RuntimeException( Messages.get( "playauthenticate.core.exception.link.controller_undefined", SETTING_KEY_ACCOUNT_AUTO_LINK)); } storeLinkUser(newUser, session); return Controller.redirect(c); } } return loginAndRedirect(context, loginUser); } else { return Controller.internalServerError(Messages .get("playauthenticate.core.exception.general")); } } catch (final AuthException e) { if (e instanceof AccessDeniedException) { return Controller.forbidden(e.getMessage()); } - return Controller.internalServerError(e.getMessage()); + final String message = e.getMessage(); + if (message != null) { + return Controller.internalServerError(message); + } else { + return Controller.internalServerError(); + } } } public static AuthProvider getProvider(final String providerKey) { return AuthProvider.Registry.get(providerKey); } }
true
true
public static Result handleAuthentication(final String provider, final Context context, final Object payload) { final AuthProvider ap = getProvider(provider); if (ap == null) { // Provider wasn't found and/or user was fooling with our stuff - // tell him off: return Controller.notFound(Messages.get( "playauthenticate.core.exception.provider_not_found", provider)); } try { final Object o = ap.authenticate(context, payload); if (o instanceof String) { return Controller.redirect((String) o); } else if (o instanceof AuthUser) { final AuthUser newUser = (AuthUser) o; final Session session = context.session(); // We might want to do merging here: // Adapted from: // http://stackoverflow.com/questions/6666267/architecture-for-merging-multiple-user-accounts-together // 1. The account is linked to a local account and no session // cookie is present --> Login // 2. The account is linked to a local account and a session // cookie is present --> Merge // 3. The account is not linked to a local account and no // session cookie is present --> Signup // 4. The account is not linked to a local account and a session // cookie is present --> Linking Additional account // get the user with which we are logged in - is null if we // are // not logged in (does NOT check expiration) AuthUser oldUser = getUser(session); // checks if the user is logged in (also checks the expiration!) boolean isLoggedIn = isLoggedIn(session); Object oldIdentity = null; // check if local user still exists - it might have been // deactivated/deleted, // so this is a signup, not a link if (isLoggedIn) { oldIdentity = getUserService().getLocalIdentity(oldUser); isLoggedIn &= oldIdentity != null; if (!isLoggedIn) { // if isLoggedIn is false here, then the local user has // been deleted/deactivated // so kill the session logout(session); oldUser = null; } } final Object loginIdentity = getUserService().getLocalIdentity( newUser); final boolean isLinked = loginIdentity != null; final AuthUser loginUser; if (isLinked && !isLoggedIn) { // 1. -> Login // User logged in once more - wanna make some updates? loginUser = getUserService().update(newUser); } else if (isLinked && isLoggedIn) { // 2. -> Merge // merge the two identities and return the AuthUser we want // to use for the log in if (isAccountMergeEnabled() && !loginIdentity.equals(oldIdentity)) { // account merge is enabled // and // The currently logged in user and the one to log in // are not the same, so shall we merge? if (isAccountAutoMerge()) { // Account auto merging is enabled loginUser = getUserService() .merge(newUser, oldUser); } else { // Account auto merging is disabled - forward user // to merge request page final Call c = getResolver().askMerge(); if (c == null) { throw new RuntimeException( Messages.get( "playauthenticate.core.exception.merge.controller_undefined", SETTING_KEY_ACCOUNT_AUTO_MERGE)); } storeMergeUser(newUser, session); return Controller.redirect(c); } } else { // the currently logged in user and the new login belong // to the same local user, // or Account merge is disabled, so just change the log // in to the new user loginUser = newUser; } } else if (!isLinked && !isLoggedIn) { // 3. -> Signup loginUser = signupUser(newUser); } else { // !isLinked && isLoggedIn: // 4. -> Link additional if (isAccountAutoLink()) { // Account auto linking is enabled loginUser = getUserService().link(oldUser, newUser); } else { // Account auto linking is disabled - forward user to // link suggestion page final Call c = getResolver().askLink(); if (c == null) { throw new RuntimeException( Messages.get( "playauthenticate.core.exception.link.controller_undefined", SETTING_KEY_ACCOUNT_AUTO_LINK)); } storeLinkUser(newUser, session); return Controller.redirect(c); } } return loginAndRedirect(context, loginUser); } else { return Controller.internalServerError(Messages .get("playauthenticate.core.exception.general")); } } catch (final AuthException e) { if (e instanceof AccessDeniedException) { return Controller.forbidden(e.getMessage()); } return Controller.internalServerError(e.getMessage()); } }
public static Result handleAuthentication(final String provider, final Context context, final Object payload) { final AuthProvider ap = getProvider(provider); if (ap == null) { // Provider wasn't found and/or user was fooling with our stuff - // tell him off: return Controller.notFound(Messages.get( "playauthenticate.core.exception.provider_not_found", provider)); } try { final Object o = ap.authenticate(context, payload); if (o instanceof String) { return Controller.redirect((String) o); } else if (o instanceof AuthUser) { final AuthUser newUser = (AuthUser) o; final Session session = context.session(); // We might want to do merging here: // Adapted from: // http://stackoverflow.com/questions/6666267/architecture-for-merging-multiple-user-accounts-together // 1. The account is linked to a local account and no session // cookie is present --> Login // 2. The account is linked to a local account and a session // cookie is present --> Merge // 3. The account is not linked to a local account and no // session cookie is present --> Signup // 4. The account is not linked to a local account and a session // cookie is present --> Linking Additional account // get the user with which we are logged in - is null if we // are // not logged in (does NOT check expiration) AuthUser oldUser = getUser(session); // checks if the user is logged in (also checks the expiration!) boolean isLoggedIn = isLoggedIn(session); Object oldIdentity = null; // check if local user still exists - it might have been // deactivated/deleted, // so this is a signup, not a link if (isLoggedIn) { oldIdentity = getUserService().getLocalIdentity(oldUser); isLoggedIn &= oldIdentity != null; if (!isLoggedIn) { // if isLoggedIn is false here, then the local user has // been deleted/deactivated // so kill the session logout(session); oldUser = null; } } final Object loginIdentity = getUserService().getLocalIdentity( newUser); final boolean isLinked = loginIdentity != null; final AuthUser loginUser; if (isLinked && !isLoggedIn) { // 1. -> Login // User logged in once more - wanna make some updates? loginUser = getUserService().update(newUser); } else if (isLinked && isLoggedIn) { // 2. -> Merge // merge the two identities and return the AuthUser we want // to use for the log in if (isAccountMergeEnabled() && !loginIdentity.equals(oldIdentity)) { // account merge is enabled // and // The currently logged in user and the one to log in // are not the same, so shall we merge? if (isAccountAutoMerge()) { // Account auto merging is enabled loginUser = getUserService() .merge(newUser, oldUser); } else { // Account auto merging is disabled - forward user // to merge request page final Call c = getResolver().askMerge(); if (c == null) { throw new RuntimeException( Messages.get( "playauthenticate.core.exception.merge.controller_undefined", SETTING_KEY_ACCOUNT_AUTO_MERGE)); } storeMergeUser(newUser, session); return Controller.redirect(c); } } else { // the currently logged in user and the new login belong // to the same local user, // or Account merge is disabled, so just change the log // in to the new user loginUser = newUser; } } else if (!isLinked && !isLoggedIn) { // 3. -> Signup loginUser = signupUser(newUser); } else { // !isLinked && isLoggedIn: // 4. -> Link additional if (isAccountAutoLink()) { // Account auto linking is enabled loginUser = getUserService().link(oldUser, newUser); } else { // Account auto linking is disabled - forward user to // link suggestion page final Call c = getResolver().askLink(); if (c == null) { throw new RuntimeException( Messages.get( "playauthenticate.core.exception.link.controller_undefined", SETTING_KEY_ACCOUNT_AUTO_LINK)); } storeLinkUser(newUser, session); return Controller.redirect(c); } } return loginAndRedirect(context, loginUser); } else { return Controller.internalServerError(Messages .get("playauthenticate.core.exception.general")); } } catch (final AuthException e) { if (e instanceof AccessDeniedException) { return Controller.forbidden(e.getMessage()); } final String message = e.getMessage(); if (message != null) { return Controller.internalServerError(message); } else { return Controller.internalServerError(); } } }
diff --git a/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/validation/SeamCoreValidator.java b/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/validation/SeamCoreValidator.java index 21bac72a7..751fd536f 100644 --- a/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/validation/SeamCoreValidator.java +++ b/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/validation/SeamCoreValidator.java @@ -1,1120 +1,1119 @@ /******************************************************************************* * Copyright (c) 2007 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.seam.internal.core.validation; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.osgi.util.NLS; import org.eclipse.wst.validation.internal.core.ValidationException; import org.eclipse.wst.validation.internal.provisional.core.IReporter; import org.jboss.tools.common.el.core.resolver.TypeInfoCollector; import org.jboss.tools.common.java.IJavaSourceReference; import org.jboss.tools.common.model.XModelObject; import org.jboss.tools.common.model.util.EclipseResourceUtil; import org.jboss.tools.common.text.ITextSourceReference; import org.jboss.tools.common.validation.ContextValidationHelper; import org.jboss.tools.common.validation.IProjectValidationContext; import org.jboss.tools.common.validation.IValidatingProjectSet; import org.jboss.tools.common.validation.IValidatingProjectTree; import org.jboss.tools.common.validation.IValidator; import org.jboss.tools.common.validation.ValidationUtil; import org.jboss.tools.common.validation.ValidatorManager; import org.jboss.tools.common.validation.internal.SimpleValidatingProjectTree; import org.jboss.tools.common.validation.internal.ValidatingProjectSet; import org.jboss.tools.jst.web.kb.IKbProject; import org.jboss.tools.jst.web.kb.KbProjectFactory; import org.jboss.tools.jst.web.kb.internal.KbProject; import org.jboss.tools.jst.web.kb.internal.validation.KBValidator; import org.jboss.tools.jst.web.model.project.ext.store.XMLValueInfo; import org.jboss.tools.seam.core.BijectedAttributeType; import org.jboss.tools.seam.core.IBijectedAttribute; import org.jboss.tools.seam.core.ISeamAnnotatedFactory; import org.jboss.tools.seam.core.ISeamComponent; import org.jboss.tools.seam.core.ISeamComponentDeclaration; import org.jboss.tools.seam.core.ISeamComponentMethod; import org.jboss.tools.seam.core.ISeamContextVariable; import org.jboss.tools.seam.core.ISeamFactory; import org.jboss.tools.seam.core.ISeamJavaComponentDeclaration; import org.jboss.tools.seam.core.ISeamProject; import org.jboss.tools.seam.core.ISeamProperty; import org.jboss.tools.seam.core.ISeamXmlComponentDeclaration; import org.jboss.tools.seam.core.ISeamXmlFactory; import org.jboss.tools.seam.core.ScopeType; import org.jboss.tools.seam.core.SeamComponentMethodType; import org.jboss.tools.seam.core.SeamCoreBuilder; import org.jboss.tools.seam.core.SeamCoreMessages; import org.jboss.tools.seam.core.SeamCorePlugin; import org.jboss.tools.seam.core.SeamPreferences; import org.jboss.tools.seam.core.SeamProjectsSet; import org.jboss.tools.seam.core.SeamUtil; import org.jboss.tools.seam.core.project.facet.SeamRuntime; import org.jboss.tools.seam.internal.core.DataModelSelectionAttribute; import org.jboss.tools.seam.internal.core.SeamComponentDeclaration; import org.jboss.tools.seam.internal.core.SeamProject; import org.jboss.tools.seam.internal.core.SeamTextSourceReference; import org.jboss.tools.seam.pages.xml.model.SeamPagesConstants; /** * Validator for Java and XML files. * @author Alexey Kazakov */ public class SeamCoreValidator extends SeamValidationErrorManager implements IValidator { public static final String ID = "org.jboss.tools.seam.core.CoreValidator"; //$NON-NLS-1$ public static final String PROBLEM_TYPE = "org.jboss.tools.seam.core.seamproblem"; //$NON-NLS-1$ public static final String MESSAGE_ID_ATTRIBUTE_NAME = "Seam_message_id"; //$NON-NLS-1$ public static final int NONUNIQUE_COMPONENT_NAME_MESSAGE_ID = 1; public static final int DUPLICATE_REMOVE_MESSAGE_ID = 2; public static final int DUPLICATE_DESTROY_MESSAGE_ID = 3; public static final int DUPLICATE_CREATE_MESSAGE_ID = 4; public static final int DUPLICATE_UNWRAP_MESSAGE_ID = 5; public static final int DESTROY_METHOD_BELONGS_TO_STATELESS_SESSION_BEAN_MESSAGE_ID = 6; public static final int CREATE_DOESNT_BELONG_TO_COMPONENT_MESSAGE_ID = 7; public static final int UNWRAP_DOESNT_BELONG_TO_COMPONENT_MESSAGE_ID = 8; public static final int OBSERVER_DOESNT_BELONG_TO_COMPONENT_MESSAGE_ID = 9; public static final int STATEFUL_COMPONENT_DOES_NOT_CONTAIN_REMOVE_ID = 10; public static final int STATEFUL_COMPONENT_DOES_NOT_CONTAIN_DESTROY_ID = 11; public static final int STATEFUL_COMPONENT_WRONG_SCOPE_ID = 12; public static final int ENTITY_COMPONENT_WRONG_SCOPE_ID = 13; public static final int UNKNOWN_COMPONENT_PROPERTY_ID = 14; private ISeamProject seamProject; private SeamProjectsSet set; private String projectName; /* * (non-Javadoc) * @see org.jboss.tools.jst.web.kb.internal.validation.ValidationErrorManager#getMarkerType() */ @Override public String getMarkerType() { return PROBLEM_TYPE; } /* * (non-Javadoc) * @see org.jboss.tools.jst.web.kb.validation.IValidator#getId() */ public String getId() { return ID; } public String getBuilderId() { return SeamCoreBuilder.BUILDER_ID; } /* * (non-Javadoc) * @see org.jboss.tools.jst.web.kb.validation.IValidator#getValidatingProjects(org.eclipse.core.resources.IProject) */ public IValidatingProjectTree getValidatingProjects(IProject project) { return getSeamValidatingProjects(project); } private static final String SHORT_ID = "jboss.seam.core"; //$NON-NLS-1$ public static IValidatingProjectTree getSeamValidatingProjects(IProject project) { SeamProjectsSet set = new SeamProjectsSet(project); IProject war = set.getWarProject(); IProjectValidationContext rootContext = null; if(war!=null && war.isAccessible()) { IKbProject kbProject = KbProjectFactory.getKbProject(war, false); if(kbProject!=null) { rootContext = kbProject.getValidationContext(); } else { KbProject.checkKBBuilderInstalled(war); ISeamProject seamProject = SeamCorePlugin.getSeamProject(war, false); if(seamProject!=null) { rootContext = seamProject.getValidationContext(); } } } if(rootContext==null) { ISeamProject seamProject = SeamCorePlugin.getSeamProject(project, false); if(seamProject!=null) { rootContext = seamProject.getValidationContext(); war = project; } } Set<IProject> projects = new HashSet<IProject>(); IProject[] array = set.getAllProjects(); for (int i = 0; i < array.length; i++) { if(array[i].isAccessible()) { projects.add(array[i]); } } IValidatingProjectSet projectSet = new ValidatingProjectSet(war, projects, rootContext); return new SimpleValidatingProjectTree(projectSet); } /* * (non-Javadoc) * @see org.jboss.tools.jst.web.kb.validation.IValidator#isEnabled(org.eclipse.core.resources.IProject) */ public boolean isEnabled(IProject project) { return SeamPreferences.isValidationEnabled(project); } /* * (non-Javadoc) * @see org.jboss.tools.jst.web.kb.validation.IValidator#shouldValidate(org.eclipse.core.resources.IProject) */ public boolean shouldValidate(IProject project) { try { return project != null && project.isAccessible() && project.hasNature(ISeamProject.NATURE_ID) && validateBuilderOrder(project) && isPreferencesEnabled(project); } catch (CoreException e) { SeamCorePlugin.getDefault().logError(e); } return false; } private boolean validateBuilderOrder(IProject project) throws CoreException { return KBValidator.validateBuilderOrder(project, getBuilderId(), getId(), SeamPreferences.getInstance()); } /* * (non-Javadoc) * @see org.jboss.tools.jst.web.kb.internal.validation.ValidationErrorManager#init(org.eclipse.core.resources.IProject, org.jboss.tools.jst.web.kb.internal.validation.ContextValidationHelper, org.jboss.tools.jst.web.kb.internal.validation.ValidatorManager, org.eclipse.wst.validation.internal.provisional.core.IReporter, org.jboss.tools.jst.web.kb.validation.IValidationContext) */ @Override public void init(IProject project, ContextValidationHelper validationHelper, IProjectValidationContext validationContext, org.eclipse.wst.validation.internal.provisional.core.IValidator manager, IReporter reporter) { super.init(project, validationHelper, validationContext, manager, reporter); set = new SeamProjectsSet(project); IProject warProject = set.getWarProject(); // Fix for JBIDE-7622: set these variables to null due to prevent wrong project validations --->>> seamProject = null; projectName = null; // <<<--- if(warProject.isAccessible()) { seamProject = SeamCorePlugin.getSeamProject(warProject, false); projectName = seamProject.getProject().getName(); } } private boolean isPreferencesEnabled(IProject project) { return isEnabled(project) && SeamPreferences.shouldValidateCore(project); } /* * (non-Javadoc) * @see org.jboss.tools.jst.web.kb.validation.IValidator#validate(java.util.Set, org.eclipse.core.resources.IProject, org.jboss.tools.jst.web.kb.internal.validation.ContextValidationHelper, org.jboss.tools.jst.web.kb.validation.IProjectValidationContext, org.jboss.tools.jst.web.kb.internal.validation.ValidatorManager, org.eclipse.wst.validation.internal.provisional.core.IReporter) */ public IStatus validate(Set<IFile> changedFiles, IProject project, ContextValidationHelper validationHelper, IProjectValidationContext context, ValidatorManager manager, IReporter reporter) throws ValidationException { init(project, validationHelper, context, manager, reporter); if(seamProject==null) { return OK_STATUS; } displaySubtask(SeamValidationMessages.SEARCHING_RESOURCES, new String[]{projectName}); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); Set<ISeamComponent> checkedComponents = new HashSet<ISeamComponent>(); Set<String> markedDuplicateFactoryNames = new HashSet<String>(); // Collect all resources which we must validate. Set<IPath> resources = new HashSet<IPath>(); // Resources which we have to validate. Set<IPath> newResources = new HashSet<IPath>(); // New (unlinked) resources file boolean validateUnnamedResources = false; for(IFile currentFile : changedFiles) { if(reporter.isCancelled()) { break; } if(!validateUnnamedResources) { String fileName = currentFile.getName().toLowerCase(); // We need to check only file names here. validateUnnamedResources = fileName.endsWith(".java") || fileName.endsWith(".properties") || fileName.equals("components.xml"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } if (ValidationUtil.checkFileExtensionForJavaAndXml(currentFile)) { resources.add(currentFile.getFullPath()); // Get new variable names from model Set<String> newVariableNamesOfChangedFile = getVariablesNameByResource(currentFile.getFullPath()); Set<String> oldDeclarationsOfChangedFile = validationContext.getVariableNamesByCoreResource(SHORT_ID, currentFile.getFullPath(), true); for (String newVariableName : newVariableNamesOfChangedFile) { // Collect resources with new variable name. Set<IPath> linkedResources = validationContext.getCoreResourcesByVariableName(SHORT_ID, newVariableName, false); if(linkedResources!=null) { resources.addAll(linkedResources); } resources.addAll(getAllResourceOfComponent(currentFile.getFullPath())); } // Get old variable names which were linked with this resource. Set<String> oldVariablesNamesOfChangedFile = validationContext.getVariableNamesByCoreResource(SHORT_ID, currentFile.getFullPath(), false); if(oldVariablesNamesOfChangedFile!=null) { for (String name : oldVariablesNamesOfChangedFile) { Set<IPath> linkedResources = validationContext.getCoreResourcesByVariableName(SHORT_ID, name, false); if(linkedResources!=null) { resources.addAll(linkedResources); } } } // Save old declarations for EL validation. We need to validate all EL resources which use this variable name but only if the variable has been changed. if(oldDeclarationsOfChangedFile!=null) { for (String name : oldDeclarationsOfChangedFile) { validationContext.addVariableNameForELValidation(SHORT_ID, name); } } newResources.add(currentFile.getFullPath()); } } // Validate all collected linked resources. // Remove all links between collected resources and variables names because they will be linked again during validation. validationContext.removeLinkedCoreResources(SHORT_ID, resources); Set<IFile> filesToValidate = new HashSet<IFile>(); // We have to remove markers from all collected source files first for (IPath linkedResource : resources) { IFile file = root.getFile(linkedResource); if(file!=null && file.isAccessible()) { filesToValidate.add(file); removeAllMessagesFromResource(file); } } // Then we can validate them for (IFile file : filesToValidate) { validateComponent(file.getFullPath(), checkedComponents, newResources); validateFactory(file.getFullPath(), markedDuplicateFactoryNames); validatePageXML(file); validateXMLVersion(file); } // If changed files are *.java or component.xml then re-validate all unnamed resources. if(validateUnnamedResources) { Set<IPath> unnamedResources = validationContext.getUnnamedCoreResources(SHORT_ID); newResources.addAll(unnamedResources); for (IPath path : newResources) { IFile file = root.getFile(path); if(file!=null && file.isAccessible()) { if(!resources.contains(path)) { removeAllMessagesFromResource(file); } displaySubtask(SeamValidationMessages.VALIDATING_RESOURCE, new String[]{projectName, path.toString()}); Set<ISeamJavaComponentDeclaration> declarations = ((SeamProject)seamProject).findJavaDeclarations(path); for (ISeamJavaComponentDeclaration d : declarations) { validateMethodsOfUnknownComponent(d); } } } } return OK_STATUS; } /* * (non-Javadoc) * @see org.jboss.tools.jst.web.kb.validation.IValidator#validateAll(org.eclipse.core.resources.IProject, org.jboss.tools.jst.web.kb.internal.validation.ContextValidationHelper, org.jboss.tools.jst.web.kb.validation.IProjectValidationContext, org.jboss.tools.jst.web.kb.internal.validation.ValidatorManager, org.eclipse.wst.validation.internal.provisional.core.IReporter) */ public IStatus validateAll(IProject project, ContextValidationHelper validationHelper, IProjectValidationContext context, ValidatorManager manager, IReporter reporter) throws ValidationException { init(project, validationHelper, context, manager, reporter); if(seamProject==null) { return OK_STATUS; } for (IProject iProject : set.getAllProjects()) { removeAllMessagesFromResource(iProject); } ISeamComponent[] components = seamProject.getComponents(); for (ISeamComponent component : components) { if(reporter.isCancelled()) { return OK_STATUS; } Set<ISeamComponentDeclaration> declarations = component.getAllDeclarations(); for (ISeamComponentDeclaration seamComponentDeclaration : declarations) { validateComponent(component); break; } } ISeamFactory[] factories = seamProject.getFactories(); Set<String> markedDuplicateFactoryNames = new HashSet<String>(); for (ISeamFactory factory : factories) { if(reporter.isCancelled()) { return OK_STATUS; } validateFactory(factory, markedDuplicateFactoryNames); } ISeamJavaComponentDeclaration[] values = ((SeamProject)seamProject).getAllJavaComponentDeclarations(); for (ISeamJavaComponentDeclaration d : values) { if(reporter.isCancelled()) { return OK_STATUS; } displaySubtask(SeamValidationMessages.VALIDATING_CLASS, new String[]{projectName, d.getClassName()}); validateMethodsOfUnknownComponent(d); } IResource webContent = set.getViewsFolder(); if(webContent instanceof IContainer && webContent.isAccessible()) { validateAllPageXMLFiles((IContainer)webContent); } return OK_STATUS; } void validateAllPageXMLFiles(IContainer c) { if(c.isAccessible()) { IResource[] rs = null; try { rs = c.members(); } catch (CoreException e) { SeamCorePlugin.getDefault().logError(e); return; } for (int i = 0; i < rs.length; i++) { if(rs[i] instanceof IContainer) { validateAllPageXMLFiles((IContainer)rs[i]); } else if(rs[i] instanceof IFile) { validatePageXML((IFile)rs[i]); } } } } private void validateFactory(IPath sourceFilePath, Set<String> markedDuplicateFactoryNames) { Set<ISeamFactory> factories = seamProject.getFactoriesByPath(sourceFilePath); for (ISeamFactory factory : factories) { validateFactory(factory, markedDuplicateFactoryNames); } } private void validateFactory(ISeamFactory factory, Set<String> markedDuplicateFactoryNames) { if(SeamUtil.isJar(factory.getSourcePath())) { return; } String factoryName = factory.getName(); if(factoryName!=null) { displaySubtask(SeamValidationMessages.VALIDATING_FACTORY, new String[]{projectName, factoryName}); } if(factory instanceof ISeamAnnotatedFactory) { validateAnnotatedFactory((ISeamAnnotatedFactory)factory, markedDuplicateFactoryNames); } else { validateXmlFactory((ISeamXmlFactory)factory, markedDuplicateFactoryNames); } } private void validateXmlFactory(ISeamXmlFactory factory, Set<String> markedDuplicateFactoryNames) { String name = factory.getName(); if(name==null) { SeamCorePlugin.getDefault().logError(NLS.bind(SeamCoreMessages.SEAM_CORE_VALIDATOR_FACTORY_METHOD_MUST_HAVE_NAME,factory.getResource())); return; } validateFactoryName(factory, name, markedDuplicateFactoryNames, false); } private void validateAnnotatedFactory(ISeamAnnotatedFactory factory, Set<String> markedDuplicateFactoryNames) { IMember sourceMember = factory.getSourceMember(); if(sourceMember instanceof IMethod) { String factoryName = factory.getName(); if(factoryName==null) { // Unknown factory name SeamCorePlugin.getDefault().logError(NLS.bind(SeamCoreMessages.SEAM_CORE_VALIDATOR_FACTORY_METHOD_MUST_HAVE_NAME,factory.getResource())); return; } validateFactoryName(factory, factoryName, markedDuplicateFactoryNames, true); } else { // factory must be java method! // JDT should mark it. } } private void validateFactoryName(ISeamFactory factory, String factoryName, Set<String> markedDuplicateFactoryNames, boolean validateUnknownName) { ScopeType factoryScope = factory.getScope(); Set<ISeamContextVariable> variables = seamProject.getVariablesByName(factoryName); boolean unknownVariable = true; boolean firstDuplicateVariableWasMarked = false; for (ISeamContextVariable variable : variables) { if(variable instanceof ISeamFactory) { if(variable!=factory && !markedDuplicateFactoryNames.contains(factoryName) && (factoryScope == variable.getScope() || factoryScope.getPriority()>variable.getScope().getPriority())) { // Duplicate factory name. Mark it. // Save link to factory resource. ITextSourceReference location = null; if(!firstDuplicateVariableWasMarked) { firstDuplicateVariableWasMarked = true; // mark original factory validationContext.addLinkedCoreResource(SHORT_ID, factoryName, factory.getSourcePath(), true); location = SeamUtil.getLocationOfName(factory); this.addError(SeamValidationMessages.DUPLICATE_VARIABLE_NAME, SeamPreferences.DUPLICATE_VARIABLE_NAME, new String[]{factoryName}, location, factory.getResource()); } // Mark duplicate variable. if(!SeamUtil.isJar(variable.getSourcePath())) { IResource resource = SeamUtil.getComponentResourceWithName(variable); validationContext.addLinkedCoreResource(SHORT_ID, factoryName, resource.getFullPath(), true); location = SeamUtil.getLocationOfName(variable); this.addError(SeamValidationMessages.DUPLICATE_VARIABLE_NAME, SeamPreferences.DUPLICATE_VARIABLE_NAME, new String[]{factoryName}, location, resource); } } } else { // We know that variable name unknownVariable = false; } } if(firstDuplicateVariableWasMarked) { markedDuplicateFactoryNames.add(factoryName); } boolean voidReturnType = false; if(factory instanceof ISeamAnnotatedFactory) { IMember sourceMember = ((ISeamAnnotatedFactory)factory).getSourceMember(); if(sourceMember instanceof IMethod) { IMethod method = (IMethod)sourceMember; try { String returnType = method.getReturnType(); if("V".equals(returnType)) { //$NON-NLS-1$ // return type is void voidReturnType = true; } } catch (JavaModelException e) { SeamCorePlugin.getDefault().logError(SeamCoreMessages.SEAM_CORE_VALIDATOR_ERROR_VALIDATING_SEAM_CORE, e); } } } if(unknownVariable && validateUnknownName && voidReturnType) { // mark unknown factory name // save link to factory resource validationContext.addLinkedCoreResource(SHORT_ID, factoryName, factory.getSourcePath(), true); this.addError(SeamValidationMessages.UNKNOWN_FACTORY_NAME, SeamPreferences.UNKNOWN_FACTORY_NAME, new String[]{factoryName}, SeamUtil.getLocationOfName(factory), factory.getResource()); } } private void validateComponent(IPath sourceFilePath, Set<ISeamComponent> checkedComponents, Set<IPath> unnamedResources) { Set<ISeamComponent> components = seamProject.getComponentsByPath(sourceFilePath); if(components.isEmpty()) { unnamedResources.add(sourceFilePath); return; } for (ISeamComponent component : components) { // Don't validate one component twice. if(!checkedComponents.contains(component)) { validateComponent(component); checkedComponents.add(component); } } } /* * Returns set of variables which are linked with this resource */ private Set<String> getVariablesNameByResource(IPath resourcePath) { Set<ISeamContextVariable> variables = seamProject.getVariablesByPath(resourcePath); Set<String> result = new HashSet<String>(); if(variables!=null) { for (ISeamContextVariable variable : variables) { String name = variable.getName(); result.add(name); } } return result; } /* * Collect all resources of all declarations of all components which is declared in the source. */ private Set<IPath> getAllResourceOfComponent(IPath sourceComponentFilePath) { Set<IPath> result = new HashSet<IPath>(); Set<ISeamComponent> components = seamProject.getComponentsByPath(sourceComponentFilePath); for (ISeamComponent component : components) { Set<ISeamComponentDeclaration> declarations = component.getAllDeclarations(); for (ISeamComponentDeclaration seamComponentDeclaration : declarations) { result.add(seamComponentDeclaration.getResource().getFullPath()); } } return result; } /* * Validates the component */ private void validateComponent(ISeamComponent component) { ISeamJavaComponentDeclaration firstJavaDeclaration = component.getJavaDeclaration(); if(firstJavaDeclaration!=null) { String componentName = component.getName(); if(componentName!=null) { displaySubtask(SeamValidationMessages.VALIDATING_COMPONENT, new String[]{projectName, componentName}); } HashMap<Integer, ISeamJavaComponentDeclaration> usedPrecedences = new HashMap<Integer, ISeamJavaComponentDeclaration>(); Set<ISeamJavaComponentDeclaration> markedDeclarations = new HashSet<ISeamJavaComponentDeclaration>(); int firstJavaDeclarationPrecedence = firstJavaDeclaration.getPrecedence(); usedPrecedences.put(firstJavaDeclarationPrecedence, firstJavaDeclaration); Set<ISeamComponentDeclaration> declarations = component.getAllDeclarations(); for (ISeamComponentDeclaration declaration : declarations) { if(declaration instanceof ISeamJavaComponentDeclaration) { ISeamJavaComponentDeclaration jd = (ISeamJavaComponentDeclaration)declaration; //do not check files declared in another project // if(jd.getSeamProject() != seamProject) continue; IType type = (IType)jd.getSourceMember(); boolean sourceJavaDeclaration = !type.isBinary(); if(sourceJavaDeclaration) { // Save link between component name and java source file. validationContext.addLinkedCoreResource(SHORT_ID, componentName, declaration.getSourcePath(), true); // Save link between component name and all supers of java declaration. try { IType[] superTypes = TypeInfoCollector.getSuperTypes(type).getSuperTypes(); for (int i = 0; superTypes != null && i < superTypes.length; i++) { if(!superTypes[i].isBinary()) { IPath path = superTypes[i].getResource().getFullPath(); validationContext.addLinkedCoreResource(SHORT_ID, componentName, path, true); } } } catch (JavaModelException e) { SeamCorePlugin.getPluginLog().logError(e); } } if(declaration!=firstJavaDeclaration) { // Validate @Name // Component class with the same component name. Check precedence. ISeamJavaComponentDeclaration javaDeclaration = (ISeamJavaComponentDeclaration)declaration; int javaDeclarationPrecedence = javaDeclaration.getPrecedence(); ISeamJavaComponentDeclaration checkedDeclaration = usedPrecedences.get(javaDeclarationPrecedence); if(checkedDeclaration==null) { usedPrecedences.put(javaDeclarationPrecedence, javaDeclaration); } else if(sourceJavaDeclaration) { boolean sourceCheckedDeclaration = !((IType)checkedDeclaration.getSourceMember()).isBinary(); IResource javaDeclarationResource = javaDeclaration.getResource(); // Mark nonunique name. if(!markedDeclarations.contains(checkedDeclaration) && sourceCheckedDeclaration) { // Mark first wrong declaration with that name IResource checkedDeclarationResource = checkedDeclaration.getResource(); ITextSourceReference location = ((SeamComponentDeclaration)checkedDeclaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); if(!SeamUtil.isEmptyLocation(location)) { addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, checkedDeclarationResource, NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } markedDeclarations.add(checkedDeclaration); } // Mark next wrong declaration with that name markedDeclarations.add(javaDeclaration); ITextSourceReference location = ((SeamComponentDeclaration)javaDeclaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); if(!SeamUtil.isEmptyLocation(location)) { addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, javaDeclarationResource, NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } } } } } boolean source = !((IType)firstJavaDeclaration.getSourceMember()).isBinary(); if(source) { // Validate all elements in first java declaration but @Name. validateJavaDeclaration(component, firstJavaDeclaration); } } validateXmlComponentDeclarations(component); } private static final String BUILT_IN_COMPONENT_NAME_PREFIX = "org.jboss.seam."; private boolean isBuiltInComponentName(String componentName) { return componentName.startsWith(BUILT_IN_COMPONENT_NAME_PREFIX); } private void validateXmlComponentDeclarations(ISeamComponent component) { String componentName = component.getName(); if(componentName!=null) { HashMap<String, ISeamXmlComponentDeclaration> usedPrecedences = new HashMap<String, ISeamXmlComponentDeclaration>(); Set<ISeamXmlComponentDeclaration> markedDeclarations = new HashSet<ISeamXmlComponentDeclaration>(); Set<ISeamJavaComponentDeclaration> markedJavaDeclarations = new HashSet<ISeamJavaComponentDeclaration>(); Set<ISeamXmlComponentDeclaration> declarations = component.getXmlDeclarations(); ISeamXmlComponentDeclaration firstNamedDeclaration = null; for (ISeamXmlComponentDeclaration declaration : declarations) { if(SeamUtil.isJar(declaration)) { return; } //do not check files declared in another project // if(declaration.getSeamProject() != seamProject) continue; validationContext.addLinkedCoreResource(SHORT_ID, componentName, declaration.getSourcePath(), true); String precedence = declaration.getPrecedence(); if(firstNamedDeclaration == null && declaration.getName()!=null) { firstNamedDeclaration = declaration; usedPrecedences.put(precedence, declaration); } if(declaration.getName()!=null && firstNamedDeclaration!=declaration) { // Check precedence ISeamXmlComponentDeclaration checkedDeclaration = usedPrecedences.get(precedence); if(checkedDeclaration==null) { usedPrecedences.put(precedence, declaration); } else { // Mark not-unique name. if(!markedDeclarations.contains(checkedDeclaration)) { // Mark first wrong declaration with that name IResource checkedDeclarationResource = checkedDeclaration.getResource(); ITextSourceReference location = ((SeamComponentDeclaration)checkedDeclaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); if(!SeamUtil.isEmptyLocation(location)) { addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, checkedDeclarationResource, NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } markedDeclarations.add(checkedDeclaration); } // Mark next wrong declaration with that name markedDeclarations.add(declaration); ITextSourceReference location = ((SeamComponentDeclaration)declaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); if(!SeamUtil.isEmptyLocation(location)) { addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, declaration.getResource(), NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } } } // Check Java declarations with the same name Set<ISeamContextVariable> vars = seamProject.getVariablesByName(componentName); for (ISeamContextVariable variable : vars) { if(variable instanceof ISeamComponent) { ISeamComponent c = (ISeamComponent)variable; Set<ISeamComponentDeclaration> decls = c.getAllDeclarations(); for (ISeamComponentDeclaration dec : decls) { if(dec instanceof ISeamJavaComponentDeclaration) { ISeamJavaComponentDeclaration javaDec = (ISeamJavaComponentDeclaration)dec; // Check names if(declaration.getClassName()!=null && javaDec.getName()!=null && javaDec.getName().equals(declaration.getName())) { // Check precedences String javaPrecedence = "" + javaDec.getPrecedence(); if(javaPrecedence.equals(precedence) && !isBuiltInComponentName(componentName)) { if(!markedJavaDeclarations.contains(javaDec)) { markedJavaDeclarations.add(javaDec); ITextSourceReference location = ((SeamComponentDeclaration)javaDec).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, javaDec.getResource(), NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } if(!markedDeclarations.contains(declaration)) { markedDeclarations.add(declaration); ITextSourceReference location = ((SeamComponentDeclaration)declaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, declaration.getResource(), NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } } } } } } } String className = declaration.getClassName(); IType type = null; if(className!=null) { // validate class name try { IProject p = seamProject.getProject(); // type = EclipseJavaUtil.findType(EclipseResourceUtil.getJavaProject(p), className); IJavaProject javaProject = EclipseResourceUtil.getJavaProject(p); if(javaProject==null) { SeamCorePlugin.getDefault().logWarning("Can't get Java project for " + seamProject.getProject()!=null?seamProject.getProject().getName():"" + " Seam project."); return; } type = javaProject.findType(className); if(type==null) { // Mark wrong class name ITextSourceReference location = ((SeamComponentDeclaration)declaration).getLocationFor(ISeamXmlComponentDeclaration.CLASS); if(SeamUtil.isEmptyLocation(location)) { location = ((SeamComponentDeclaration)declaration).getLocationFor(ISeamXmlComponentDeclaration.NAME); } if(SeamUtil.isEmptyLocation(location)) { location = declaration; } if(!declaration.isClassNameGuessed()) { addError(SeamValidationMessages.UNKNOWN_COMPONENT_CLASS_NAME, SeamPreferences.UNKNOWN_COMPONENT_CLASS_NAME, new String[]{className}, location, declaration.getResource()); } else { addError(SeamValidationMessages.UNKNOWN_COMPONENT_CLASS_NAME, SeamPreferences.UNKNOWN_COMPONENT_CLASS_NAME_GUESS, new String[]{className}, location, declaration.getResource()); } - return; } else if(!type.isBinary()) { validationContext.addLinkedCoreResource(SHORT_ID, componentName, type.getResource().getFullPath(), true); } } catch (JavaModelException e) { SeamCorePlugin.getDefault().logError(SeamCoreMessages.SEAM_CORE_VALIDATOR_ERROR_VALIDATING_SEAM_CORE, e); } } // validate properties Collection<ISeamProperty> properties = declaration.getProperties(); for (ISeamProperty property : properties) { if(SeamUtil.isJar(property)) { return; } String name = property.getName(); if(name==null) { return; } if(type==null && component.getJavaDeclaration()!=null) { IMember member = component.getJavaDeclaration().getSourceMember(); if(member instanceof IType) { type = (IType)member; } } if(type!=null) { boolean ok = type.isBinary() || SeamUtil.findProperty(type, name)!=null; if(!ok) { addError(SeamValidationMessages.UNKNOWN_COMPONENT_PROPERTY, SeamPreferences.UNKNOWN_COMPONENT_PROPERTY, new String[]{type.getElementName(), componentName, name}, property, declaration.getResource(), UNKNOWN_COMPONENT_PROPERTY_ID); } } } } } } private void validateEntityComponent(ISeamComponent component) { if(component.isEntity()) { ISeamJavaComponentDeclaration javaDeclaration = component.getJavaDeclaration(); ScopeType scope = component.getScope(); if(scope == ScopeType.STATELESS) { ITextSourceReference location = getScopeLocation(component); addError(SeamValidationMessages.ENTITY_COMPONENT_WRONG_SCOPE, SeamPreferences.ENTITY_COMPONENT_WRONG_SCOPE, new String[]{component.getName()}, location, javaDeclaration.getResource(), ENTITY_COMPONENT_WRONG_SCOPE_ID); } } } private ITextSourceReference getScopeLocation(ISeamComponent component) { ISeamJavaComponentDeclaration javaDeclaration = component.getJavaDeclaration(); ITextSourceReference location = ((SeamComponentDeclaration)javaDeclaration).getLocationFor(SeamComponentDeclaration.PATH_OF_SCOPE); if(SeamUtil.isEmptyLocation(location)) { location = getNameLocation(javaDeclaration); } return location; } private ITextSourceReference getNameLocation(IJavaSourceReference source) { int length = 0; int offset = 0; try { length = source.getSourceMember().getNameRange().getLength(); offset = source.getSourceMember().getNameRange().getOffset(); } catch (JavaModelException e) { SeamCorePlugin.getDefault().logError(SeamCoreMessages.SEAM_CORE_VALIDATOR_ERROR_VALIDATING_SEAM_CORE, e); } return new SeamTextSourceReference(length, offset, source.getResource()); } private void validateStatefulComponent(ISeamComponent component) { if(component.isStateful()) { ISeamJavaComponentDeclaration javaDeclaration = component.getJavaDeclaration(); validateStatefulComponentMethods(SeamComponentMethodType.DESTROY, component, SeamValidationMessages.STATEFUL_COMPONENT_DOES_NOT_CONTAIN_DESTROY, SeamPreferences.STATEFUL_COMPONENT_DOES_NOT_CONTENT_DESTROY, STATEFUL_COMPONENT_DOES_NOT_CONTAIN_DESTROY_ID); validateStatefulComponentMethods(SeamComponentMethodType.REMOVE, component, SeamValidationMessages.STATEFUL_COMPONENT_DOES_NOT_CONTAIN_REMOVE, SeamPreferences.STATEFUL_COMPONENT_DOES_NOT_CONTENT_REMOVE, STATEFUL_COMPONENT_DOES_NOT_CONTAIN_REMOVE_ID); ScopeType scope = component.getScope(); if(scope == ScopeType.PAGE || scope == ScopeType.STATELESS) { ITextSourceReference location = getScopeLocation(component); addError(SeamValidationMessages.STATEFUL_COMPONENT_WRONG_SCOPE, SeamPreferences.STATEFUL_COMPONENT_WRONG_SCOPE, new String[]{component.getName()}, location, javaDeclaration.getResource(), STATEFUL_COMPONENT_WRONG_SCOPE_ID); } validateDuplicateComponentMethod(SeamComponentMethodType.REMOVE, component, SeamValidationMessages.DUPLICATE_REMOVE, SeamPreferences.DUPLICATE_REMOVE, DUPLICATE_REMOVE_MESSAGE_ID); } } private void validateStatefulComponentMethods(SeamComponentMethodType methodType, ISeamComponent component, String message, String preferenceKey, int id) { ISeamJavaComponentDeclaration javaDeclaration = component.getJavaDeclaration(); ITextSourceReference classNameLocation = getNameLocation(javaDeclaration); Set<ISeamComponentMethod> methods = javaDeclaration.getMethodsByType(methodType); if(methods==null || methods.isEmpty()) { addError(message, preferenceKey, new String[]{component.getName()}, classNameLocation, javaDeclaration.getResource(), id); } } private void validateDuplicateComponentMethods(ISeamComponent component) { validateDuplicateComponentMethod(SeamComponentMethodType.DESTROY, component, SeamValidationMessages.DUPLICATE_DESTROY, SeamPreferences.DUPLICATE_DESTROY, DUPLICATE_DESTROY_MESSAGE_ID); validateDuplicateComponentMethod(SeamComponentMethodType.CREATE, component, SeamValidationMessages.DUPLICATE_CREATE, SeamPreferences.DUPLICATE_CREATE, DUPLICATE_CREATE_MESSAGE_ID); validateDuplicateComponentMethod(SeamComponentMethodType.UNWRAP, component, SeamValidationMessages.DUPLICATE_UNWRAP, SeamPreferences.DUPLICATE_UNWRAP, DUPLICATE_UNWRAP_MESSAGE_ID); } private void validateDuplicateComponentMethod(SeamComponentMethodType methodType, ISeamComponent component, String message, String preferenceKey, int message_id) { ISeamJavaComponentDeclaration javaDeclaration = component.getJavaDeclaration(); Set<ISeamComponentMethod> methods = javaDeclaration.getMethodsByType(methodType); if(methods!=null && methods.size()>1) { for (ISeamComponentMethod method : methods) { if(javaDeclaration.getSourcePath().equals(method.getSourcePath())) { IMethod javaMethod = (IMethod)method.getSourceMember(); String methodName = javaMethod.getElementName(); ITextSourceReference methodNameLocation = getNameLocation(method); addError(message, preferenceKey, new String[]{methodName}, methodNameLocation, javaDeclaration.getResource(), message_id); } } } } private void validateJavaDeclaration(ISeamComponent component, ISeamJavaComponentDeclaration declaration) { validateBijections(declaration); validateStatefulComponent(component); validateDuplicateComponentMethods(component); validateEntityComponent(component); validateDestroyMethod(component); } private void validateBijections(ISeamJavaComponentDeclaration declaration) { Set<IBijectedAttribute> bijections = declaration.getBijectedAttributes(); if(bijections==null) { return; } for (IBijectedAttribute bijection : bijections) { if(bijection.isOfType(BijectedAttributeType.DATA_MODEL_SELECTION) || bijection.isOfType(BijectedAttributeType.DATA_MODEL_SELECTION_INDEX)) { validateDataModelSelection(declaration, bijection); } else { validateInAndOut(declaration, bijection); } } } private void validateInAndOut(ISeamJavaComponentDeclaration declaration, IBijectedAttribute bijection) { String name = bijection.getName(); if(name==null || name.startsWith("#{") || name.startsWith("${")) { //$NON-NLS-1$ //$NON-NLS-2$ return; } // Validate @In if(bijection.isOfType(BijectedAttributeType.IN)) { // save link between java source and variable name validationContext.addLinkedCoreResource(SHORT_ID, name, declaration.getSourcePath(), false); Set<ISeamContextVariable> variables = declaration.getVariablesByName(name); if(variables == null || variables.isEmpty()) variables = seamProject.getVariablesByName(name); if(variables == null || variables.isEmpty()) { ISeamProject parentProject = seamProject.getParentProject(); if(parentProject != null) { variables = parentProject.getVariablesByName(name); } } if(variables==null || variables.size()<1) { // Injection has unknown name. Mark it. IResource declarationResource = declaration.getResource(); ITextSourceReference nameRef = getNameLocation(bijection); if(nameRef == null) { nameRef = bijection; } addError(SeamValidationMessages.UNKNOWN_VARIABLE_NAME, SeamPreferences.UNKNOWN_VARIABLE_NAME, new String[]{name}, nameRef, declarationResource); } } else { // save link between java source and variable name validationContext.addLinkedCoreResource(SHORT_ID, name, declaration.getSourcePath(), true); } } private void validateDataModelSelection(ISeamJavaComponentDeclaration declaration, IBijectedAttribute bijection) { String dataModelName = bijection.getValue(); String selectionName = bijection.getName(); // save link between java source and variable name validationContext.addLinkedCoreResource(SHORT_ID, selectionName, declaration.getSourcePath(), false); if(dataModelName==null) { // here must be the only one @DataModel in the component Set<IBijectedAttribute> dataBinders = declaration.getBijectedAttributesByType(BijectedAttributeType.DATA_BINDER); ITextSourceReference location = null; if(dataBinders!=null && dataBinders.size()>1) { for (IBijectedAttribute dataBinder : dataBinders) { location = dataBinder.getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); addError(SeamValidationMessages.MULTIPLE_DATA_BINDER, SeamPreferences.MULTIPLE_DATA_BINDER, location, declaration.getResource()); } } } else { // save link between java source and Data Model name validationContext.addLinkedCoreResource(SHORT_ID, dataModelName, declaration.getSourcePath(), true); Set<IBijectedAttribute> dataBinders = declaration.getBijectedAttributesByName(dataModelName); if(dataBinders!=null) { for (IBijectedAttribute dataBinder : dataBinders) { if(dataBinder.isOfType(BijectedAttributeType.DATA_BINDER) || dataBinder.isOfType(BijectedAttributeType.OUT)) { return; } } } addError(SeamValidationMessages.UNKNOWN_DATA_MODEL, SeamPreferences.UNKNOWN_DATA_MODEL, new String[]{dataModelName}, SeamUtil.getLocationOfAttribute(bijection, DataModelSelectionAttribute.VALUE), declaration.getResource()); } } /* * Validates methods of java classes. They must belong components. */ private void validateMethodsOfUnknownComponent(ISeamJavaComponentDeclaration declaration) { if(seamProject.getComponentsByPath(declaration.getSourcePath()).isEmpty()) { IMember member = declaration.getSourceMember(); try { if(member!=null && !Flags.isAbstract(member.getFlags())) { validateMethodOfUnknownComponent(SeamComponentMethodType.CREATE, declaration, SeamValidationMessages.CREATE_DOESNT_BELONG_TO_COMPONENT, SeamPreferences.CREATE_DOESNT_BELONG_TO_COMPONENT, CREATE_DOESNT_BELONG_TO_COMPONENT_MESSAGE_ID); validateMethodOfUnknownComponent(SeamComponentMethodType.UNWRAP, declaration, SeamValidationMessages.UNWRAP_DOESNT_BELONG_TO_COMPONENT, SeamPreferences.UNWRAP_DOESNT_BELONG_TO_COMPONENT, UNWRAP_DOESNT_BELONG_TO_COMPONENT_MESSAGE_ID); validateMethodOfUnknownComponent(SeamComponentMethodType.OBSERVER, declaration, SeamValidationMessages.OBSERVER_DOESNT_BELONG_TO_COMPONENT, SeamPreferences.OBSERVER_DOESNT_BELONG_TO_COMPONENT, OBSERVER_DOESNT_BELONG_TO_COMPONENT_MESSAGE_ID); } } catch (JavaModelException e) { SeamCorePlugin.getPluginLog().logError(e); } } validationContext.removeUnnamedCoreResource(SHORT_ID, declaration.getSourcePath()); } private void validateDestroyMethod(ISeamComponent component) { if(component.isStateless()) { ISeamJavaComponentDeclaration javaDeclaration = component.getJavaDeclaration(); Set<ISeamComponentMethod> methods = javaDeclaration.getMethodsByType(SeamComponentMethodType.DESTROY); if(methods==null) { return; } for (ISeamComponentMethod method : methods) { IMethod javaMethod = (IMethod)method.getSourceMember(); String methodName = javaMethod.getElementName(); if(javaDeclaration.getSourcePath().equals(javaMethod.getPath())) { validationContext.addLinkedCoreResource(SHORT_ID, component.getName(), javaDeclaration.getSourcePath(), true); ITextSourceReference methodNameLocation = getNameLocation(method); addError(SeamValidationMessages.DESTROY_METHOD_BELONGS_TO_STATELESS_SESSION_BEAN, SeamPreferences.DESTROY_METHOD_BELONGS_TO_STATELESS_SESSION_BEAN, new String[]{methodName}, methodNameLocation, method.getResource(), DESTROY_METHOD_BELONGS_TO_STATELESS_SESSION_BEAN_MESSAGE_ID); } } } } private void validateMethodOfUnknownComponent(SeamComponentMethodType methodType, ISeamJavaComponentDeclaration declaration, String message, String preferenceKey, int message_id) { Set<ISeamComponentMethod> methods = declaration.getMethodsByType(methodType); if(methods!=null && !methods.isEmpty()) { for (ISeamComponentMethod method : methods) { IMethod javaMethod = (IMethod)method.getSourceMember(); String methodName = javaMethod.getElementName(); if(declaration.getSourcePath().equals(javaMethod.getPath())) { ITextSourceReference methodNameLocation = getNameLocation(method); addError(message, preferenceKey, new String[]{methodName}, methodNameLocation, method.getResource(), message_id); validationContext.addUnnamedCoreResource(SHORT_ID, declaration.getSourcePath()); } } } else { validationContext.removeUnnamedCoreResource(SHORT_ID, declaration.getSourcePath()); } } private void validateXMLVersion(IFile file) { String ext = file.getFileExtension(); if(!"xml".equals(ext)) return; XModelObject o = EclipseResourceUtil.createObjectForResource(file); if(o == null) return; if(!o.getModelEntity().getName().startsWith("FileSeamComponent")) return; Set<String> vs = getXMLVersions(o); SeamRuntime runtime = seamProject.getRuntime(); if(runtime == null) return; String version = runtime.getVersion().toString(); String wrongVersion = null; for (String v: vs) { if(!v.startsWith(version)) { wrongVersion = v; break; } } if(wrongVersion != null) { addError( SeamValidationMessages.INVALID_XML_VERSION, SeamPreferences.INVALID_XML_VERSION, new String[]{wrongVersion, version}, file); } } private Set<String> getXMLVersions(XModelObject o) { Set<String> result = new HashSet<String>(); if(o.getModelEntity().getName().endsWith("11")) { result.add("1.1"); return result; } String sl = o.getAttributeValue("xsi:schemaLocation"); int i = 0; while(i >= 0 && i < sl.length()) { int j = sl.indexOf('-', i); if(j < 0) break; int k = sl.indexOf(".xsd", j); if(k < 0) break; String v = sl.substring(j + 1, k); if(isVersion(v)) result.add(v); i = k; } return result; } private boolean isVersion(String s) { if(s.length() == 0) return false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c != '.' && !Character.isDigit(c)) return false; } return true; } private void validatePageXML(IFile f) { if(f.isAccessible() && (f.getName().equals("pages.xml") || f.getName().endsWith(".page.xml"))) { XModelObject object = EclipseResourceUtil.createObjectForResource(f); if(object == null) return; if(object.getModelEntity().getName().startsWith(SeamPagesConstants.ENT_FILE_SEAM_PAGE)) { validatePageViewIds(object, f); } } } private void validatePageViewIds(XModelObject o, IFile f) { String entity = o.getModelEntity().getName(); validatePageViewId(o, f); if(entity.startsWith(SeamPagesConstants.ENT_REDIRECT) || entity.startsWith(SeamPagesConstants.ENT_RENDER)) { } else { XModelObject[] cs = o.getChildren(); for (XModelObject c: cs) { validatePageViewIds(c, f); } } } static String ATTR_NO_CONVERSATION_VIEW_ID = "no conversation view id"; static String ATTR_LOGIN_VIEW_ID = "login view id"; private void validatePageViewId(XModelObject object, IFile f) { validatePageViewId(object, f, SeamPagesConstants.ATTR_VIEW_ID); validatePageViewId(object, f, ATTR_NO_CONVERSATION_VIEW_ID); validatePageViewId(object, f, ATTR_LOGIN_VIEW_ID); } private void validatePageViewId(XModelObject object, IFile f, String attr) { if(object.getModelEntity().getAttribute(attr) == null) return; String path = object.getAttributeValue(attr); if(path == null || path.length() == 0 || path.indexOf('*') >= 0) return; path = path.replace('\\', '/'); if(path.indexOf('?') >= 0) { path = path.substring(0, path.indexOf('?')); } XModelObject target = object.getModel().getByPath(path); if(target == null) { XMLValueInfo i = new XMLValueInfo(object, attr); addError(NLS.bind(SeamValidationMessages.UNRESOLVED_VIEW_ID, path), SeamPreferences.UNRESOLVED_VIEW_ID, i, f); } } public IMarker addError(String message, String preferenceKey, String[] messageArguments, ITextSourceReference location, IResource target, int messageId) { IMarker marker = addError(message, preferenceKey, messageArguments, location, target); try{ if(marker!=null) { marker.setAttribute(MESSAGE_ID_ATTRIBUTE_NAME, new Integer(messageId)); } }catch(CoreException ex){ SeamCorePlugin.getDefault().logError(ex); } return marker; } }
true
true
private void validateXmlComponentDeclarations(ISeamComponent component) { String componentName = component.getName(); if(componentName!=null) { HashMap<String, ISeamXmlComponentDeclaration> usedPrecedences = new HashMap<String, ISeamXmlComponentDeclaration>(); Set<ISeamXmlComponentDeclaration> markedDeclarations = new HashSet<ISeamXmlComponentDeclaration>(); Set<ISeamJavaComponentDeclaration> markedJavaDeclarations = new HashSet<ISeamJavaComponentDeclaration>(); Set<ISeamXmlComponentDeclaration> declarations = component.getXmlDeclarations(); ISeamXmlComponentDeclaration firstNamedDeclaration = null; for (ISeamXmlComponentDeclaration declaration : declarations) { if(SeamUtil.isJar(declaration)) { return; } //do not check files declared in another project // if(declaration.getSeamProject() != seamProject) continue; validationContext.addLinkedCoreResource(SHORT_ID, componentName, declaration.getSourcePath(), true); String precedence = declaration.getPrecedence(); if(firstNamedDeclaration == null && declaration.getName()!=null) { firstNamedDeclaration = declaration; usedPrecedences.put(precedence, declaration); } if(declaration.getName()!=null && firstNamedDeclaration!=declaration) { // Check precedence ISeamXmlComponentDeclaration checkedDeclaration = usedPrecedences.get(precedence); if(checkedDeclaration==null) { usedPrecedences.put(precedence, declaration); } else { // Mark not-unique name. if(!markedDeclarations.contains(checkedDeclaration)) { // Mark first wrong declaration with that name IResource checkedDeclarationResource = checkedDeclaration.getResource(); ITextSourceReference location = ((SeamComponentDeclaration)checkedDeclaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); if(!SeamUtil.isEmptyLocation(location)) { addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, checkedDeclarationResource, NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } markedDeclarations.add(checkedDeclaration); } // Mark next wrong declaration with that name markedDeclarations.add(declaration); ITextSourceReference location = ((SeamComponentDeclaration)declaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); if(!SeamUtil.isEmptyLocation(location)) { addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, declaration.getResource(), NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } } } // Check Java declarations with the same name Set<ISeamContextVariable> vars = seamProject.getVariablesByName(componentName); for (ISeamContextVariable variable : vars) { if(variable instanceof ISeamComponent) { ISeamComponent c = (ISeamComponent)variable; Set<ISeamComponentDeclaration> decls = c.getAllDeclarations(); for (ISeamComponentDeclaration dec : decls) { if(dec instanceof ISeamJavaComponentDeclaration) { ISeamJavaComponentDeclaration javaDec = (ISeamJavaComponentDeclaration)dec; // Check names if(declaration.getClassName()!=null && javaDec.getName()!=null && javaDec.getName().equals(declaration.getName())) { // Check precedences String javaPrecedence = "" + javaDec.getPrecedence(); if(javaPrecedence.equals(precedence) && !isBuiltInComponentName(componentName)) { if(!markedJavaDeclarations.contains(javaDec)) { markedJavaDeclarations.add(javaDec); ITextSourceReference location = ((SeamComponentDeclaration)javaDec).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, javaDec.getResource(), NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } if(!markedDeclarations.contains(declaration)) { markedDeclarations.add(declaration); ITextSourceReference location = ((SeamComponentDeclaration)declaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, declaration.getResource(), NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } } } } } } } String className = declaration.getClassName(); IType type = null; if(className!=null) { // validate class name try { IProject p = seamProject.getProject(); // type = EclipseJavaUtil.findType(EclipseResourceUtil.getJavaProject(p), className); IJavaProject javaProject = EclipseResourceUtil.getJavaProject(p); if(javaProject==null) { SeamCorePlugin.getDefault().logWarning("Can't get Java project for " + seamProject.getProject()!=null?seamProject.getProject().getName():"" + " Seam project."); return; } type = javaProject.findType(className); if(type==null) { // Mark wrong class name ITextSourceReference location = ((SeamComponentDeclaration)declaration).getLocationFor(ISeamXmlComponentDeclaration.CLASS); if(SeamUtil.isEmptyLocation(location)) { location = ((SeamComponentDeclaration)declaration).getLocationFor(ISeamXmlComponentDeclaration.NAME); } if(SeamUtil.isEmptyLocation(location)) { location = declaration; } if(!declaration.isClassNameGuessed()) { addError(SeamValidationMessages.UNKNOWN_COMPONENT_CLASS_NAME, SeamPreferences.UNKNOWN_COMPONENT_CLASS_NAME, new String[]{className}, location, declaration.getResource()); } else { addError(SeamValidationMessages.UNKNOWN_COMPONENT_CLASS_NAME, SeamPreferences.UNKNOWN_COMPONENT_CLASS_NAME_GUESS, new String[]{className}, location, declaration.getResource()); } return; } else if(!type.isBinary()) { validationContext.addLinkedCoreResource(SHORT_ID, componentName, type.getResource().getFullPath(), true); } } catch (JavaModelException e) { SeamCorePlugin.getDefault().logError(SeamCoreMessages.SEAM_CORE_VALIDATOR_ERROR_VALIDATING_SEAM_CORE, e); } } // validate properties Collection<ISeamProperty> properties = declaration.getProperties(); for (ISeamProperty property : properties) { if(SeamUtil.isJar(property)) { return; } String name = property.getName(); if(name==null) { return; } if(type==null && component.getJavaDeclaration()!=null) { IMember member = component.getJavaDeclaration().getSourceMember(); if(member instanceof IType) { type = (IType)member; } } if(type!=null) { boolean ok = type.isBinary() || SeamUtil.findProperty(type, name)!=null; if(!ok) { addError(SeamValidationMessages.UNKNOWN_COMPONENT_PROPERTY, SeamPreferences.UNKNOWN_COMPONENT_PROPERTY, new String[]{type.getElementName(), componentName, name}, property, declaration.getResource(), UNKNOWN_COMPONENT_PROPERTY_ID); } } } } } }
private void validateXmlComponentDeclarations(ISeamComponent component) { String componentName = component.getName(); if(componentName!=null) { HashMap<String, ISeamXmlComponentDeclaration> usedPrecedences = new HashMap<String, ISeamXmlComponentDeclaration>(); Set<ISeamXmlComponentDeclaration> markedDeclarations = new HashSet<ISeamXmlComponentDeclaration>(); Set<ISeamJavaComponentDeclaration> markedJavaDeclarations = new HashSet<ISeamJavaComponentDeclaration>(); Set<ISeamXmlComponentDeclaration> declarations = component.getXmlDeclarations(); ISeamXmlComponentDeclaration firstNamedDeclaration = null; for (ISeamXmlComponentDeclaration declaration : declarations) { if(SeamUtil.isJar(declaration)) { return; } //do not check files declared in another project // if(declaration.getSeamProject() != seamProject) continue; validationContext.addLinkedCoreResource(SHORT_ID, componentName, declaration.getSourcePath(), true); String precedence = declaration.getPrecedence(); if(firstNamedDeclaration == null && declaration.getName()!=null) { firstNamedDeclaration = declaration; usedPrecedences.put(precedence, declaration); } if(declaration.getName()!=null && firstNamedDeclaration!=declaration) { // Check precedence ISeamXmlComponentDeclaration checkedDeclaration = usedPrecedences.get(precedence); if(checkedDeclaration==null) { usedPrecedences.put(precedence, declaration); } else { // Mark not-unique name. if(!markedDeclarations.contains(checkedDeclaration)) { // Mark first wrong declaration with that name IResource checkedDeclarationResource = checkedDeclaration.getResource(); ITextSourceReference location = ((SeamComponentDeclaration)checkedDeclaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); if(!SeamUtil.isEmptyLocation(location)) { addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, checkedDeclarationResource, NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } markedDeclarations.add(checkedDeclaration); } // Mark next wrong declaration with that name markedDeclarations.add(declaration); ITextSourceReference location = ((SeamComponentDeclaration)declaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); if(!SeamUtil.isEmptyLocation(location)) { addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, declaration.getResource(), NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } } } // Check Java declarations with the same name Set<ISeamContextVariable> vars = seamProject.getVariablesByName(componentName); for (ISeamContextVariable variable : vars) { if(variable instanceof ISeamComponent) { ISeamComponent c = (ISeamComponent)variable; Set<ISeamComponentDeclaration> decls = c.getAllDeclarations(); for (ISeamComponentDeclaration dec : decls) { if(dec instanceof ISeamJavaComponentDeclaration) { ISeamJavaComponentDeclaration javaDec = (ISeamJavaComponentDeclaration)dec; // Check names if(declaration.getClassName()!=null && javaDec.getName()!=null && javaDec.getName().equals(declaration.getName())) { // Check precedences String javaPrecedence = "" + javaDec.getPrecedence(); if(javaPrecedence.equals(precedence) && !isBuiltInComponentName(componentName)) { if(!markedJavaDeclarations.contains(javaDec)) { markedJavaDeclarations.add(javaDec); ITextSourceReference location = ((SeamComponentDeclaration)javaDec).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, javaDec.getResource(), NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } if(!markedDeclarations.contains(declaration)) { markedDeclarations.add(declaration); ITextSourceReference location = ((SeamComponentDeclaration)declaration).getLocationFor(SeamComponentDeclaration.PATH_OF_NAME); addError(SeamValidationMessages.NONUNIQUE_COMPONENT_NAME_MESSAGE, SeamPreferences.NONUNIQUE_COMPONENT_NAME, new String[]{componentName}, location, declaration.getResource(), NONUNIQUE_COMPONENT_NAME_MESSAGE_ID); } } } } } } } String className = declaration.getClassName(); IType type = null; if(className!=null) { // validate class name try { IProject p = seamProject.getProject(); // type = EclipseJavaUtil.findType(EclipseResourceUtil.getJavaProject(p), className); IJavaProject javaProject = EclipseResourceUtil.getJavaProject(p); if(javaProject==null) { SeamCorePlugin.getDefault().logWarning("Can't get Java project for " + seamProject.getProject()!=null?seamProject.getProject().getName():"" + " Seam project."); return; } type = javaProject.findType(className); if(type==null) { // Mark wrong class name ITextSourceReference location = ((SeamComponentDeclaration)declaration).getLocationFor(ISeamXmlComponentDeclaration.CLASS); if(SeamUtil.isEmptyLocation(location)) { location = ((SeamComponentDeclaration)declaration).getLocationFor(ISeamXmlComponentDeclaration.NAME); } if(SeamUtil.isEmptyLocation(location)) { location = declaration; } if(!declaration.isClassNameGuessed()) { addError(SeamValidationMessages.UNKNOWN_COMPONENT_CLASS_NAME, SeamPreferences.UNKNOWN_COMPONENT_CLASS_NAME, new String[]{className}, location, declaration.getResource()); } else { addError(SeamValidationMessages.UNKNOWN_COMPONENT_CLASS_NAME, SeamPreferences.UNKNOWN_COMPONENT_CLASS_NAME_GUESS, new String[]{className}, location, declaration.getResource()); } } else if(!type.isBinary()) { validationContext.addLinkedCoreResource(SHORT_ID, componentName, type.getResource().getFullPath(), true); } } catch (JavaModelException e) { SeamCorePlugin.getDefault().logError(SeamCoreMessages.SEAM_CORE_VALIDATOR_ERROR_VALIDATING_SEAM_CORE, e); } } // validate properties Collection<ISeamProperty> properties = declaration.getProperties(); for (ISeamProperty property : properties) { if(SeamUtil.isJar(property)) { return; } String name = property.getName(); if(name==null) { return; } if(type==null && component.getJavaDeclaration()!=null) { IMember member = component.getJavaDeclaration().getSourceMember(); if(member instanceof IType) { type = (IType)member; } } if(type!=null) { boolean ok = type.isBinary() || SeamUtil.findProperty(type, name)!=null; if(!ok) { addError(SeamValidationMessages.UNKNOWN_COMPONENT_PROPERTY, SeamPreferences.UNKNOWN_COMPONENT_PROPERTY, new String[]{type.getElementName(), componentName, name}, property, declaration.getResource(), UNKNOWN_COMPONENT_PROPERTY_ID); } } } } } }
diff --git a/src/org/thiesen/helenaorm/HelenaDAO.java b/src/org/thiesen/helenaorm/HelenaDAO.java index 7f5b1c7..b156704 100644 --- a/src/org/thiesen/helenaorm/HelenaDAO.java +++ b/src/org/thiesen/helenaorm/HelenaDAO.java @@ -1,410 +1,410 @@ /* * The MIT License * * Copyright (c) 2010 Marcus Thiesen ([email protected]) * * This file is part of HelenaORM. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.thiesen.helenaorm; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.Map.Entry; import me.prettyprint.cassandra.dao.Command; import me.prettyprint.cassandra.service.Keyspace; import org.apache.cassandra.thrift.Column; import org.apache.cassandra.thrift.ColumnParent; import org.apache.cassandra.thrift.ColumnPath; import org.apache.cassandra.thrift.NotFoundException; import org.apache.cassandra.thrift.SlicePredicate; import org.apache.cassandra.thrift.SuperColumn; import org.apache.commons.beanutils.PropertyUtils; import org.thiesen.helenaorm.annotations.HelenaBean; import org.thiesen.helenaorm.annotations.KeyProperty; import org.thiesen.helenaorm.annotations.SuperColumnProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.ImmutableSet.Builder; public class HelenaDAO<T> { private final String _hostname; private final int _port; private final String _keyspace; private final String _columnFamily; private final PropertyDescriptor[] _propertyDescriptors; private final ImmutableList<byte[]> _columnNames; private final Class<T> _clz; private PropertyDescriptor _keyPropertyDescriptor; private PropertyDescriptor _superColumnPropertyDescriptor; private final TypeConverter _typeConverter; HelenaDAO( final Class<T> clz, final String hostname, final int port, final SerializeUnknownClasses serializationPolicy, final ImmutableMap<Class<?>, TypeMapping<?>> typeMappings ) { if ( !clz.isAnnotationPresent( HelenaBean.class ) ) { throw new IllegalArgumentException("Trying to get a HelenaDAO for a class that is not mapped with @HelenaBean"); } final HelenaBean annotation = clz.getAnnotation( HelenaBean.class ); _typeConverter = new TypeConverter( typeMappings, serializationPolicy ); _clz = clz; _propertyDescriptors = PropertyUtils.getPropertyDescriptors( clz ); _columnFamily = annotation.columnFamily(); _hostname = hostname; _port = port; _keyspace = annotation.keyspace(); final Builder<byte[]> setBuilder = ImmutableSet.<byte[]>builder(); for ( final PropertyDescriptor descriptor : _propertyDescriptors ) { setBuilder.add( _typeConverter.stringToBytes( descriptor.getName() ) ); if ( isKeyProperty( descriptor ) ) { _keyPropertyDescriptor = descriptor; } if ( isSuperColumnProperty( descriptor ) ) { _superColumnPropertyDescriptor = descriptor; } } _columnNames = ImmutableList.copyOf( setBuilder.build() ); if ( _keyPropertyDescriptor == null ) { throw new HelenaRuntimeException("Could not find key of class " + clz.getName() + ", did you annotate with @KeyProperty" ); } } private boolean isSuperColumnProperty( final PropertyDescriptor descriptor ) { return safeIsAnnotationPresent( descriptor, SuperColumnProperty.class ); } public void insert( final T object ) { final MarshalledObject marshalledObject = MarshalledObject.create(); for ( final PropertyDescriptor d : _propertyDescriptors ) { if ( isReadWrite( d ) ) { try { final String name = d.getName(); final byte[] value = _typeConverter.convertValueObjectToByteArray( PropertyUtils.getProperty( object, name ) ); if ( isKeyProperty( d ) ) { marshalledObject.setKey( value ); - } if ( isSuperColumnProperty( d ) ) { + } else if ( isSuperColumnProperty( d ) ) { marshalledObject.setSuperColumn( value ); } else { marshalledObject.addValue( name, value ); } } catch ( final NoSuchMethodException e ) { throw new HelenaRuntimeException( e ); } catch ( final IllegalAccessException e ) { throw new HelenaRuntimeException( e ); } catch ( final InvocationTargetException e ) { throw new HelenaRuntimeException( e ); } } } if ( marshalledObject.getKey() == null || marshalledObject.getKey().length == 0 ) { throw new HelenaRuntimeException("Key is null, can't store object"); } store( marshalledObject ); } private boolean isKeyProperty( final PropertyDescriptor d ) { return safeIsAnnotationPresent( d, KeyProperty.class ); } private boolean safeIsAnnotationPresent( final PropertyDescriptor d, final Class<? extends Annotation> annotation ) { return nullSafeAnnotationPresent( annotation, d.getReadMethod() ) || nullSafeAnnotationPresent( annotation, d.getWriteMethod() ); } private boolean nullSafeAnnotationPresent( final Class<? extends Annotation> annotation, final Method method ) { if ( method != null ) { if ( method.isAnnotationPresent( annotation ) ) { return true; } } return false; } private boolean isReadWrite( final PropertyDescriptor d ) { return d.getReadMethod() != null && d.getWriteMethod() != null; } private void store( final MarshalledObject marshalledObject ) { final byte[] idColumn = marshalledObject.getKey(); final List<Column> columnList = Lists.newLinkedList(); final long timestamp = System.currentTimeMillis(); for ( final Map.Entry<String, byte[]> property : marshalledObject.getEntries() ) { columnList.add( toColumn( property, timestamp ) ); } final Map<String, List<Column>> columnMap; final Map<String, List<SuperColumn>> superColumnMap; if ( marshalledObject.isSuperColumnPresent() ) { final SuperColumn superColumn = new SuperColumn( marshalledObject.getSuperColumn(), columnList ); superColumnMap = ImmutableMap.<String, List<SuperColumn>>of( _columnFamily, ImmutableList.of( superColumn ) ); columnMap = null; } else { columnMap = ImmutableMap.<String,List<Column>>of( _columnFamily, columnList ); superColumnMap = null; } try { execute(new Command<Void>(){ @Override public Void execute(final Keyspace ks) throws Exception { ks.batchInsert( _typeConverter.bytesToString( idColumn ), columnMap, superColumnMap ); return null; } } ); } catch ( final Exception e ) { throw new HelenaRuntimeException(e); } } private Column toColumn( final Entry<String, byte[]> property, final long timestamp ) { return new Column( _typeConverter.stringToBytes( property.getKey() ), property.getValue(), timestamp ); } private <V> V execute(final Command<V> command) throws Exception { return command.execute(_hostname, _port, _keyspace); } public T get(final String key) { final ColumnParent parent = makeColumnParent(); final SlicePredicate predicate = makeSlicePredicateWithAllPropertyColumns(); try { return execute(new Command<T>(){ @Override public T execute(final Keyspace ks) throws Exception { try { final List<Column> slice = ks.getSlice( key, parent , predicate ); return applyColumns( key, slice ); } catch (final NotFoundException e) { return null; } } }); } catch ( final Exception e ) { throw new HelenaRuntimeException( e ); } } private T applyColumns( final String key, final Iterable<Column> slice ) { try { final T newInstance = _clz.newInstance(); PropertyUtils.setProperty( newInstance, _keyPropertyDescriptor.getName(), _typeConverter.convertByteArrayToValueObject( _keyPropertyDescriptor.getReadMethod().getReturnType(), _typeConverter.stringToBytes( key ) ) ); for ( final Column c : slice ) { final String name = _typeConverter.bytesToString( c.name ); if ( PropertyUtils.isWriteable( newInstance, name ) ) { final PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor( newInstance, name ); final Class<?> returnType = propertyDescriptor.getReadMethod().getReturnType(); PropertyUtils.setProperty( newInstance, name, _typeConverter.convertByteArrayToValueObject( returnType, c.value ) ); } } return newInstance; } catch ( final InstantiationException e ) { throw new HelenaRuntimeException("Could not instanciate " + _clz.getName(), e ); } catch ( final IllegalAccessException e ) { throw new HelenaRuntimeException("Could not instanciate " + _clz.getName(), e ); } catch ( final InvocationTargetException e ) { throw new HelenaRuntimeException( e ); } catch ( final NoSuchMethodException e ) { throw new HelenaRuntimeException( e ); } } private List<T> applyColumns( final String key, final List<SuperColumn> slice ) { final ImmutableList.Builder<T> listBuilder = ImmutableList.builder(); for ( final SuperColumn superColumn : slice ) { final T object = applyColumns( key, superColumn.getColumns() ); applySuperColumnName( object, superColumn.getName() ); listBuilder.add( object ); } return listBuilder.build(); } private void applySuperColumnName( final T object, final byte[] value ) { final Class<?> returnType = _superColumnPropertyDescriptor.getReadMethod().getReturnType(); try { PropertyUtils.setProperty( object, _superColumnPropertyDescriptor.getName(), _typeConverter.convertByteArrayToValueObject( returnType, value ) ); } catch ( final IllegalAccessException e ) { throw new HelenaRuntimeException( e ); } catch ( final InvocationTargetException e ) { throw new HelenaRuntimeException( e ); } catch ( final NoSuchMethodException e ) { throw new HelenaRuntimeException( e ); } } public void delete( final T object ) { delete( getKeyFrom( object ) ); } private String getKeyFrom( final T object ) { try { return _typeConverter.bytesToString( _typeConverter.convertValueObjectToByteArray( PropertyUtils.getProperty( object, _keyPropertyDescriptor.getName() ) ) ); } catch ( final IllegalAccessException e ) { throw new HelenaRuntimeException( e ); } catch ( final InvocationTargetException e ) { throw new HelenaRuntimeException( e ); } catch ( final NoSuchMethodException e ) { throw new HelenaRuntimeException( e ); } } public void delete( final String key ) { try { execute(new Command<Void>(){ @Override public Void execute(final Keyspace ks) throws Exception { ks.remove( key, new ColumnPath( _columnFamily ) ); return null; } }); } catch ( final Exception e ) { throw new HelenaRuntimeException( e ); } } public List<T> get( final Iterable<String> keys ) { final ColumnParent parent = makeColumnParent(); final SlicePredicate predicate = makeSlicePredicateWithAllPropertyColumns(); try { return execute(new Command<List<T>>(){ @Override public List<T> execute(final Keyspace ks) throws Exception { final Map<String,List<Column>> slice = ks.multigetSlice( ImmutableList.copyOf( keys ), parent , predicate ); return convertToList( slice ); } }); } catch ( final Exception e ) { throw new HelenaRuntimeException( e ); } } public List<T> getRange( final String keyStart, final String keyEnd, final int amount ) { final ColumnParent parent = makeColumnParent(); final SlicePredicate predicate = makeSlicePredicateWithAllPropertyColumns(); try { return execute(new Command<List<T>>(){ @Override public List<T> execute(final Keyspace ks) throws Exception { final Map<String,List<Column>> slice = ks.getRangeSlice( parent, predicate, keyStart, keyEnd , amount ); return convertToList( slice ); } }); } catch ( final Exception e ) { throw new HelenaRuntimeException( e ); } } private SlicePredicate makeSlicePredicateWithAllPropertyColumns() { final SlicePredicate predicate = new SlicePredicate(); predicate.setColumn_names( _columnNames ); return predicate; } private ColumnParent makeColumnParent() { final ColumnParent parent = new ColumnParent(); parent.setColumn_family( _columnFamily ); return parent; } private List<T> convertToList( final Map<String, List<Column>> slice ) { final ImmutableList.Builder<T> listBuilder = ImmutableList.<T>builder(); for ( final Map.Entry<String, List<Column>> entry : slice.entrySet() ) { listBuilder.add( applyColumns( entry.getKey(), entry.getValue() ) ); } return listBuilder.build(); } public List<T> get( final String key, final Iterable<String> columns ) { final ColumnParent parent = makeColumnParent(); final SlicePredicate predicate = makeSlicePredicateWithColumns( columns ); try { return execute(new Command<List<T>>(){ @Override public List<T> execute(final Keyspace ks) throws Exception { try { final List<SuperColumn> slice = ks.getSuperSlice( key, parent, predicate ); return applyColumns( key, slice ); } catch (final NotFoundException e) { return null; } } }); } catch ( final Exception e ) { throw new HelenaRuntimeException( e ); } } private SlicePredicate makeSlicePredicateWithColumns( final Iterable<String> columns ) { final SlicePredicate predicate = new SlicePredicate(); predicate.setColumn_names( ImmutableList.copyOf( Iterables.transform( columns, _typeConverter.toByteArrayFunction() ) ) ); return predicate; } }
true
true
public void insert( final T object ) { final MarshalledObject marshalledObject = MarshalledObject.create(); for ( final PropertyDescriptor d : _propertyDescriptors ) { if ( isReadWrite( d ) ) { try { final String name = d.getName(); final byte[] value = _typeConverter.convertValueObjectToByteArray( PropertyUtils.getProperty( object, name ) ); if ( isKeyProperty( d ) ) { marshalledObject.setKey( value ); } if ( isSuperColumnProperty( d ) ) { marshalledObject.setSuperColumn( value ); } else { marshalledObject.addValue( name, value ); } } catch ( final NoSuchMethodException e ) { throw new HelenaRuntimeException( e ); } catch ( final IllegalAccessException e ) { throw new HelenaRuntimeException( e ); } catch ( final InvocationTargetException e ) { throw new HelenaRuntimeException( e ); } } } if ( marshalledObject.getKey() == null || marshalledObject.getKey().length == 0 ) { throw new HelenaRuntimeException("Key is null, can't store object"); } store( marshalledObject ); }
public void insert( final T object ) { final MarshalledObject marshalledObject = MarshalledObject.create(); for ( final PropertyDescriptor d : _propertyDescriptors ) { if ( isReadWrite( d ) ) { try { final String name = d.getName(); final byte[] value = _typeConverter.convertValueObjectToByteArray( PropertyUtils.getProperty( object, name ) ); if ( isKeyProperty( d ) ) { marshalledObject.setKey( value ); } else if ( isSuperColumnProperty( d ) ) { marshalledObject.setSuperColumn( value ); } else { marshalledObject.addValue( name, value ); } } catch ( final NoSuchMethodException e ) { throw new HelenaRuntimeException( e ); } catch ( final IllegalAccessException e ) { throw new HelenaRuntimeException( e ); } catch ( final InvocationTargetException e ) { throw new HelenaRuntimeException( e ); } } } if ( marshalledObject.getKey() == null || marshalledObject.getKey().length == 0 ) { throw new HelenaRuntimeException("Key is null, can't store object"); } store( marshalledObject ); }
diff --git a/zendserver-deployment-eclipse/org.zend.php.zendserver.deployment.debug.core/src/org/zend/php/zendserver/deployment/debug/core/DebugModeManager.java b/zendserver-deployment-eclipse/org.zend.php.zendserver.deployment.debug.core/src/org/zend/php/zendserver/deployment/debug/core/DebugModeManager.java index e9634d96..17035509 100644 --- a/zendserver-deployment-eclipse/org.zend.php.zendserver.deployment.debug.core/src/org/zend/php/zendserver/deployment/debug/core/DebugModeManager.java +++ b/zendserver-deployment-eclipse/org.zend.php.zendserver.deployment.debug.core/src/org/zend/php/zendserver/deployment/debug/core/DebugModeManager.java @@ -1,181 +1,179 @@ package org.zend.php.zendserver.deployment.debug.core; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.preferences.DefaultScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.php.internal.debug.core.debugger.AbstractDebuggerConfiguration; import org.eclipse.php.internal.debug.core.preferences.PHPDebuggersRegistry; import org.eclipse.php.internal.debug.core.zend.communication.DebuggerCommunicationDaemon; import org.zend.sdklib.SdkException; import org.zend.sdklib.application.ZendDebugMode; import org.zend.sdklib.application.ZendDebugMode.State; import org.zend.sdklib.manager.TargetsManager; import org.zend.sdklib.target.IZendTarget; public class DebugModeManager { public static final int[] prohibitedPorts = new int[] { 10081, 10082 }; private static final String DEBUG_STOP = "debug_stop"; //$NON-NLS-1$ private static final String DEBUG_HOST = "debug_host"; //$NON-NLS-1$ private static final String DEBUG_PORT = "debug_port"; //$NON-NLS-1$ private static final String LOCALHOST = "localhost"; //$NON-NLS-1$ public static final String DEBUG_MODE_NODE = Activator.PLUGIN_ID + "/debugMode"; //$NON-NLS-1$ public static final String FILTER_SEPARATOR = ","; //$NON-NLS-1$ private static final String CLIENT_HOST_KEY = "org.eclipse.php.debug.coreclient_ip"; //$NON-NLS-1$ private static final String DEBUG_PLUGIN_ID = "org.eclipse.php.debug.core"; //$NON-NLS-1$ private static DebugModeManager manager; private Map<IZendTarget, Boolean> targets; private DebugModeManager() { this.targets = new HashMap<IZendTarget, Boolean>(); } public static DebugModeManager getManager() { if (manager == null) { manager = new DebugModeManager(); } return manager; } @SuppressWarnings("restriction") public IStatus startDebugMode(IZendTarget target) { ZendDebugMode debugMode = new ZendDebugMode(target.getId()); Map<String, String> options = new HashMap<String, String>(); debugMode.setFilters(getFilters(target)); AbstractDebuggerConfiguration debuggerConfiguration = PHPDebuggersRegistry .getDebuggerConfiguration(DebuggerCommunicationDaemon.ZEND_DEBUGGER_ID); if (debuggerConfiguration != null) { int port = debuggerConfiguration.getPort(); options.put(DEBUG_PORT, String.valueOf(port)); options.put(DEBUG_HOST, getDebugHosts(target)); options.put(DEBUG_STOP, "1"); //$NON-NLS-1$ debugMode.setOptions(options); } State result = State.ERROR; try { result = debugMode.start(); } catch (SdkException e) { Activator.log(e); - return new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getCause() - .getMessage()); } if (result == State.STARTING) { targets.put(target, true); return new Status(IStatus.OK, Activator.PLUGIN_ID, Messages.DebugModeManager_StartSuccess); } if (result == State.STARTED) { return new Status(IStatus.WARNING, Activator.PLUGIN_ID, Messages.DebugModeManager_AlreadyStartedWarning); } return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.DebugModeManager_CannotStartError); } public IStatus stopDebugMode(IZendTarget target) { ZendDebugMode debugMode = new ZendDebugMode(target.getId()); State result = State.ERROR; try { result = debugMode.stop(); } catch (SdkException e) { Activator.log(e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getCause() .getMessage()); } if (result == State.STOPPING) { targets.put(target, false); return new Status(IStatus.OK, Activator.PLUGIN_ID, Messages.DebugModeManager_StopSuccess); } if (result == State.STOPPED) { if (isInDebugMode(target)) { targets.put(target, false); } return new Status(IStatus.WARNING, Activator.PLUGIN_ID, Messages.DebugModeManager_AlreadyStoppedWarning); } return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.DebugModeManager_CannotStopError); } public IStatus restartDebugMode(IZendTarget target) { IStatus stopStatus = stopDebugMode(target); if (stopStatus.getSeverity() != IStatus.ERROR) { return startDebugMode(target); } else { return stopStatus; } } public boolean isInDebugMode(IZendTarget target) { Boolean value = targets.get(target); if (value == null || !value) { return false; } return true; } public static void stopAll() { DebugModeManager manager = getManager(); Set<IZendTarget> keys = manager.targets.keySet(); for (IZendTarget target : keys) { if (manager.isInDebugMode(target)) { manager.stopDebugMode(target); } } } private String getDebugHosts(IZendTarget target) { if (TargetsManager.isOpenShift(target) || TargetsManager.isPhpcloud(target)) { return LOCALHOST; } String host = target.getHost().getHost(); if (host.equals(LOCALHOST)) { return LOCALHOST; } IEclipsePreferences prefs = InstanceScope.INSTANCE .getNode(DEBUG_PLUGIN_ID); String clientHosts = prefs.get(CLIENT_HOST_KEY, (String) null); if (clientHosts == null) { IEclipsePreferences defaultPrefs = DefaultScope.INSTANCE .getNode(DEBUG_PLUGIN_ID); clientHosts = defaultPrefs.get(CLIENT_HOST_KEY, (String) null); } return clientHosts; } private String[] getFilters(IZendTarget target) { IEclipsePreferences prefs = InstanceScope.INSTANCE .getNode(DEBUG_MODE_NODE); String val = prefs.get(target.getId(), null); List<String> filters = null; if (val != null && val.length() > 0) { filters = new ArrayList<String>(Arrays.asList(val .split(FILTER_SEPARATOR))); } else { filters = new ArrayList<String>(); } return filters.toArray(new String[0]); } }
true
true
public IStatus startDebugMode(IZendTarget target) { ZendDebugMode debugMode = new ZendDebugMode(target.getId()); Map<String, String> options = new HashMap<String, String>(); debugMode.setFilters(getFilters(target)); AbstractDebuggerConfiguration debuggerConfiguration = PHPDebuggersRegistry .getDebuggerConfiguration(DebuggerCommunicationDaemon.ZEND_DEBUGGER_ID); if (debuggerConfiguration != null) { int port = debuggerConfiguration.getPort(); options.put(DEBUG_PORT, String.valueOf(port)); options.put(DEBUG_HOST, getDebugHosts(target)); options.put(DEBUG_STOP, "1"); //$NON-NLS-1$ debugMode.setOptions(options); } State result = State.ERROR; try { result = debugMode.start(); } catch (SdkException e) { Activator.log(e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getCause() .getMessage()); } if (result == State.STARTING) { targets.put(target, true); return new Status(IStatus.OK, Activator.PLUGIN_ID, Messages.DebugModeManager_StartSuccess); } if (result == State.STARTED) { return new Status(IStatus.WARNING, Activator.PLUGIN_ID, Messages.DebugModeManager_AlreadyStartedWarning); } return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.DebugModeManager_CannotStartError); }
public IStatus startDebugMode(IZendTarget target) { ZendDebugMode debugMode = new ZendDebugMode(target.getId()); Map<String, String> options = new HashMap<String, String>(); debugMode.setFilters(getFilters(target)); AbstractDebuggerConfiguration debuggerConfiguration = PHPDebuggersRegistry .getDebuggerConfiguration(DebuggerCommunicationDaemon.ZEND_DEBUGGER_ID); if (debuggerConfiguration != null) { int port = debuggerConfiguration.getPort(); options.put(DEBUG_PORT, String.valueOf(port)); options.put(DEBUG_HOST, getDebugHosts(target)); options.put(DEBUG_STOP, "1"); //$NON-NLS-1$ debugMode.setOptions(options); } State result = State.ERROR; try { result = debugMode.start(); } catch (SdkException e) { Activator.log(e); } if (result == State.STARTING) { targets.put(target, true); return new Status(IStatus.OK, Activator.PLUGIN_ID, Messages.DebugModeManager_StartSuccess); } if (result == State.STARTED) { return new Status(IStatus.WARNING, Activator.PLUGIN_ID, Messages.DebugModeManager_AlreadyStartedWarning); } return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.DebugModeManager_CannotStartError); }
diff --git a/src/net/gamerservices/npcx/npcx.java b/src/net/gamerservices/npcx/npcx.java index 232afda..79d6fa8 100644 --- a/src/net/gamerservices/npcx/npcx.java +++ b/src/net/gamerservices/npcx/npcx.java @@ -1,2665 +1,2665 @@ package net.gamerservices.npcx; import com.nijiko.coelho.iConomy.iConomy; import net.gamerservices.npclibfork.BasicHumanNpc; import net.gamerservices.npclibfork.BasicHumanNpcList; import net.gamerservices.npclibfork.NpcEntityTargetEvent; import net.gamerservices.npclibfork.NpcSpawner; import net.gamerservices.npclibfork.NpcEntityTargetEvent.NpcTargetReason; import org.bukkit.plugin.PluginManager; import java.util.HashMap; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.BlockIterator; import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.entity.Zombie; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.event.*; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.entity.CreatureType; import java.util.ConcurrentModificationException; import java.util.List; import java.util.Properties; import java.util.Random; import java.util.Timer; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import org.bukkit.event.Event.Type; import java.util.logging.Logger; import org.bukkit.event.Event.Priority; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.*; public class npcx extends JavaPlugin { private static final Logger logger = Logger.getLogger("Minecraft"); private npcxEListener mEntityListener; private npcxPListener mPlayerListener; private npcxWListener mWorldListener; private npcxBListener mBlockListener; public myUniverse universe; // iconomy private static PluginListener PluginListener = null; private static iConomy iConomy = null; private static Server Server = null; // end iconomy public BasicHumanNpcList npclist = new BasicHumanNpcList(); private Timer tick = new Timer(); private Timer longtick = new Timer(); public boolean checkchunks = false; public void onNPCDeath(BasicHumanNpc npc) { for (myPlayer player : universe.players.values()){ if (player.target == npc) { player.target = null; } } for (myLoottable lt : this.universe.loottables) { if (npc.parent != null) { if (npc.parent.loottable == lt) { for (myLoottable_entry lte : lt.loottable_entries) { npc.getBukkitEntity().getWorld().dropItem( new Location ( npc.getBukkitEntity().getWorld(), npc.getBukkitEntity().getLocation().getX(), npc.getBukkitEntity().getLocation().getY(), npc.getBukkitEntity().getLocation().getZ() ), new ItemStack(lte.itemid)); } } } } npclist.remove(npc); universe.npcs.remove(npc); //System.out.println("Removing NPC"); NpcSpawner.RemoveBasicHumanNpc(npc); if (npc.parent != null) { npc.parent.spawngroup.activecountdown = 100; } } public double getDistance(double d, double e) { return d-e; } public void longCheck() { this.universe.commitPlayerFactions(); this.universe.commitNpcFactions(); longtick.schedule(new LongTick(this), 1 * 20000); } public void think() { // check fhunks if (this.checkchunks == true) { if (this.universe.checkChunks()) { this.checkchunks = false; } else { this.checkchunks = true; } } tick.schedule(new Tick(this), 1 * 500); fixDead(); // check npc logic try { // // NPC THINK // for (myNPC npc : universe.npcs.values()) { if (npc.npc != null) { npc.npc.doThinkGreater(); //always do pathgroups after think() npc.npc.doThinkLesser(); if (this.universe.players.size() > 0) { try { for (myPlayer player : this.universe.players.values()) { if (player.player != null) { if (player.player.getHealth() > 0) { double distancex = getDistance(npc.npc.getBukkitEntity().getLocation().getX(), player.player.getLocation().getX()); double distancey = getDistance(npc.npc.getBukkitEntity().getLocation().getY(), player.player.getLocation().getY()); double distancez = getDistance(npc.npc.getBukkitEntity().getLocation().getZ(), player.player.getLocation().getZ()); if (distancex > -5 && distancey > -5 && distancez > -5 && distancex < 5 && distancey < 5 && distancez < 5) { if (npc.parent != null) { if (npc.npc.parent.faction != null) { if (npc.npc.parent.faction.base <= -1000) { npc.npc.aggro = player.player; npc.npc.follow = player.player; } else { // Add the players faction standing onto this base int newfactvalue = npc.npc.parent.faction.base + player.getPlayerFactionStanding(npc.npc.parent.faction); } } else { //System.out.println("npcx : i have no faction so ill be be neutral"); } } } } } } } catch (Exception e) { // Concurrent modification occured e.printStackTrace(); } } // VS NPCS for (Entity entity : npc.npc.getBukkitEntity().getWorld().getEntities()) { if (entity instanceof HumanEntity) { HumanEntity e = (HumanEntity) entity; if (e.getHealth() > 0) { double distancex = getDistance(npc.npc.getBukkitEntity().getLocation().getX(), e.getLocation().getX()); double distancey = getDistance(npc.npc.getBukkitEntity().getLocation().getY(), e.getLocation().getY()); double distancez = getDistance(npc.npc.getBukkitEntity().getLocation().getZ(), e.getLocation().getZ()); // HumanEntity in range? if (distancex > -5 && distancey > -5 && distancez > -5 && distancex < 5 && distancey < 5 && distancez < 5) { // monster in range but is it worth chasing? myNPC targetnpc = this.universe.tryFactionVSNPCAttack(npc,(HumanEntity)e); if (targetnpc != null) { // face direction dbg(1,"npcx:think:NPCVSNPC:ATTK"+entity.toString()); // line of site boolean foundresult = false; try { for (Block blockinsight : e.getLineOfSight(null, 5)) { // Entities seem to be Y + 1 Location eloc = e.getLocation(); eloc.setY(eloc.getY()+1); if (blockinsight == eloc.getBlock()) { foundresult = true; npc.npc.aggro = e; npc.npc.follow = e; targetnpc.npc.onDamage(npc); } } if (foundresult == false) { //System.out.println("I can hear one but can't see it"); npc.npc.faceLocation(e.getLocation()); npc.npc.aggro = null; npc.npc.follow = null; } } catch (NullPointerException ex) { // unable to retrieve blocks in area, lets go home // skip } } } } } } // VS MONSTERS if (this.universe.monsters.size() > 0) { try { for (LivingEntity e : this.universe.monsters) { if (e.getHealth() > 0) { double distancex = getDistance(npc.npc.getBukkitEntity().getLocation().getX(), e.getLocation().getX()); double distancey = getDistance(npc.npc.getBukkitEntity().getLocation().getY(), e.getLocation().getY()); double distancez = getDistance(npc.npc.getBukkitEntity().getLocation().getZ(), e.getLocation().getZ()); if (e instanceof Monster) { // mosnter in range? if (distancex > -5 && distancey > -5 && distancez > -5 && distancex < 5 && distancey < 5 && distancez < 5) { // monster in range but is it worth chasing? // face direction // line of site boolean foundresult = false; for (Block blockinsight : e.getLineOfSight(null, 5)) { // Entities seem to be Y + 1 Location eloc = e.getLocation(); eloc.setY(eloc.getY()+1); if (blockinsight == eloc.getBlock()) { foundresult = true; npc.npc.aggro = e; npc.npc.follow = e; } } if (foundresult == false) { //System.out.println("I can hear one but can't see it"); npc.npc.faceLocation(e.getLocation()); npc.npc.aggro = null; npc.npc.follow = null; } } } } } } catch (Exception e) { // Concurrent modification occured e.printStackTrace(); } } } } // // SPAWN FROM ACTIVE SPAWNGROUPS // for (mySpawngroup spawngroup : universe.spawngroups.values()) { // Check if any spawngroups have finished their cooldown period if (spawngroup.activecountdown > 0) { spawngroup.activecountdown--; if (spawngroup.activecountdown == 1) { spawngroup.active = false; } } if (spawngroup.chunkactive) { if (!spawngroup.active) { //System.out.println("npcx : found inactive spawngroup ("+ spawngroup.id +") with :[" + spawngroup.npcs.size() + "]"); int count = 0; Random generator = new Random(); if (spawngroup.npcs != null) { Object[] values = spawngroup.npcs.values().toArray(); if (values.length > 0) { myNPC npc = (myNPC) values[generator.nextInt(values.length)]; try { // is there at least one player in game? if (this.getServer().getOnlinePlayers().length > 0) { if (!spawngroup.active) { npc.spawngroup = spawngroup; //System.out.println("npcx : made spawngroup active"); Double pitch = new Double(spawngroup.pitch); Double yaw = new Double(spawngroup.yaw); BasicHumanNpc hnpc = npc.Spawn(npc.id, npc.name, this.getServer().getWorld(this.universe.defaultworld), spawngroup.x, spawngroup.y, spawngroup.z,yaw , pitch); npc.npc = hnpc; ItemStack iprimary = new ItemStack(npc.weapon); ItemStack ihelmet = new ItemStack(npc.helmet); ItemStack ichest = new ItemStack(npc.chest); ItemStack ilegs = new ItemStack(npc.legs); ItemStack iboots = new ItemStack(npc.boots); npc.npc.getBukkitEntity().getInventory().setItemInHand(iprimary); npc.npc.getBukkitEntity().getInventory().setHelmet(ihelmet); npc.npc.getBukkitEntity().getInventory().setChestplate(ichest); npc.npc.getBukkitEntity().getInventory().setLeggings(ilegs); npc.npc.getBukkitEntity().getInventory().setBoots(iboots); hnpc.parent = npc; this.npclist.put(spawngroup.id + "-" + npc.id, hnpc); this.universe.npcs.put(spawngroup.id+"-"+npc.id,npc); spawngroup.active = true; } } } catch (Exception e) { e.printStackTrace(); } } } } } else { // dont spawn, the chunk isnt up atm if (spawngroup.npcs != null) { for (myNPC npc : spawngroup.npcs.values()) { if (npc.npc != null) { this.onNPCDeath(npc.npc); } } } } } } catch (ConcurrentModificationException e) { // its locked being written to atm, try again on next loop } catch (Exception e) { e.printStackTrace(); } } @Override public void onDisable() { // TODO Auto-generated method stub try { this.universe.commitPlayerFactions(); PluginDescriptionFile pdfFile = this.getDescription(); logger.log(Level.INFO, pdfFile.getName() + " version " + pdfFile.getVersion() + " disabled."); } catch (Exception e) { logger.log(Level.WARNING, "npcx : error: " + e.getMessage() + e.getStackTrace().toString()); e.printStackTrace(); return; } } public String dbGetNPCname(String string) { try { Class.forName ("com.mysql.jdbc.Driver").newInstance (); universe.conn = DriverManager.getConnection (universe.dsn, universe.dbuser, universe.dbpass); Statement s11 = this.universe.conn.createStatement (); s11.executeQuery ("SELECT name FROM npc WHERE id ="+string); ResultSet rs11 = s11.getResultSet (); while (rs11.next ()) { String name = rs11.getString ("name"); return name; } } catch (Exception e) { return "dummy"; } return "dummy"; } public myFaction getFactionByID(int id) { for (myFaction f : this.universe.factions) { if (f.id == id) { return f; } } return null; } public myFaction dbGetNPCfaction(String string) { try { Class.forName ("com.mysql.jdbc.Driver").newInstance (); universe.conn = DriverManager.getConnection (universe.dsn, universe.dbuser, universe.dbpass); PreparedStatement s11 = this.universe.conn.prepareStatement("SELECT faction_id FROM npc WHERE id = ?",Statement.RETURN_GENERATED_KEYS); s11.setInt(1, Integer.parseInt(string)); s11.executeQuery(); ResultSet rs11 = s11.getResultSet (); while (rs11.next ()) { int factionid = rs11.getInt ("faction_id"); for (myFaction f : this.universe.factions) { if (f.id == factionid) { return f; } } } } catch (Exception e) { return null; } return null; } public myLoottable dbGetNPCloottable(String string) { try { Class.forName ("com.mysql.jdbc.Driver").newInstance (); universe.conn = DriverManager.getConnection (universe.dsn, universe.dbuser, universe.dbpass); PreparedStatement s11 = this.universe.conn.prepareStatement("SELECT loottable_id FROM npc WHERE id = ?",Statement.RETURN_GENERATED_KEYS); s11.setInt(1, Integer.parseInt(string)); s11.executeQuery(); ResultSet rs11 = s11.getResultSet (); while (rs11.next ()) { int lootttableid = rs11.getInt ("loottable_id"); for (myLoottable f : this.universe.loottables) { if (f.id == lootttableid) { return f; } } } } catch (Exception e) { return null; } return null; } public void fixDead() { int count = 0; for (myPlayer player : universe.players.values()) { if (player.dead == true) { try { for (World w : getServer().getWorlds()) { for (Player p : w.getPlayers()) { if (player.name == p.getName()) { player.player = p; player.dead = false; count++; } } } } catch (ConcurrentModificationException e) { //we loop soon anyway //System.out.println("npcx : FAILED establishing dead player"); } } } if (count > 0) { //System.out.println("npcx : reestablished " + count + " dead players."); } } public static Server getBukkitServer() { return Server; } public static iConomy getiConomy() { return iConomy; } public static boolean setiConomy(iConomy plugin) { if (iConomy == null) { iConomy = plugin; } else { return false; } return true; } public boolean EventsSetup() { try { System.out.println("npcx : registering monitored events"); this.Server = getServer(); this.PluginListener = new PluginListener(this); getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_ENABLE, PluginListener, Priority.Monitor, this); PluginManager pm = getServer().getPluginManager(); mEntityListener = new npcxEListener(this); mPlayerListener = new npcxPListener(this); mWorldListener = new npcxWListener(this); mBlockListener = new npcxBListener(this); pm.registerEvent(Type.CHUNK_LOAD, mWorldListener, Priority.Normal, this); pm.registerEvent(Type.CHUNK_UNLOAD, mWorldListener, Priority.Normal, this); pm.registerEvent(Type.PLAYER_MOVE, mPlayerListener, Priority.Normal, this); pm.registerEvent(Type.ENTITY_TARGET, mEntityListener, Priority.Normal, this); pm.registerEvent(Type.ENTITY_DAMAGE, mEntityListener, Priority.Normal, this); pm.registerEvent(Type.ENTITY_EXPLODE, mEntityListener, Priority.Normal, this); pm.registerEvent(Type.ENTITY_DEATH, mEntityListener, Priority.Normal, this); pm.registerEvent(Type.CREATURE_SPAWN, mEntityListener, Priority.Normal, this); pm.registerEvent(Type.BLOCK_IGNITE, mBlockListener, Priority.Normal, this); pm.registerEvent(Type.PLAYER_RESPAWN, mPlayerListener, Priority.Normal, this); pm.registerEvent(Type.PLAYER_INTERACT, mPlayerListener, Priority.Normal, this); pm.registerEvent(Type.PLAYER_TELEPORT, mPlayerListener, Priority.Normal, this); pm.registerEvent(Type.PLAYER_JOIN, mPlayerListener, Priority.Normal, this); pm.registerEvent(Type.PLAYER_QUIT, mPlayerListener, Priority.Normal, this); pm.registerEvent(Type.PLAYER_CHAT, mPlayerListener, Priority.Normal, this); return true; } catch (NoSuchFieldError e) { System.out.println("npcx : *****************************************************"); System.out.println("npcx : * FAILED TO LOAD NPCX ! *"); System.out.println("npcx : * This version of NPCX is built for Bukkit RB 602 *"); System.out.println("npcx : * FAILED TO LOAD NPCX ! *"); System.out.println("npcx : *****************************************************"); return false; } } @Override public void onEnable() { // TODO Auto-generated method stub universe = new myUniverse(this); universe.checkSetup(); // Check if world exists and settings are loaded if (!universe.loadSetup()) return; // TODO Auto-generated method stub if (EventsSetup() == false) { return; } universe.checkDbSetup(); universe.checkUpdates(); universe.loadData(); PluginDescriptionFile pdfFile = this.getDescription(); logger.log(Level.INFO, pdfFile.getName() + " version " + pdfFile.getVersion() + " enabled."); think(); longCheck(); } @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { // any player // // CIV COMMAND MENU // if (command.getName().toLowerCase().equals("civ")) { if (!(sender instanceof Player)) { return false; } Player player = (Player) sender; if (args.length < 1) { player.sendMessage("Insufficient arguments /civ buy"); player.sendMessage("Insufficient arguments /civ add playername"); player.sendMessage("Insufficient arguments /civ here"); player.sendMessage("Insufficient arguments /civ gift playername"); player.sendMessage("Insufficient arguments /civ abandon"); return false; } String subCommand = args[0].toLowerCase(); if (subCommand.equals("add")) { int playerx = this.universe.getZoneCoord(player.getLocation().getX()); int playerz = this.universe.getZoneCoord(player.getLocation().getZ()); if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx civ add playername"); return false; } - if (!args[2].equals(player.getName())) + if (!args[1].equals(player.getName())) { for (myZone z : this.universe.zones) { if (z.x == playerx && z.z == playerz) { // are they the owner? if (this.universe.isZoneOwner(z.id, player.getName())) { // are they in alraedy if (this.universe.isZoneMember(z.id, args[1])) { player.sendMessage("Sorry that player is already in this civilisation!"); return false; } else { this.universe.addZoneMember(z.id,player.getName()); player.sendMessage("Player added to civilization!!"); return true; } } } else { // zone not in list } } } else { player.sendMessage("You cannot be a member of a town you own!"); return false; } } if (subCommand.equals("buy")) { int cost = 25000; if (cost <= this.universe.getPlayerBalance(player)) { Chunk c = player.getLocation().getWorld().getChunkAt(player.getLocation()); myZone z = this.universe.getZoneFromChunkAndLoc(this.universe.getZoneCoord(player.getLocation().getX()),this.universe.getZoneCoord(player.getLocation().getZ()), player.getLocation().getWorld()); if (z != null) { if (z.ownername.equals("")) { z.setOwner(player.getName()); z.name = player.getName()+"s land"; player.getServer().broadcastMessage(ChatColor.LIGHT_PURPLE+"* A new civilization has been settled at [" + z.x + ":" + z.z+ "] by "+player.getName()+"!"); player.sendMessage("Thanks! That's " +ChatColor.YELLOW+ cost + ChatColor.WHITE+" total coins!"); this.universe.subtractPlayerBalance(player,cost); player.sendMessage("You just bought region: ["+ChatColor.LIGHT_PURPLE+z.x+","+z.z+""+ChatColor.WHITE+"]!"); this.universe.setPlayerLastChunkX(player,z.x); this.universe.setPlayerLastChunkZ(player,z.z); this.universe.setPlayerLastChunkName(player,z.name); } else { player.sendMessage("Sorry this zone has already been purchased by another Civ"); } } else { player.sendMessage("Failed to buy zone at your location - target zone does not exist"); } } else { player.sendMessage("You don't have enough to buy this plot (25000)!"); } } if (subCommand.equals("abandon")) { myZone z = this.universe.getZoneFromChunkAndLoc(this.universe.getZoneCoord(player.getLocation().getX()),this.universe.getZoneCoord(player.getLocation().getZ()), player.getLocation().getWorld()); if (z != null) { if (z.ownername.equals(player.getName())) { z.setOwner(""); z.name = "Abandoned land"; for (myZoneMember zm : this.universe.zonemembers.values()) { if (zm.zoneid == z.id) { // member of town zm = null; } } player.getServer().broadcastMessage(ChatColor.LIGHT_PURPLE+"* "+ player.getName()+" has lost one of his civilizations!"); player.sendMessage("Thanks! Here's " +ChatColor.YELLOW+ 5000 + ChatColor.WHITE+" coin from the sale of our land!"); this.universe.addPlayerBalance(player,5000); player.sendMessage("You just released region: ["+ChatColor.LIGHT_PURPLE+z.x+","+z.z+""+ChatColor.WHITE+"]!"); this.universe.setPlayerLastChunkX(player,z.x); this.universe.setPlayerLastChunkZ(player,z.z); this.universe.setPlayerLastChunkName(player,"Abandoned land"); } else { player.sendMessage("Sorry this zone is not yours to abandon"); } } else { player.sendMessage("Failed to abandon zone at your location - target zone does not exist"); } } if (subCommand.equals("here")) { int playerx = this.universe.getZoneCoord(player.getLocation().getX()); int playerz = this.universe.getZoneCoord(player.getLocation().getZ()); for (myZone z : this.universe.zones) { if (z.x == playerx && z.z == playerz) { player.sendMessage("["+ChatColor.LIGHT_PURPLE+""+z.x+","+z.z+""+ChatColor.WHITE+"] "+ChatColor.YELLOW+""+z.name); } else { // zone not in list } } } } // ops only try { // // NPCX COMMAND MENU // if (!command.getName().toLowerCase().equals("npcx")) { return false; } if (!(sender instanceof Player)) { return false; } if (sender.isOp() == false) { return false; } Player player = (Player) sender; if (args.length < 1) { player.sendMessage("Insufficient arguments /npcx spawngroup"); player.sendMessage("Insufficient arguments /npcx faction"); player.sendMessage("Insufficient arguments /npcx loottable"); player.sendMessage("Insufficient arguments /npcx npc"); player.sendMessage("Insufficient arguments /npcx pathgroup"); player.sendMessage("Insufficient arguments /npcx merchant"); player.sendMessage("Insufficient arguments /npcx civ"); return false; } String subCommand = args[0].toLowerCase(); //debug: logger.log(Level.WARNING, "npcx : " + command.getName().toLowerCase() + "(" + subCommand + ")"); Location l = player.getLocation(); if (subCommand.equals("debug")) { } if (subCommand.equals("spawngroup")) { // Overview: // A spawngroup is like a container. It contains many npcs and any one of them could spawn randomly. // If you placed just one npc in the group only one npc would spawn. This allows you to create 'rare' npcs // Spawngroups need to be assigned to a location with 'spawngroup place' Once assigned that group // will spawn in that location and remain stationary // If a path is assigned to the spawn group, the npc will follow the path continuously after spawning // at the location of 'spawngroup place' // todo: functionality // creates a new spawngroup with name // adds an npc to a spawngroup with a chance // makes the spawngroup spawn at your location // assigns a path to the spawngroup if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx spawngroup create spawngroupname"); player.sendMessage("Insufficient arguments /npcx spawngroup add spawngroupid npcid"); player.sendMessage("Insufficient arguments /npcx spawngroup pathgroup spawngroupid pathgroupid"); player.sendMessage("Insufficient arguments /npcx spawngroup list [name]"); player.sendMessage("Insufficient arguments /npcx spawngroup updatepos spawngroupid"); player.sendMessage("Insufficient arguments /npcx spawngroup delete spawngroupid"); player.sendMessage("Insufficient arguments /npcx version"); return false; } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx spawngroup create spawngroupname"); } else { player.sendMessage("Created spawngroup: " + args[2]); double x = player.getLocation().getX(); double y = player.getLocation().getY(); double z = player.getLocation().getZ(); double pitch = player.getLocation().getPitch(); double yaw = player.getLocation().getYaw(); PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO spawngroup (name,x,y,z,pitch,yaw) VALUES (?,?,?,?,?,?);",Statement.RETURN_GENERATED_KEYS); stmt.setString(1,args[2]); stmt.setString(2, Double.toString(x)); stmt.setString(3, Double.toString(y)); stmt.setString(4, Double.toString(z)); stmt.setString(5, Double.toString(pitch)); stmt.setString(6, Double.toString(yaw)); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } stmt.close(); player.sendMessage("Spawngroup ["+ key + "] now active at your position"); mySpawngroup sg = new mySpawngroup(this); sg.id = key; sg.name = args[2]; sg.x = x; sg.y = y; sg.z = z; sg.pitch = pitch; sg.yaw = yaw; sg.world = player.getWorld(); this.universe.spawngroups.put(Integer.toString(key),sg); System.out.println("npcx : + cached new spawngroup("+ args[2] + ")"); } } if (args[1].equals("delete")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx spawngroup delete spawngroupid"); } else { int count = 0; for (mySpawngroup spawngroup : this.universe.spawngroups.values()) { if (spawngroup.id == Integer.parseInt(args[2])) { spawngroup.DBDelete(); count++; } } player.sendMessage("Deleted cached "+count+" spawngroups."); } } if (args[1].equals("pathgroup")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx spawngroup pathgroup spawngroupid pathgroupid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE spawngroup SET pathgroupid = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(mySpawngroup sg : universe.spawngroups.values()) { if (sg.id == Integer.parseInt(args[2])) { if (Integer.parseInt(args[3]) != 0) { sg.pathgroup = getPathgroupByID(Integer.parseInt(args[3])); for (myNPC n : universe.npcs.values()) { if (n.spawngroup == sg) { n.pathgroup = sg.pathgroup; } } player.sendMessage("npcx : Updated spawngroups cached pathgroup ("+args[3]+"): "+sg.pathgroup.name); } else { sg.pathgroup = null; sg.pathgroup = getPathgroupByID(Integer.parseInt(args[3])); for (myNPC n : universe.npcs.values()) { if (n.spawngroup == sg) { n.pathgroup = null; } } player.sendMessage("npcx : Updated spawngroups cached pathgroup (0)"); } } } player.sendMessage("Updated pathgroup ID:" + args[3] + " on spawngroup ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("add")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx spawngroup add spawngroup npcid"); } else { player.sendMessage("Added to spawngroup " + args[2] + "<"+ args[3]+ "."); // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO spawngroup_entries (spawngroupid,npcid) VALUES (?,?);",Statement.RETURN_GENERATED_KEYS); s2.setString(1,args[2]); s2.setString(2,args[3]); s2.executeUpdate(); player.sendMessage("NPC ["+ args[3] + "] added to group ["+ args[2] + "]"); // add to cached spawngroup for (mySpawngroup sg : universe.spawngroups.values()) { if (sg.id == Integer.parseInt(args[2])) { PreparedStatement stmtNPC = this.universe.conn.prepareStatement("SELECT * FROM npc WHERE id = ?;"); stmtNPC.setString(1,args[3]); stmtNPC.executeQuery(); ResultSet rsNPC = stmtNPC.getResultSet (); int count = 0; while (rsNPC.next ()) { Location loc = new Location(getServer().getWorld(this.universe.defaultworld),0,0,0,0,0); myNPC npc = new myNPC(this,universe.fetchTriggerWords(Integer.parseInt(args[3])), loc, "dummy"); npc.name = rsNPC.getString ("name"); npc.category = rsNPC.getString ("category"); npc.faction = dbGetNPCfaction(args[3]); npc.loottable = dbGetNPCloottable(args[3]); npc.helmet = rsNPC.getInt ("helmet"); npc.pathgroup = sg.pathgroup; npc.chest = rsNPC.getInt ("chest"); npc.legs = rsNPC.getInt ("legs"); npc.boots = rsNPC.getInt ("boots"); npc.weapon = rsNPC.getInt ("weapon"); npc.spawngroup = sg; npc.id = args[3]; sg.npcs.put(sg.id+"-"+npc.id, npc); universe.npcs.put(sg.id+"-"+npc.id, npc); ++count; } rsNPC.close(); stmtNPC.close(); dbg(1,"npcx : + cached new spawngroup entry("+ args[3] + ")"); } } mySpawngroup sg = new mySpawngroup(this); // close db s2.close(); } } if (args[1].equals("updatepos")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx spawngroup updatepos spawngroupid"); } else { Location loc = player.getLocation(); PreparedStatement s2 = this.universe.conn.prepareStatement("UPDATE spawngroup SET x=?,y=?,z=?,yaw=?,pitch=? WHERE id = ?;"); s2.setString(1,Double.toString(loc.getX())); s2.setString(2,Double.toString(loc.getY())); s2.setString(3,Double.toString(loc.getZ())); s2.setString(4,Double.toString(loc.getYaw())); s2.setString(5,Double.toString(loc.getPitch())); s2.setString(6,args[2]); s2.executeUpdate(); player.sendMessage("Updated Spawngroup " + args[2] + " to your position"); // Update cached spawngroups for (mySpawngroup sg : this.universe.spawngroups.values()) { if (sg.id == Integer.parseInt(args[2])) { // update the spawngroup sg.x = loc.getX(); sg.y = loc.getY(); sg.z = loc.getZ(); sg.yaw = loc.getYaw(); sg.pitch = loc.getPitch(); dbg(1,"npcx : + cached updated spawngroup ("+ args[2] + ")"); // Found the spawngroup, lets make sure the NPCs have their spawn values set right for (myNPC np : sg.npcs.values()) { if (np.npc != null) { np.npc.spawnx = sg.x; np.npc.spawny = sg.y; np.npc.spawnz = sg.z; np.npc.spawnyaw = sg.yaw; np.npc.spawnpitch = sg.pitch; Location locnpc = new Location(getServer().getWorld(this.universe.defaultworld),loc.getX(),loc.getY(),loc.getZ(),loc.getYaw(),loc.getPitch()); np.npc.forceMove(locnpc); } } } } // close statement s2.close(); } } if (args[1].equals("list")) { player.sendMessage("Spawngroups:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM spawngroup ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM spawngroup WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } } // // START CIV // if (subCommand.equals("civ")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx civ givemoney playername amount"); player.sendMessage("Insufficient arguments /npcx civ money playername"); player.sendMessage("Insufficient arguments /npcx civ unclaim"); return false; } if (args[1].matches("money")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx civ money playername"); return false; } else { for (myPlayer p : this.universe.players.values()) { if (p.player.getName().matches(args[2])) { player.sendMessage("Balance: " + p.getNPCXBalance()); } } } } if (args[1].matches("givemoney")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx civ givemoney playername amount"); return false; } else { for (myPlayer p : this.universe.players.values()) { if (p.player.getName().matches(args[2])) { p.setNPCXBalance(p.getNPCXBalance() + (Integer.parseInt(args[3]))); player.sendMessage("Added to balance " + args[2] + "<"+ args[3]); } } } } if (args[1].matches("unclaim")) { myZone z = this.universe.getZoneFromChunkAndLoc(this.universe.getZoneCoord(player.getLocation().getX()),this.universe.getZoneCoord(player.getLocation().getZ()), player.getLocation().getWorld()); if (z != null) { z.setOwner(""); z.name = "Refurbished land"; player.sendMessage("You just released region: ["+ChatColor.LIGHT_PURPLE+z.x+","+z.z+""+ChatColor.WHITE+"]!"); this.universe.setPlayerLastChunkX(player,z.x); this.universe.setPlayerLastChunkZ(player,z.z); this.universe.setPlayerLastChunkName(player,"Refurbished land"); } else { player.sendMessage("Failed to buy zone at your location - target zone does not exist"); } } } // // START LOOTTABLE // if (subCommand.equals("loottable")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx loottable create loottablename"); player.sendMessage("Insufficient arguments /npcx loottable list"); player.sendMessage("Insufficient arguments /npcx loottable add loottableid itemid amount"); return false; } if (args[1].equals("add")) { if (args.length < 5) { player.sendMessage("Insufficient arguments /npcx loottable add loottableid itemid amount"); return false; } else { player.sendMessage("Added to loottable " + args[2] + "<"+ args[3]+ "x"+args[4]+"."); // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO loottable_entries (loottable_id,item_id,amount) VALUES (?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setString(1,args[2]); s2.setString(2,args[3]); s2.setString(3,args[4]); s2.executeUpdate(); player.sendMessage("NPC ["+ args[3] + "x"+args[4]+"] added to group ["+ args[2] + "]"); // add to cached loottable for (myLoottable lt : this.universe.loottables) { if (lt.id == Integer.parseInt(args[2])) { myLoottable_entry entry = new myLoottable_entry(); entry.id = Integer.parseInt(args[2]); entry.itemid = Integer.parseInt(args[3]); entry.amount = Integer.parseInt(args[4]); dbg(1,"npcx : + cached new loottable entry("+ args[3] + ")"); lt.loottable_entries.add(entry); } } mySpawngroup sg = new mySpawngroup(this); // close statement s2.close(); } } if (args[1].equals("create")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx loottable create loottablename"); return false; } else { try { PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO loottables (name) VALUES (?);",Statement.RETURN_GENERATED_KEYS); stmt.setString(1,args[2]); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } stmt.close(); player.sendMessage("Loottable ["+ key + "] now active"); myLoottable fa = new myLoottable(key,args[2]); fa.id = key; fa.name = args[2]; this.universe.loottables.add(fa); dbg(1,"npcx : + cached new loottable ("+ args[2] + ")"); } catch (IndexOutOfBoundsException e) { player.sendMessage("Insufficient arguments"); } } } if (args[1].equals("list")) { player.sendMessage("Loottables:"); Statement s = this.universe.conn.createStatement (); s.executeQuery ("SELECT id, name FROM loottables"); ResultSet rs = s.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); player.sendMessage( "id = " + idVal + ", name = " + nameVal); Statement sFindEntries = this.universe.conn.createStatement(); sFindEntries.executeQuery("SELECT * FROM loottable_entries WHERE loottable_id = " + idVal); ResultSet rsEntries = sFindEntries.getResultSet (); int countentries = 0; while (rsEntries.next ()) { int id = rsEntries.getInt("id"); int itemid = rsEntries.getInt("item_id"); int loottableid = rsEntries.getInt("loottable_id"); int amount = rsEntries.getInt("amount"); player.sendMessage( " + id = " + id + ", loottableid = " + loottableid + ", itemid = " + itemid + ", amount = " + amount); countentries++; } player.sendMessage (countentries + " entries in this set"); ++count; } rs.close (); s.close (); player.sendMessage (count + " loottables were retrieved"); } } // END LOOTTABLE // // START FACTION // if (subCommand.equals("faction")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx faction create baseamount factionname"); player.sendMessage("Insufficient arguments /npcx faction list"); player.sendMessage("Insufficient arguments /npcx faction npc npcid factionid amount"); return false; } if (args[1].equals("npc")) { if (args.length < 5) { player.sendMessage("Insufficient arguments /npcx faction npc add npcid factionid amount"); } else { // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO npc_faction (npc_id,faction_id,amount) VALUES (?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setInt(1,Integer.parseInt(args[2])); s2.setInt(2,Integer.parseInt(args[3])); s2.setInt(3,Integer.parseInt(args[4])); s2.executeUpdate(); ResultSet keyset = s2.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } s2.close(); myNpc_faction nf = new myNpc_faction(key, Integer.parseInt(args[2]), Integer.parseInt(args[3]), Integer.parseInt(args[4])); player.sendMessage("Added to npc faction ["+key+"] "+args[2]+"<" + args[3] + "="+ args[4]+ "."); this.universe.npcfactions.put(Integer.toString(nf.id), nf); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx faction create baseamount factionname"); } else { try { PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO faction_list (name,base) VALUES (?,?);",Statement.RETURN_GENERATED_KEYS); stmt.setString(1,args[3]); stmt.setInt(2,Integer.parseInt(args[2])); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } stmt.close(); player.sendMessage("Faction ["+ key + "] now active"); myFaction fa = new myFaction(); fa.id = key; fa.name = args[3]; fa.base = Integer.parseInt(args[2]); this.universe.factions.add(fa); dbg(1,"npcx : + cached new faction("+ args[3] + ")"); } catch (IndexOutOfBoundsException e) { player.sendMessage("Insufficient arguments"); } } } if (args[1].equals("list")) { player.sendMessage("Factions:"); Statement s = this.universe.conn.createStatement (); s.executeQuery ("SELECT id, name, base FROM faction_list"); ResultSet rs = s.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String baseVal = rs.getString ("base"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", base = " + baseVal); ++count; } rs.close (); s.close (); player.sendMessage (count + " rows were retrieved"); } } // END FACTION if (subCommand.equals("pathgroup")) { if (args.length < 2) { // todo: need to implement npc types here ie: 0 = default 1 = banker 2 = merchant // todo: need to implement '/npcx npc edit' here player.sendMessage("Insufficient arguments /npcx pathgroup create name"); // todo needs to force the player to provide a search term to not spam them with lots of results in the event of a huge npc list player.sendMessage("Insufficient arguments /npcx pathgroup list"); player.sendMessage("Insufficient arguments /npcx pathgroup add pathgroupid order"); player.sendMessage("Insufficient arguments /npcx pathgroup inspect pathgroupid"); return false; } if (args[1].equals("inspect")) { player.sendMessage("Pathgroup Entries:"); if (args.length >= 3) { PreparedStatement pginspect = this.universe.conn.prepareStatement("SELECT id,s,x,y,z,pathgroup,name FROM pathgroup_entries WHERE pathgroup = ? ORDER BY s ASC"); pginspect.setInt(1, Integer.parseInt(args[2])); pginspect.executeQuery (); ResultSet rspginspect = pginspect.getResultSet (); int count = 0; while (rspginspect.next ()) { int idVal = rspginspect.getInt ("id"); String nameVal = rspginspect.getString ("name"); int s = rspginspect.getInt ("s"); int pgid = rspginspect.getInt ("pathgroup"); String x = rspginspect.getString ("x"); String y = rspginspect.getString ("y"); String z = rspginspect.getString ("z"); player.sendMessage("s: "+s+" pgid: "+pgid+" XYZ: "+x+","+y+","+z); ++count; } rspginspect.close (); pginspect.close (); player.sendMessage (count + " rows were retrieved"); } else { player.sendMessage("Insufficient arguments /npcx pathgroup inspect pathgroupid"); } } if (args[1].equals("add")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx pathgroup add pathgroupid order"); } else { player.sendMessage("Added to pathgroup " + args[2] + "<"+ args[3]+ "."); // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO pathgroup_entries (pathgroup,s,x,y,z,pitch,yaw) VALUES (?,?,?,?,?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setString(1,args[2]); s2.setString(2,args[3]); s2.setDouble(3,player.getLocation().getX()); s2.setDouble(4,player.getLocation().getY()); s2.setDouble(5,player.getLocation().getZ()); s2.setFloat(6,player.getLocation().getPitch()); s2.setFloat(7,player.getLocation().getYaw()); s2.executeUpdate(); player.sendMessage("Pathing Position ["+ args[3] + "] added to pathggroup ["+ args[2] + "]"); // add to cached spawngroup for (myPathgroup pg : this.universe.pathgroups) { if (pg.id == Integer.parseInt(args[2])) { int dpathgroupid = Integer.parseInt(args[2]); int dspot = Integer.parseInt(args[3]); myPathgroup_entry pge = new myPathgroup_entry(player.getLocation(),dpathgroupid,pg,dspot); dbg(1,"npcx : + cached new pathgroup entry("+ args[3] + ")"); // add new pathgroup entry object to the pathgroups entry list pg.pathgroupentries.add(pge); } } // close db s2.close(); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx pathgroup create name"); } else { PreparedStatement statementPCreate = this.universe.conn.prepareStatement("INSERT INTO pathgroup (name) VALUES (?)",Statement.RETURN_GENERATED_KEYS); statementPCreate.setString(1, args[2]); statementPCreate.executeUpdate(); ResultSet keyset = statementPCreate.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } myPathgroup pathgroup = new myPathgroup(); pathgroup.id = key; pathgroup.name = args[2]; this.universe.pathgroups.add(pathgroup); statementPCreate.close(); player.sendMessage("Created pathgroup ["+key+"]: " + args[2]); } } if (args[1].equals("list")) { player.sendMessage("Pathgroups:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM pathgroup ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM pathgroup WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } } if (subCommand.equals("merchant")) { if (args.length < 2) { // todo: need to implement npc types here ie: 0 = default 1 = banker 2 = merchant // todo: need to implement '/npcx npc edit' here player.sendMessage("Insufficient arguments /npcx merchant create name"); // todo needs to force the player to provide a search term to not spam them with lots of results in the event of a huge npc list player.sendMessage("Insufficient arguments /npcx merchant list"); player.sendMessage("Insufficient arguments /npcx merchant add merchantid item amount pricebuyat pricesellat"); player.sendMessage("Insufficient arguments /npcx merchant inspect merchantid"); player.sendMessage("Insufficient arguments /npcx merchant category merchantid category"); return false; } if (args[1].equals("category")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx merchant category merchantid category"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE merchant SET category = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myMerchant n : universe.merchants) { if (n.id == Integer.parseInt(args[2])) { n.category = args[3]; player.sendMessage("npcx : Updated merchant to cached category ("+args[3]+"): "+n.category); // when faction changes reset aggro and follow status } } player.sendMessage("Updated merchant category :" + args[3] + " on Merchant ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("inspect")) { player.sendMessage("Merchant Entries:"); if (args.length >= 3) { PreparedStatement pginspect = this.universe.conn.prepareStatement("SELECT id,merchantid,itemid,amount,pricebuy,pricesell FROM merchant_entries WHERE merchantid = ? ORDER BY id ASC"); pginspect.setInt(1, Integer.parseInt(args[2])); pginspect.executeQuery (); ResultSet rspginspect = pginspect.getResultSet (); int count = 0; while (rspginspect.next ()) { int idVal = rspginspect.getInt ("id"); int merchantid = rspginspect.getInt ("merchantid"); int itemid = rspginspect.getInt ("itemid"); int amount = rspginspect.getInt ("amount"); int pricebuy = rspginspect.getInt ("pricebuy"); int pricesell = rspginspect.getInt ("pricesell"); player.sendMessage("EID:"+idVal+":MID:"+merchantid+" Item:"+itemid +" - Amount: "+amount+" Buying: "+pricebuy+"Selling: "+pricesell); ++count; } rspginspect.close (); pginspect.close (); player.sendMessage (count + " rows were retrieved"); } else { player.sendMessage("Insufficient arguments /npcx merchant inspect merchantid"); } } if (args[1].equals("add")) { if (args.length < 6) { player.sendMessage("Insufficient arguments /npcx merchant add merchantid itemid amount pricebuyat pricesellat"); } else { // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO merchant_entries (merchantid,itemid,amount,pricebuy,pricesell) VALUES (?,?,?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setInt (1,Integer.parseInt(args[2])); s2.setInt (2,Integer.parseInt(args[3])); s2.setInt (3,Integer.parseInt(args[4])); s2.setInt (4,Integer.parseInt(args[5])); s2.setInt (5,Integer.parseInt(args[6])); s2.executeUpdate(); player.sendMessage("Merchant Item ["+ args[3] + "x" + args[4] + "@"+args[5]+"/"+args[6]+"] added to Merchant: ["+ args[2] + "]"); // add to cached spawngroup for (myMerchant pg : this.universe.merchants) { if (pg.id == Integer.parseInt(args[2])) { int dmerchantid = Integer.parseInt(args[2]); int itemid = Integer.parseInt(args[3]); int amount = Integer.parseInt(args[4]); int pricebuy = Integer.parseInt(args[5]); int pricesell = Integer.parseInt(args[6]); myMerchant_entry pge = new myMerchant_entry(pg, dmerchantid,itemid,amount,pricebuy,pricesell); dbg("npcx : + cached new merchant entry("+ args[3] + ")"); // add new merchant entry object to the merchants entry list pg.merchantentries.add(pge); player.sendMessage("Added to merchant " + args[2] + "<"+ args[3]+ "x"+args[4]+"@"+args[5]+"."); } } // close db s2.close(); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx merchant create name"); } else { PreparedStatement statementPCreate = this.universe.conn.prepareStatement("INSERT INTO merchant (name) VALUES (?)",Statement.RETURN_GENERATED_KEYS); statementPCreate.setString(1, args[2]); statementPCreate.executeUpdate(); ResultSet keyset = statementPCreate.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } myMerchant merchant = new myMerchant(this,key,args[2]); merchant.id = key; merchant.name = args[2]; this.universe.merchants.add(merchant); statementPCreate.close(); player.sendMessage("Created merchant ["+key+"]: " + args[2]); } } if (args[1].equals("list")) { player.sendMessage("merchants:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM merchant ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM merchant WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + rs.getString ("category")); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } } if (subCommand.equals("version")) { PluginDescriptionFile pdfFile = this.getDescription(); player.sendMessage("npcx version "+ pdfFile.getVersion() + " db version: " + this.universe.dbversion); } if (subCommand.equals("npc")) { // Overview: // NPCs are just that, definitions of the mob you want to appear in game. There can be multiple of the same // npc in many spawngroups, for example if you wanted a custom npc called 'Thief' to spawn in several locations // you would put the npc into many spawn groups // In the future these npcs will support npctypes which determines how the npc will respond to right click, attack, etc events // ie for: bankers, normal npcs, merchants etc // Also loottables will be assignable // todo: functionality // creates a new npc with name if (args.length < 2) { // todo: need to implement npc types here ie: 0 = default 1 = banker 2 = merchant // todo: need to implement '/npcx npc edit' here player.sendMessage("Insufficient arguments /npcx npc create name"); // todo needs to force the player to provide a search term to not spam them with lots of results in the event of a huge npc list player.sendMessage("Insufficient arguments /npcx npc list [name]"); // spawns the npc temporarily at your current spot for testing //player.sendMessage("Insufficient arguments /npcx npc spawn name"); player.sendMessage("Insufficient arguments /npcx npc triggerword add npcid triggerword response"); player.sendMessage("Insufficient arguments /npcx npc faction npcid factionid"); player.sendMessage("Insufficient arguments /npcx npc loottable npcid loottableid"); player.sendMessage("Insufficient arguments /npcx npc category npcid category"); player.sendMessage("Insufficient arguments /npcx npc merchant npcid merchantid"); player.sendMessage("Insufficient arguments /npcx npc weapon npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc helmet npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc chest npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc legs npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc boots npcid itemid"); return false; } if (args[1].equals("merchant")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc merchant npcid merchantid"); return false; } else { if (Integer.parseInt(args[3]) == 0) { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET merchantid = null WHERE id = ?;"); stmt.setString(1, args[2]); stmt.executeUpdate(); stmt.close(); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET merchantid = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); stmt.close(); } int count = 0; for(myNPC sg : universe.npcs.values()) { //player.sendMessage("npcx : Checking: "+sg.name); if (sg.id.matches(args[2])) { if (Integer.parseInt(args[3]) != 0) { sg.merchant = getMerchantByID(Integer.parseInt(args[3])); player.sendMessage("npcx : Updated NPCs cached merchant ("+args[3]+"): "+sg.merchant.name); count++; } else { sg.merchant = null; player.sendMessage("npcx : Updated NPCs cached merchant (0)"); count++; } } } player.sendMessage("Updated "+count+" entries."); } } if (args[1].equals("triggerword")) { if (args.length < 6) { player.sendMessage("Insufficient arguments /npcx npc triggerword add npcid triggerword response"); } else { String reply = ""; int current = 6; while (current <= args.length) { reply = reply + args[current-1]+" "; current++; } reply = reply.substring(0,reply.length()-1); PreparedStatement statementTword = this.universe.conn.prepareStatement("INSERT INTO npc_triggerwords (npcid,triggerword,reply) VALUES (?,?,?)",Statement.RETURN_GENERATED_KEYS); statementTword.setString(1,args[3]); statementTword.setString(2,args[4]); statementTword.setString(3,reply); statementTword.executeUpdate(); ResultSet keyset = statementTword.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } player.sendMessage("Added ("+universe.npcs.values().size()+") triggerword ["+key+"] to npc "+args[3]); // add it to any spawned npcs for (myNPC npc : universe.npcs.values()) { dbg(1,"my id="+npc.id.toString()); if (npc.id.equals(args[3])) { dbg(1,"npcx : adding reply because ("+ npc.id +") is ("+args[3]+") ("+ reply + ") and trigger ("+ reply +") for [" + args[3] + "] npc to npc: " + npc.id); myTriggerword tw = new myTriggerword(); tw.word = args[4]; tw.id = key; tw.response = reply; player.sendMessage("Added triggerword to Active npc "+args[3]); npc.triggerwords.put(Integer.toString(tw.id), tw); } } } } if (args[1].equals("chest")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc chest npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET chest = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.chest = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.chest); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setChestplate(i); player.sendMessage("npcx : Updated living npc to cached chest ("+args[3]+"): "+n.chest); stmt.executeUpdate(); } } player.sendMessage("Updated npc chest: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("helmet")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc helmet npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET helmet = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.helmet = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.helmet); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setHelmet(i); player.sendMessage("npcx : Updated living npc to cached helmet ("+args[3]+"): "+n.helmet); stmt.executeUpdate(); } } player.sendMessage("Updated npc helmet: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("weapon")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc weapon npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET weapon = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.weapon = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.weapon); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setItemInHand(i); player.sendMessage("npcx : Updated living npc to cached weapon ("+args[3]+"): "+n.weapon); stmt.executeUpdate(); } } player.sendMessage("Updated npc weapon: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("boots")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc boots npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET boots = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.boots = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.boots); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setBoots(i); player.sendMessage("npcx : Updated living npc to cached boots ("+args[3]+"): "+n.boots); stmt.executeUpdate(); } } player.sendMessage("Updated npc boots: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("legs")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc legs npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET legs = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.legs = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.legs); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setLeggings(i); player.sendMessage("npcx : Updated living npc to cached legs ("+args[3]+"): "+n.legs); stmt.executeUpdate(); } } player.sendMessage("Updated npc legs: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("faction")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc faction npcid factionid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET faction_id = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.faction = getFactionByID(Integer.parseInt(args[3])); player.sendMessage("npcx : Updated living npc to cached faction ("+args[3]+"): "+n.faction.name); // when faction changes reset aggro and follow status n.npc.aggro = null; n.npc.follow = null; } } player.sendMessage("Updated npc faction ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("category")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc category npcid category"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET category = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.category = args[3]; player.sendMessage("npcx : Updated living npc to cached category ("+args[3]+"): "+n.category); // when faction changes reset aggro and follow status } } player.sendMessage("Updated npc category :" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("list")) { player.sendMessage("Npcs:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM npc ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM npc WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } if (args[1].equals("loottable")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc loottable npcid loottableid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET loottable_id = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.loottable = getLoottableByID(Integer.parseInt(args[3])); player.sendMessage("npcx : Updated living npc to cached loottable ("+args[3]+"): "+n.loottable.name); } } player.sendMessage("Updated npc loottable ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx npc create npcname"); } else { Statement s2 = this.universe.conn.createStatement (); PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO npc (name,weapon,helmet,chest,legs,boots) VALUES (?,'267','0','307','308','309');",Statement.RETURN_GENERATED_KEYS); stmt.setString(1, args[2]); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } player.sendMessage("Created npc: " + args[2] + " ID:[" + key + "]"); s2.close(); } } /* * Disabled temporarily * if (args[1].equals("spawn")) { player.sendMessage("Spawning new (temporary) NPC: " + args[2]); // temporary Location loc = new Location(player.getWorld(),player.getLocation().getX(),player.getLocation().getY(),player.getLocation().getZ(),player.getLocation().getYaw(),player.getLocation().getPitch()); myNPC npc = new myNPC(this, null, loc, args[2]); npc.Spawn(args[2],loc); this.universe.npcs.put("ZZSpawns"+"-"+npc.id,npc); this.npclist.put(args[2], npc.npc); return true; } */ } } catch (Exception e) { sender.sendMessage("An error occured."); logger.log(Level.WARNING, "npcx: error: " + e.getMessage() + e.getStackTrace().toString()); e.printStackTrace(); return true; } return true; } private myMerchant getMerchantByID(int parseInt) { // TODO Auto-generated method stub for (myMerchant g : this.universe.merchants) { if (g.id == parseInt) { System.out.println("Found a merchant"); return g; } } return null; } private myPathgroup getPathgroupByID(int parseInt) { // TODO Auto-generated method stub dbg(1,"getPathgroupByID:called ("+parseInt+")!"); for (myPathgroup g : this.universe.pathgroups) { dbg(1,"getPathgroupByID:iterating!"); if (g.id == parseInt) { dbg(1,"getPathgroupByID:found!"); return g; } } return null; } private myLoottable getLoottableByID(int parseInt) { for (myLoottable f : this.universe.loottables) { if (f.id == parseInt) { return f; } } return null; } public void dbg(int debug, String string) { // TODO Auto-generated method stub if (debug >= 1) { // do stuff with info/warn } else { dbg(string); } } public void dbg(String string) { System.out.println("npcx: "+string); } public void informNpcDeadPlayer(Player player) { // TODO Auto-generated method stub for (myNPC npc : this.universe.npcs.values()) { if (npc.npc != null && npc.npc.aggro != null) { if (npc.npc.aggro == player) { dbg(1,"informNpcDeadPlayer:aggro:"+player.getName()); npc.npc.follow = null; } } } } public void sendPlayerItemList(Player player) { // TODO Auto-generated method stub String list = "Examples are: STONE GRASS DIRT IRON_SPADE LOG LEAVES GLASS LAPIS_ORE LAPIS_BLOCK IRON_INGOT"; player.sendMessage(list); } public void registerChunk(Chunk chunk) { // TODO Auto-generated method stub /* // get a location in the chunk Location loc = chunk.getBlock(0, 0, 0).getLocation(); myZone m = this.universe.getZoneFromChunk(chunk,loc); if (m != null) { myZone mc = new myZone(this.universe, m.id, chunk, m.x, m.z); this.universe.zones.add(mc); } */ } public void deregisterChunk(Chunk chunk) { // TODO Auto-generated method stub /* Location loc = chunk.getBlock(0, 0, 0).getLocation(); myZone m = this.universe.getZoneFromChunk(chunk,loc); if (m != null) { myZone mc = new myZone(this.universe, m.id, chunk, m.x, m.z); this.universe.zones.remove(mc); } else { // doesn't exist anyway } */ } }
true
true
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { // any player // // CIV COMMAND MENU // if (command.getName().toLowerCase().equals("civ")) { if (!(sender instanceof Player)) { return false; } Player player = (Player) sender; if (args.length < 1) { player.sendMessage("Insufficient arguments /civ buy"); player.sendMessage("Insufficient arguments /civ add playername"); player.sendMessage("Insufficient arguments /civ here"); player.sendMessage("Insufficient arguments /civ gift playername"); player.sendMessage("Insufficient arguments /civ abandon"); return false; } String subCommand = args[0].toLowerCase(); if (subCommand.equals("add")) { int playerx = this.universe.getZoneCoord(player.getLocation().getX()); int playerz = this.universe.getZoneCoord(player.getLocation().getZ()); if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx civ add playername"); return false; } if (!args[2].equals(player.getName())) { for (myZone z : this.universe.zones) { if (z.x == playerx && z.z == playerz) { // are they the owner? if (this.universe.isZoneOwner(z.id, player.getName())) { // are they in alraedy if (this.universe.isZoneMember(z.id, args[1])) { player.sendMessage("Sorry that player is already in this civilisation!"); return false; } else { this.universe.addZoneMember(z.id,player.getName()); player.sendMessage("Player added to civilization!!"); return true; } } } else { // zone not in list } } } else { player.sendMessage("You cannot be a member of a town you own!"); return false; } } if (subCommand.equals("buy")) { int cost = 25000; if (cost <= this.universe.getPlayerBalance(player)) { Chunk c = player.getLocation().getWorld().getChunkAt(player.getLocation()); myZone z = this.universe.getZoneFromChunkAndLoc(this.universe.getZoneCoord(player.getLocation().getX()),this.universe.getZoneCoord(player.getLocation().getZ()), player.getLocation().getWorld()); if (z != null) { if (z.ownername.equals("")) { z.setOwner(player.getName()); z.name = player.getName()+"s land"; player.getServer().broadcastMessage(ChatColor.LIGHT_PURPLE+"* A new civilization has been settled at [" + z.x + ":" + z.z+ "] by "+player.getName()+"!"); player.sendMessage("Thanks! That's " +ChatColor.YELLOW+ cost + ChatColor.WHITE+" total coins!"); this.universe.subtractPlayerBalance(player,cost); player.sendMessage("You just bought region: ["+ChatColor.LIGHT_PURPLE+z.x+","+z.z+""+ChatColor.WHITE+"]!"); this.universe.setPlayerLastChunkX(player,z.x); this.universe.setPlayerLastChunkZ(player,z.z); this.universe.setPlayerLastChunkName(player,z.name); } else { player.sendMessage("Sorry this zone has already been purchased by another Civ"); } } else { player.sendMessage("Failed to buy zone at your location - target zone does not exist"); } } else { player.sendMessage("You don't have enough to buy this plot (25000)!"); } } if (subCommand.equals("abandon")) { myZone z = this.universe.getZoneFromChunkAndLoc(this.universe.getZoneCoord(player.getLocation().getX()),this.universe.getZoneCoord(player.getLocation().getZ()), player.getLocation().getWorld()); if (z != null) { if (z.ownername.equals(player.getName())) { z.setOwner(""); z.name = "Abandoned land"; for (myZoneMember zm : this.universe.zonemembers.values()) { if (zm.zoneid == z.id) { // member of town zm = null; } } player.getServer().broadcastMessage(ChatColor.LIGHT_PURPLE+"* "+ player.getName()+" has lost one of his civilizations!"); player.sendMessage("Thanks! Here's " +ChatColor.YELLOW+ 5000 + ChatColor.WHITE+" coin from the sale of our land!"); this.universe.addPlayerBalance(player,5000); player.sendMessage("You just released region: ["+ChatColor.LIGHT_PURPLE+z.x+","+z.z+""+ChatColor.WHITE+"]!"); this.universe.setPlayerLastChunkX(player,z.x); this.universe.setPlayerLastChunkZ(player,z.z); this.universe.setPlayerLastChunkName(player,"Abandoned land"); } else { player.sendMessage("Sorry this zone is not yours to abandon"); } } else { player.sendMessage("Failed to abandon zone at your location - target zone does not exist"); } } if (subCommand.equals("here")) { int playerx = this.universe.getZoneCoord(player.getLocation().getX()); int playerz = this.universe.getZoneCoord(player.getLocation().getZ()); for (myZone z : this.universe.zones) { if (z.x == playerx && z.z == playerz) { player.sendMessage("["+ChatColor.LIGHT_PURPLE+""+z.x+","+z.z+""+ChatColor.WHITE+"] "+ChatColor.YELLOW+""+z.name); } else { // zone not in list } } } } // ops only try { // // NPCX COMMAND MENU // if (!command.getName().toLowerCase().equals("npcx")) { return false; } if (!(sender instanceof Player)) { return false; } if (sender.isOp() == false) { return false; } Player player = (Player) sender; if (args.length < 1) { player.sendMessage("Insufficient arguments /npcx spawngroup"); player.sendMessage("Insufficient arguments /npcx faction"); player.sendMessage("Insufficient arguments /npcx loottable"); player.sendMessage("Insufficient arguments /npcx npc"); player.sendMessage("Insufficient arguments /npcx pathgroup"); player.sendMessage("Insufficient arguments /npcx merchant"); player.sendMessage("Insufficient arguments /npcx civ"); return false; } String subCommand = args[0].toLowerCase(); //debug: logger.log(Level.WARNING, "npcx : " + command.getName().toLowerCase() + "(" + subCommand + ")"); Location l = player.getLocation(); if (subCommand.equals("debug")) { } if (subCommand.equals("spawngroup")) { // Overview: // A spawngroup is like a container. It contains many npcs and any one of them could spawn randomly. // If you placed just one npc in the group only one npc would spawn. This allows you to create 'rare' npcs // Spawngroups need to be assigned to a location with 'spawngroup place' Once assigned that group // will spawn in that location and remain stationary // If a path is assigned to the spawn group, the npc will follow the path continuously after spawning // at the location of 'spawngroup place' // todo: functionality // creates a new spawngroup with name // adds an npc to a spawngroup with a chance // makes the spawngroup spawn at your location // assigns a path to the spawngroup if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx spawngroup create spawngroupname"); player.sendMessage("Insufficient arguments /npcx spawngroup add spawngroupid npcid"); player.sendMessage("Insufficient arguments /npcx spawngroup pathgroup spawngroupid pathgroupid"); player.sendMessage("Insufficient arguments /npcx spawngroup list [name]"); player.sendMessage("Insufficient arguments /npcx spawngroup updatepos spawngroupid"); player.sendMessage("Insufficient arguments /npcx spawngroup delete spawngroupid"); player.sendMessage("Insufficient arguments /npcx version"); return false; } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx spawngroup create spawngroupname"); } else { player.sendMessage("Created spawngroup: " + args[2]); double x = player.getLocation().getX(); double y = player.getLocation().getY(); double z = player.getLocation().getZ(); double pitch = player.getLocation().getPitch(); double yaw = player.getLocation().getYaw(); PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO spawngroup (name,x,y,z,pitch,yaw) VALUES (?,?,?,?,?,?);",Statement.RETURN_GENERATED_KEYS); stmt.setString(1,args[2]); stmt.setString(2, Double.toString(x)); stmt.setString(3, Double.toString(y)); stmt.setString(4, Double.toString(z)); stmt.setString(5, Double.toString(pitch)); stmt.setString(6, Double.toString(yaw)); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } stmt.close(); player.sendMessage("Spawngroup ["+ key + "] now active at your position"); mySpawngroup sg = new mySpawngroup(this); sg.id = key; sg.name = args[2]; sg.x = x; sg.y = y; sg.z = z; sg.pitch = pitch; sg.yaw = yaw; sg.world = player.getWorld(); this.universe.spawngroups.put(Integer.toString(key),sg); System.out.println("npcx : + cached new spawngroup("+ args[2] + ")"); } } if (args[1].equals("delete")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx spawngroup delete spawngroupid"); } else { int count = 0; for (mySpawngroup spawngroup : this.universe.spawngroups.values()) { if (spawngroup.id == Integer.parseInt(args[2])) { spawngroup.DBDelete(); count++; } } player.sendMessage("Deleted cached "+count+" spawngroups."); } } if (args[1].equals("pathgroup")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx spawngroup pathgroup spawngroupid pathgroupid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE spawngroup SET pathgroupid = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(mySpawngroup sg : universe.spawngroups.values()) { if (sg.id == Integer.parseInt(args[2])) { if (Integer.parseInt(args[3]) != 0) { sg.pathgroup = getPathgroupByID(Integer.parseInt(args[3])); for (myNPC n : universe.npcs.values()) { if (n.spawngroup == sg) { n.pathgroup = sg.pathgroup; } } player.sendMessage("npcx : Updated spawngroups cached pathgroup ("+args[3]+"): "+sg.pathgroup.name); } else { sg.pathgroup = null; sg.pathgroup = getPathgroupByID(Integer.parseInt(args[3])); for (myNPC n : universe.npcs.values()) { if (n.spawngroup == sg) { n.pathgroup = null; } } player.sendMessage("npcx : Updated spawngroups cached pathgroup (0)"); } } } player.sendMessage("Updated pathgroup ID:" + args[3] + " on spawngroup ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("add")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx spawngroup add spawngroup npcid"); } else { player.sendMessage("Added to spawngroup " + args[2] + "<"+ args[3]+ "."); // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO spawngroup_entries (spawngroupid,npcid) VALUES (?,?);",Statement.RETURN_GENERATED_KEYS); s2.setString(1,args[2]); s2.setString(2,args[3]); s2.executeUpdate(); player.sendMessage("NPC ["+ args[3] + "] added to group ["+ args[2] + "]"); // add to cached spawngroup for (mySpawngroup sg : universe.spawngroups.values()) { if (sg.id == Integer.parseInt(args[2])) { PreparedStatement stmtNPC = this.universe.conn.prepareStatement("SELECT * FROM npc WHERE id = ?;"); stmtNPC.setString(1,args[3]); stmtNPC.executeQuery(); ResultSet rsNPC = stmtNPC.getResultSet (); int count = 0; while (rsNPC.next ()) { Location loc = new Location(getServer().getWorld(this.universe.defaultworld),0,0,0,0,0); myNPC npc = new myNPC(this,universe.fetchTriggerWords(Integer.parseInt(args[3])), loc, "dummy"); npc.name = rsNPC.getString ("name"); npc.category = rsNPC.getString ("category"); npc.faction = dbGetNPCfaction(args[3]); npc.loottable = dbGetNPCloottable(args[3]); npc.helmet = rsNPC.getInt ("helmet"); npc.pathgroup = sg.pathgroup; npc.chest = rsNPC.getInt ("chest"); npc.legs = rsNPC.getInt ("legs"); npc.boots = rsNPC.getInt ("boots"); npc.weapon = rsNPC.getInt ("weapon"); npc.spawngroup = sg; npc.id = args[3]; sg.npcs.put(sg.id+"-"+npc.id, npc); universe.npcs.put(sg.id+"-"+npc.id, npc); ++count; } rsNPC.close(); stmtNPC.close(); dbg(1,"npcx : + cached new spawngroup entry("+ args[3] + ")"); } } mySpawngroup sg = new mySpawngroup(this); // close db s2.close(); } } if (args[1].equals("updatepos")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx spawngroup updatepos spawngroupid"); } else { Location loc = player.getLocation(); PreparedStatement s2 = this.universe.conn.prepareStatement("UPDATE spawngroup SET x=?,y=?,z=?,yaw=?,pitch=? WHERE id = ?;"); s2.setString(1,Double.toString(loc.getX())); s2.setString(2,Double.toString(loc.getY())); s2.setString(3,Double.toString(loc.getZ())); s2.setString(4,Double.toString(loc.getYaw())); s2.setString(5,Double.toString(loc.getPitch())); s2.setString(6,args[2]); s2.executeUpdate(); player.sendMessage("Updated Spawngroup " + args[2] + " to your position"); // Update cached spawngroups for (mySpawngroup sg : this.universe.spawngroups.values()) { if (sg.id == Integer.parseInt(args[2])) { // update the spawngroup sg.x = loc.getX(); sg.y = loc.getY(); sg.z = loc.getZ(); sg.yaw = loc.getYaw(); sg.pitch = loc.getPitch(); dbg(1,"npcx : + cached updated spawngroup ("+ args[2] + ")"); // Found the spawngroup, lets make sure the NPCs have their spawn values set right for (myNPC np : sg.npcs.values()) { if (np.npc != null) { np.npc.spawnx = sg.x; np.npc.spawny = sg.y; np.npc.spawnz = sg.z; np.npc.spawnyaw = sg.yaw; np.npc.spawnpitch = sg.pitch; Location locnpc = new Location(getServer().getWorld(this.universe.defaultworld),loc.getX(),loc.getY(),loc.getZ(),loc.getYaw(),loc.getPitch()); np.npc.forceMove(locnpc); } } } } // close statement s2.close(); } } if (args[1].equals("list")) { player.sendMessage("Spawngroups:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM spawngroup ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM spawngroup WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } } // // START CIV // if (subCommand.equals("civ")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx civ givemoney playername amount"); player.sendMessage("Insufficient arguments /npcx civ money playername"); player.sendMessage("Insufficient arguments /npcx civ unclaim"); return false; } if (args[1].matches("money")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx civ money playername"); return false; } else { for (myPlayer p : this.universe.players.values()) { if (p.player.getName().matches(args[2])) { player.sendMessage("Balance: " + p.getNPCXBalance()); } } } } if (args[1].matches("givemoney")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx civ givemoney playername amount"); return false; } else { for (myPlayer p : this.universe.players.values()) { if (p.player.getName().matches(args[2])) { p.setNPCXBalance(p.getNPCXBalance() + (Integer.parseInt(args[3]))); player.sendMessage("Added to balance " + args[2] + "<"+ args[3]); } } } } if (args[1].matches("unclaim")) { myZone z = this.universe.getZoneFromChunkAndLoc(this.universe.getZoneCoord(player.getLocation().getX()),this.universe.getZoneCoord(player.getLocation().getZ()), player.getLocation().getWorld()); if (z != null) { z.setOwner(""); z.name = "Refurbished land"; player.sendMessage("You just released region: ["+ChatColor.LIGHT_PURPLE+z.x+","+z.z+""+ChatColor.WHITE+"]!"); this.universe.setPlayerLastChunkX(player,z.x); this.universe.setPlayerLastChunkZ(player,z.z); this.universe.setPlayerLastChunkName(player,"Refurbished land"); } else { player.sendMessage("Failed to buy zone at your location - target zone does not exist"); } } } // // START LOOTTABLE // if (subCommand.equals("loottable")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx loottable create loottablename"); player.sendMessage("Insufficient arguments /npcx loottable list"); player.sendMessage("Insufficient arguments /npcx loottable add loottableid itemid amount"); return false; } if (args[1].equals("add")) { if (args.length < 5) { player.sendMessage("Insufficient arguments /npcx loottable add loottableid itemid amount"); return false; } else { player.sendMessage("Added to loottable " + args[2] + "<"+ args[3]+ "x"+args[4]+"."); // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO loottable_entries (loottable_id,item_id,amount) VALUES (?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setString(1,args[2]); s2.setString(2,args[3]); s2.setString(3,args[4]); s2.executeUpdate(); player.sendMessage("NPC ["+ args[3] + "x"+args[4]+"] added to group ["+ args[2] + "]"); // add to cached loottable for (myLoottable lt : this.universe.loottables) { if (lt.id == Integer.parseInt(args[2])) { myLoottable_entry entry = new myLoottable_entry(); entry.id = Integer.parseInt(args[2]); entry.itemid = Integer.parseInt(args[3]); entry.amount = Integer.parseInt(args[4]); dbg(1,"npcx : + cached new loottable entry("+ args[3] + ")"); lt.loottable_entries.add(entry); } } mySpawngroup sg = new mySpawngroup(this); // close statement s2.close(); } } if (args[1].equals("create")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx loottable create loottablename"); return false; } else { try { PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO loottables (name) VALUES (?);",Statement.RETURN_GENERATED_KEYS); stmt.setString(1,args[2]); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } stmt.close(); player.sendMessage("Loottable ["+ key + "] now active"); myLoottable fa = new myLoottable(key,args[2]); fa.id = key; fa.name = args[2]; this.universe.loottables.add(fa); dbg(1,"npcx : + cached new loottable ("+ args[2] + ")"); } catch (IndexOutOfBoundsException e) { player.sendMessage("Insufficient arguments"); } } } if (args[1].equals("list")) { player.sendMessage("Loottables:"); Statement s = this.universe.conn.createStatement (); s.executeQuery ("SELECT id, name FROM loottables"); ResultSet rs = s.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); player.sendMessage( "id = " + idVal + ", name = " + nameVal); Statement sFindEntries = this.universe.conn.createStatement(); sFindEntries.executeQuery("SELECT * FROM loottable_entries WHERE loottable_id = " + idVal); ResultSet rsEntries = sFindEntries.getResultSet (); int countentries = 0; while (rsEntries.next ()) { int id = rsEntries.getInt("id"); int itemid = rsEntries.getInt("item_id"); int loottableid = rsEntries.getInt("loottable_id"); int amount = rsEntries.getInt("amount"); player.sendMessage( " + id = " + id + ", loottableid = " + loottableid + ", itemid = " + itemid + ", amount = " + amount); countentries++; } player.sendMessage (countentries + " entries in this set"); ++count; } rs.close (); s.close (); player.sendMessage (count + " loottables were retrieved"); } } // END LOOTTABLE // // START FACTION // if (subCommand.equals("faction")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx faction create baseamount factionname"); player.sendMessage("Insufficient arguments /npcx faction list"); player.sendMessage("Insufficient arguments /npcx faction npc npcid factionid amount"); return false; } if (args[1].equals("npc")) { if (args.length < 5) { player.sendMessage("Insufficient arguments /npcx faction npc add npcid factionid amount"); } else { // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO npc_faction (npc_id,faction_id,amount) VALUES (?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setInt(1,Integer.parseInt(args[2])); s2.setInt(2,Integer.parseInt(args[3])); s2.setInt(3,Integer.parseInt(args[4])); s2.executeUpdate(); ResultSet keyset = s2.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } s2.close(); myNpc_faction nf = new myNpc_faction(key, Integer.parseInt(args[2]), Integer.parseInt(args[3]), Integer.parseInt(args[4])); player.sendMessage("Added to npc faction ["+key+"] "+args[2]+"<" + args[3] + "="+ args[4]+ "."); this.universe.npcfactions.put(Integer.toString(nf.id), nf); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx faction create baseamount factionname"); } else { try { PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO faction_list (name,base) VALUES (?,?);",Statement.RETURN_GENERATED_KEYS); stmt.setString(1,args[3]); stmt.setInt(2,Integer.parseInt(args[2])); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } stmt.close(); player.sendMessage("Faction ["+ key + "] now active"); myFaction fa = new myFaction(); fa.id = key; fa.name = args[3]; fa.base = Integer.parseInt(args[2]); this.universe.factions.add(fa); dbg(1,"npcx : + cached new faction("+ args[3] + ")"); } catch (IndexOutOfBoundsException e) { player.sendMessage("Insufficient arguments"); } } } if (args[1].equals("list")) { player.sendMessage("Factions:"); Statement s = this.universe.conn.createStatement (); s.executeQuery ("SELECT id, name, base FROM faction_list"); ResultSet rs = s.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String baseVal = rs.getString ("base"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", base = " + baseVal); ++count; } rs.close (); s.close (); player.sendMessage (count + " rows were retrieved"); } } // END FACTION if (subCommand.equals("pathgroup")) { if (args.length < 2) { // todo: need to implement npc types here ie: 0 = default 1 = banker 2 = merchant // todo: need to implement '/npcx npc edit' here player.sendMessage("Insufficient arguments /npcx pathgroup create name"); // todo needs to force the player to provide a search term to not spam them with lots of results in the event of a huge npc list player.sendMessage("Insufficient arguments /npcx pathgroup list"); player.sendMessage("Insufficient arguments /npcx pathgroup add pathgroupid order"); player.sendMessage("Insufficient arguments /npcx pathgroup inspect pathgroupid"); return false; } if (args[1].equals("inspect")) { player.sendMessage("Pathgroup Entries:"); if (args.length >= 3) { PreparedStatement pginspect = this.universe.conn.prepareStatement("SELECT id,s,x,y,z,pathgroup,name FROM pathgroup_entries WHERE pathgroup = ? ORDER BY s ASC"); pginspect.setInt(1, Integer.parseInt(args[2])); pginspect.executeQuery (); ResultSet rspginspect = pginspect.getResultSet (); int count = 0; while (rspginspect.next ()) { int idVal = rspginspect.getInt ("id"); String nameVal = rspginspect.getString ("name"); int s = rspginspect.getInt ("s"); int pgid = rspginspect.getInt ("pathgroup"); String x = rspginspect.getString ("x"); String y = rspginspect.getString ("y"); String z = rspginspect.getString ("z"); player.sendMessage("s: "+s+" pgid: "+pgid+" XYZ: "+x+","+y+","+z); ++count; } rspginspect.close (); pginspect.close (); player.sendMessage (count + " rows were retrieved"); } else { player.sendMessage("Insufficient arguments /npcx pathgroup inspect pathgroupid"); } } if (args[1].equals("add")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx pathgroup add pathgroupid order"); } else { player.sendMessage("Added to pathgroup " + args[2] + "<"+ args[3]+ "."); // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO pathgroup_entries (pathgroup,s,x,y,z,pitch,yaw) VALUES (?,?,?,?,?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setString(1,args[2]); s2.setString(2,args[3]); s2.setDouble(3,player.getLocation().getX()); s2.setDouble(4,player.getLocation().getY()); s2.setDouble(5,player.getLocation().getZ()); s2.setFloat(6,player.getLocation().getPitch()); s2.setFloat(7,player.getLocation().getYaw()); s2.executeUpdate(); player.sendMessage("Pathing Position ["+ args[3] + "] added to pathggroup ["+ args[2] + "]"); // add to cached spawngroup for (myPathgroup pg : this.universe.pathgroups) { if (pg.id == Integer.parseInt(args[2])) { int dpathgroupid = Integer.parseInt(args[2]); int dspot = Integer.parseInt(args[3]); myPathgroup_entry pge = new myPathgroup_entry(player.getLocation(),dpathgroupid,pg,dspot); dbg(1,"npcx : + cached new pathgroup entry("+ args[3] + ")"); // add new pathgroup entry object to the pathgroups entry list pg.pathgroupentries.add(pge); } } // close db s2.close(); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx pathgroup create name"); } else { PreparedStatement statementPCreate = this.universe.conn.prepareStatement("INSERT INTO pathgroup (name) VALUES (?)",Statement.RETURN_GENERATED_KEYS); statementPCreate.setString(1, args[2]); statementPCreate.executeUpdate(); ResultSet keyset = statementPCreate.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } myPathgroup pathgroup = new myPathgroup(); pathgroup.id = key; pathgroup.name = args[2]; this.universe.pathgroups.add(pathgroup); statementPCreate.close(); player.sendMessage("Created pathgroup ["+key+"]: " + args[2]); } } if (args[1].equals("list")) { player.sendMessage("Pathgroups:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM pathgroup ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM pathgroup WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } } if (subCommand.equals("merchant")) { if (args.length < 2) { // todo: need to implement npc types here ie: 0 = default 1 = banker 2 = merchant // todo: need to implement '/npcx npc edit' here player.sendMessage("Insufficient arguments /npcx merchant create name"); // todo needs to force the player to provide a search term to not spam them with lots of results in the event of a huge npc list player.sendMessage("Insufficient arguments /npcx merchant list"); player.sendMessage("Insufficient arguments /npcx merchant add merchantid item amount pricebuyat pricesellat"); player.sendMessage("Insufficient arguments /npcx merchant inspect merchantid"); player.sendMessage("Insufficient arguments /npcx merchant category merchantid category"); return false; } if (args[1].equals("category")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx merchant category merchantid category"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE merchant SET category = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myMerchant n : universe.merchants) { if (n.id == Integer.parseInt(args[2])) { n.category = args[3]; player.sendMessage("npcx : Updated merchant to cached category ("+args[3]+"): "+n.category); // when faction changes reset aggro and follow status } } player.sendMessage("Updated merchant category :" + args[3] + " on Merchant ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("inspect")) { player.sendMessage("Merchant Entries:"); if (args.length >= 3) { PreparedStatement pginspect = this.universe.conn.prepareStatement("SELECT id,merchantid,itemid,amount,pricebuy,pricesell FROM merchant_entries WHERE merchantid = ? ORDER BY id ASC"); pginspect.setInt(1, Integer.parseInt(args[2])); pginspect.executeQuery (); ResultSet rspginspect = pginspect.getResultSet (); int count = 0; while (rspginspect.next ()) { int idVal = rspginspect.getInt ("id"); int merchantid = rspginspect.getInt ("merchantid"); int itemid = rspginspect.getInt ("itemid"); int amount = rspginspect.getInt ("amount"); int pricebuy = rspginspect.getInt ("pricebuy"); int pricesell = rspginspect.getInt ("pricesell"); player.sendMessage("EID:"+idVal+":MID:"+merchantid+" Item:"+itemid +" - Amount: "+amount+" Buying: "+pricebuy+"Selling: "+pricesell); ++count; } rspginspect.close (); pginspect.close (); player.sendMessage (count + " rows were retrieved"); } else { player.sendMessage("Insufficient arguments /npcx merchant inspect merchantid"); } } if (args[1].equals("add")) { if (args.length < 6) { player.sendMessage("Insufficient arguments /npcx merchant add merchantid itemid amount pricebuyat pricesellat"); } else { // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO merchant_entries (merchantid,itemid,amount,pricebuy,pricesell) VALUES (?,?,?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setInt (1,Integer.parseInt(args[2])); s2.setInt (2,Integer.parseInt(args[3])); s2.setInt (3,Integer.parseInt(args[4])); s2.setInt (4,Integer.parseInt(args[5])); s2.setInt (5,Integer.parseInt(args[6])); s2.executeUpdate(); player.sendMessage("Merchant Item ["+ args[3] + "x" + args[4] + "@"+args[5]+"/"+args[6]+"] added to Merchant: ["+ args[2] + "]"); // add to cached spawngroup for (myMerchant pg : this.universe.merchants) { if (pg.id == Integer.parseInt(args[2])) { int dmerchantid = Integer.parseInt(args[2]); int itemid = Integer.parseInt(args[3]); int amount = Integer.parseInt(args[4]); int pricebuy = Integer.parseInt(args[5]); int pricesell = Integer.parseInt(args[6]); myMerchant_entry pge = new myMerchant_entry(pg, dmerchantid,itemid,amount,pricebuy,pricesell); dbg("npcx : + cached new merchant entry("+ args[3] + ")"); // add new merchant entry object to the merchants entry list pg.merchantentries.add(pge); player.sendMessage("Added to merchant " + args[2] + "<"+ args[3]+ "x"+args[4]+"@"+args[5]+"."); } } // close db s2.close(); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx merchant create name"); } else { PreparedStatement statementPCreate = this.universe.conn.prepareStatement("INSERT INTO merchant (name) VALUES (?)",Statement.RETURN_GENERATED_KEYS); statementPCreate.setString(1, args[2]); statementPCreate.executeUpdate(); ResultSet keyset = statementPCreate.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } myMerchant merchant = new myMerchant(this,key,args[2]); merchant.id = key; merchant.name = args[2]; this.universe.merchants.add(merchant); statementPCreate.close(); player.sendMessage("Created merchant ["+key+"]: " + args[2]); } } if (args[1].equals("list")) { player.sendMessage("merchants:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM merchant ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM merchant WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + rs.getString ("category")); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } } if (subCommand.equals("version")) { PluginDescriptionFile pdfFile = this.getDescription(); player.sendMessage("npcx version "+ pdfFile.getVersion() + " db version: " + this.universe.dbversion); } if (subCommand.equals("npc")) { // Overview: // NPCs are just that, definitions of the mob you want to appear in game. There can be multiple of the same // npc in many spawngroups, for example if you wanted a custom npc called 'Thief' to spawn in several locations // you would put the npc into many spawn groups // In the future these npcs will support npctypes which determines how the npc will respond to right click, attack, etc events // ie for: bankers, normal npcs, merchants etc // Also loottables will be assignable // todo: functionality // creates a new npc with name if (args.length < 2) { // todo: need to implement npc types here ie: 0 = default 1 = banker 2 = merchant // todo: need to implement '/npcx npc edit' here player.sendMessage("Insufficient arguments /npcx npc create name"); // todo needs to force the player to provide a search term to not spam them with lots of results in the event of a huge npc list player.sendMessage("Insufficient arguments /npcx npc list [name]"); // spawns the npc temporarily at your current spot for testing //player.sendMessage("Insufficient arguments /npcx npc spawn name"); player.sendMessage("Insufficient arguments /npcx npc triggerword add npcid triggerword response"); player.sendMessage("Insufficient arguments /npcx npc faction npcid factionid"); player.sendMessage("Insufficient arguments /npcx npc loottable npcid loottableid"); player.sendMessage("Insufficient arguments /npcx npc category npcid category"); player.sendMessage("Insufficient arguments /npcx npc merchant npcid merchantid"); player.sendMessage("Insufficient arguments /npcx npc weapon npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc helmet npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc chest npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc legs npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc boots npcid itemid"); return false; } if (args[1].equals("merchant")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc merchant npcid merchantid"); return false; } else { if (Integer.parseInt(args[3]) == 0) { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET merchantid = null WHERE id = ?;"); stmt.setString(1, args[2]); stmt.executeUpdate(); stmt.close(); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET merchantid = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); stmt.close(); } int count = 0; for(myNPC sg : universe.npcs.values()) { //player.sendMessage("npcx : Checking: "+sg.name); if (sg.id.matches(args[2])) { if (Integer.parseInt(args[3]) != 0) { sg.merchant = getMerchantByID(Integer.parseInt(args[3])); player.sendMessage("npcx : Updated NPCs cached merchant ("+args[3]+"): "+sg.merchant.name); count++; } else { sg.merchant = null; player.sendMessage("npcx : Updated NPCs cached merchant (0)"); count++; } } } player.sendMessage("Updated "+count+" entries."); } } if (args[1].equals("triggerword")) { if (args.length < 6) { player.sendMessage("Insufficient arguments /npcx npc triggerword add npcid triggerword response"); } else { String reply = ""; int current = 6; while (current <= args.length) { reply = reply + args[current-1]+" "; current++; } reply = reply.substring(0,reply.length()-1); PreparedStatement statementTword = this.universe.conn.prepareStatement("INSERT INTO npc_triggerwords (npcid,triggerword,reply) VALUES (?,?,?)",Statement.RETURN_GENERATED_KEYS); statementTword.setString(1,args[3]); statementTword.setString(2,args[4]); statementTword.setString(3,reply); statementTword.executeUpdate(); ResultSet keyset = statementTword.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } player.sendMessage("Added ("+universe.npcs.values().size()+") triggerword ["+key+"] to npc "+args[3]); // add it to any spawned npcs for (myNPC npc : universe.npcs.values()) { dbg(1,"my id="+npc.id.toString()); if (npc.id.equals(args[3])) { dbg(1,"npcx : adding reply because ("+ npc.id +") is ("+args[3]+") ("+ reply + ") and trigger ("+ reply +") for [" + args[3] + "] npc to npc: " + npc.id); myTriggerword tw = new myTriggerword(); tw.word = args[4]; tw.id = key; tw.response = reply; player.sendMessage("Added triggerword to Active npc "+args[3]); npc.triggerwords.put(Integer.toString(tw.id), tw); } } } } if (args[1].equals("chest")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc chest npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET chest = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.chest = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.chest); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setChestplate(i); player.sendMessage("npcx : Updated living npc to cached chest ("+args[3]+"): "+n.chest); stmt.executeUpdate(); } } player.sendMessage("Updated npc chest: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("helmet")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc helmet npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET helmet = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.helmet = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.helmet); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setHelmet(i); player.sendMessage("npcx : Updated living npc to cached helmet ("+args[3]+"): "+n.helmet); stmt.executeUpdate(); } } player.sendMessage("Updated npc helmet: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("weapon")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc weapon npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET weapon = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.weapon = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.weapon); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setItemInHand(i); player.sendMessage("npcx : Updated living npc to cached weapon ("+args[3]+"): "+n.weapon); stmt.executeUpdate(); } } player.sendMessage("Updated npc weapon: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("boots")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc boots npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET boots = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.boots = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.boots); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setBoots(i); player.sendMessage("npcx : Updated living npc to cached boots ("+args[3]+"): "+n.boots); stmt.executeUpdate(); } } player.sendMessage("Updated npc boots: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("legs")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc legs npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET legs = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.legs = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.legs); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setLeggings(i); player.sendMessage("npcx : Updated living npc to cached legs ("+args[3]+"): "+n.legs); stmt.executeUpdate(); } } player.sendMessage("Updated npc legs: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("faction")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc faction npcid factionid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET faction_id = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.faction = getFactionByID(Integer.parseInt(args[3])); player.sendMessage("npcx : Updated living npc to cached faction ("+args[3]+"): "+n.faction.name); // when faction changes reset aggro and follow status n.npc.aggro = null; n.npc.follow = null; } } player.sendMessage("Updated npc faction ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("category")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc category npcid category"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET category = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.category = args[3]; player.sendMessage("npcx : Updated living npc to cached category ("+args[3]+"): "+n.category); // when faction changes reset aggro and follow status } } player.sendMessage("Updated npc category :" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("list")) { player.sendMessage("Npcs:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM npc ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM npc WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } if (args[1].equals("loottable")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc loottable npcid loottableid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET loottable_id = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.loottable = getLoottableByID(Integer.parseInt(args[3])); player.sendMessage("npcx : Updated living npc to cached loottable ("+args[3]+"): "+n.loottable.name); } } player.sendMessage("Updated npc loottable ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx npc create npcname"); } else { Statement s2 = this.universe.conn.createStatement (); PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO npc (name,weapon,helmet,chest,legs,boots) VALUES (?,'267','0','307','308','309');",Statement.RETURN_GENERATED_KEYS); stmt.setString(1, args[2]); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } player.sendMessage("Created npc: " + args[2] + " ID:[" + key + "]"); s2.close(); } } /* * Disabled temporarily * if (args[1].equals("spawn")) { player.sendMessage("Spawning new (temporary) NPC: " + args[2]); // temporary Location loc = new Location(player.getWorld(),player.getLocation().getX(),player.getLocation().getY(),player.getLocation().getZ(),player.getLocation().getYaw(),player.getLocation().getPitch()); myNPC npc = new myNPC(this, null, loc, args[2]); npc.Spawn(args[2],loc); this.universe.npcs.put("ZZSpawns"+"-"+npc.id,npc); this.npclist.put(args[2], npc.npc); return true; } */ } } catch (Exception e) { sender.sendMessage("An error occured."); logger.log(Level.WARNING, "npcx: error: " + e.getMessage() + e.getStackTrace().toString()); e.printStackTrace(); return true; } return true; }
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { // any player // // CIV COMMAND MENU // if (command.getName().toLowerCase().equals("civ")) { if (!(sender instanceof Player)) { return false; } Player player = (Player) sender; if (args.length < 1) { player.sendMessage("Insufficient arguments /civ buy"); player.sendMessage("Insufficient arguments /civ add playername"); player.sendMessage("Insufficient arguments /civ here"); player.sendMessage("Insufficient arguments /civ gift playername"); player.sendMessage("Insufficient arguments /civ abandon"); return false; } String subCommand = args[0].toLowerCase(); if (subCommand.equals("add")) { int playerx = this.universe.getZoneCoord(player.getLocation().getX()); int playerz = this.universe.getZoneCoord(player.getLocation().getZ()); if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx civ add playername"); return false; } if (!args[1].equals(player.getName())) { for (myZone z : this.universe.zones) { if (z.x == playerx && z.z == playerz) { // are they the owner? if (this.universe.isZoneOwner(z.id, player.getName())) { // are they in alraedy if (this.universe.isZoneMember(z.id, args[1])) { player.sendMessage("Sorry that player is already in this civilisation!"); return false; } else { this.universe.addZoneMember(z.id,player.getName()); player.sendMessage("Player added to civilization!!"); return true; } } } else { // zone not in list } } } else { player.sendMessage("You cannot be a member of a town you own!"); return false; } } if (subCommand.equals("buy")) { int cost = 25000; if (cost <= this.universe.getPlayerBalance(player)) { Chunk c = player.getLocation().getWorld().getChunkAt(player.getLocation()); myZone z = this.universe.getZoneFromChunkAndLoc(this.universe.getZoneCoord(player.getLocation().getX()),this.universe.getZoneCoord(player.getLocation().getZ()), player.getLocation().getWorld()); if (z != null) { if (z.ownername.equals("")) { z.setOwner(player.getName()); z.name = player.getName()+"s land"; player.getServer().broadcastMessage(ChatColor.LIGHT_PURPLE+"* A new civilization has been settled at [" + z.x + ":" + z.z+ "] by "+player.getName()+"!"); player.sendMessage("Thanks! That's " +ChatColor.YELLOW+ cost + ChatColor.WHITE+" total coins!"); this.universe.subtractPlayerBalance(player,cost); player.sendMessage("You just bought region: ["+ChatColor.LIGHT_PURPLE+z.x+","+z.z+""+ChatColor.WHITE+"]!"); this.universe.setPlayerLastChunkX(player,z.x); this.universe.setPlayerLastChunkZ(player,z.z); this.universe.setPlayerLastChunkName(player,z.name); } else { player.sendMessage("Sorry this zone has already been purchased by another Civ"); } } else { player.sendMessage("Failed to buy zone at your location - target zone does not exist"); } } else { player.sendMessage("You don't have enough to buy this plot (25000)!"); } } if (subCommand.equals("abandon")) { myZone z = this.universe.getZoneFromChunkAndLoc(this.universe.getZoneCoord(player.getLocation().getX()),this.universe.getZoneCoord(player.getLocation().getZ()), player.getLocation().getWorld()); if (z != null) { if (z.ownername.equals(player.getName())) { z.setOwner(""); z.name = "Abandoned land"; for (myZoneMember zm : this.universe.zonemembers.values()) { if (zm.zoneid == z.id) { // member of town zm = null; } } player.getServer().broadcastMessage(ChatColor.LIGHT_PURPLE+"* "+ player.getName()+" has lost one of his civilizations!"); player.sendMessage("Thanks! Here's " +ChatColor.YELLOW+ 5000 + ChatColor.WHITE+" coin from the sale of our land!"); this.universe.addPlayerBalance(player,5000); player.sendMessage("You just released region: ["+ChatColor.LIGHT_PURPLE+z.x+","+z.z+""+ChatColor.WHITE+"]!"); this.universe.setPlayerLastChunkX(player,z.x); this.universe.setPlayerLastChunkZ(player,z.z); this.universe.setPlayerLastChunkName(player,"Abandoned land"); } else { player.sendMessage("Sorry this zone is not yours to abandon"); } } else { player.sendMessage("Failed to abandon zone at your location - target zone does not exist"); } } if (subCommand.equals("here")) { int playerx = this.universe.getZoneCoord(player.getLocation().getX()); int playerz = this.universe.getZoneCoord(player.getLocation().getZ()); for (myZone z : this.universe.zones) { if (z.x == playerx && z.z == playerz) { player.sendMessage("["+ChatColor.LIGHT_PURPLE+""+z.x+","+z.z+""+ChatColor.WHITE+"] "+ChatColor.YELLOW+""+z.name); } else { // zone not in list } } } } // ops only try { // // NPCX COMMAND MENU // if (!command.getName().toLowerCase().equals("npcx")) { return false; } if (!(sender instanceof Player)) { return false; } if (sender.isOp() == false) { return false; } Player player = (Player) sender; if (args.length < 1) { player.sendMessage("Insufficient arguments /npcx spawngroup"); player.sendMessage("Insufficient arguments /npcx faction"); player.sendMessage("Insufficient arguments /npcx loottable"); player.sendMessage("Insufficient arguments /npcx npc"); player.sendMessage("Insufficient arguments /npcx pathgroup"); player.sendMessage("Insufficient arguments /npcx merchant"); player.sendMessage("Insufficient arguments /npcx civ"); return false; } String subCommand = args[0].toLowerCase(); //debug: logger.log(Level.WARNING, "npcx : " + command.getName().toLowerCase() + "(" + subCommand + ")"); Location l = player.getLocation(); if (subCommand.equals("debug")) { } if (subCommand.equals("spawngroup")) { // Overview: // A spawngroup is like a container. It contains many npcs and any one of them could spawn randomly. // If you placed just one npc in the group only one npc would spawn. This allows you to create 'rare' npcs // Spawngroups need to be assigned to a location with 'spawngroup place' Once assigned that group // will spawn in that location and remain stationary // If a path is assigned to the spawn group, the npc will follow the path continuously after spawning // at the location of 'spawngroup place' // todo: functionality // creates a new spawngroup with name // adds an npc to a spawngroup with a chance // makes the spawngroup spawn at your location // assigns a path to the spawngroup if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx spawngroup create spawngroupname"); player.sendMessage("Insufficient arguments /npcx spawngroup add spawngroupid npcid"); player.sendMessage("Insufficient arguments /npcx spawngroup pathgroup spawngroupid pathgroupid"); player.sendMessage("Insufficient arguments /npcx spawngroup list [name]"); player.sendMessage("Insufficient arguments /npcx spawngroup updatepos spawngroupid"); player.sendMessage("Insufficient arguments /npcx spawngroup delete spawngroupid"); player.sendMessage("Insufficient arguments /npcx version"); return false; } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx spawngroup create spawngroupname"); } else { player.sendMessage("Created spawngroup: " + args[2]); double x = player.getLocation().getX(); double y = player.getLocation().getY(); double z = player.getLocation().getZ(); double pitch = player.getLocation().getPitch(); double yaw = player.getLocation().getYaw(); PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO spawngroup (name,x,y,z,pitch,yaw) VALUES (?,?,?,?,?,?);",Statement.RETURN_GENERATED_KEYS); stmt.setString(1,args[2]); stmt.setString(2, Double.toString(x)); stmt.setString(3, Double.toString(y)); stmt.setString(4, Double.toString(z)); stmt.setString(5, Double.toString(pitch)); stmt.setString(6, Double.toString(yaw)); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } stmt.close(); player.sendMessage("Spawngroup ["+ key + "] now active at your position"); mySpawngroup sg = new mySpawngroup(this); sg.id = key; sg.name = args[2]; sg.x = x; sg.y = y; sg.z = z; sg.pitch = pitch; sg.yaw = yaw; sg.world = player.getWorld(); this.universe.spawngroups.put(Integer.toString(key),sg); System.out.println("npcx : + cached new spawngroup("+ args[2] + ")"); } } if (args[1].equals("delete")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx spawngroup delete spawngroupid"); } else { int count = 0; for (mySpawngroup spawngroup : this.universe.spawngroups.values()) { if (spawngroup.id == Integer.parseInt(args[2])) { spawngroup.DBDelete(); count++; } } player.sendMessage("Deleted cached "+count+" spawngroups."); } } if (args[1].equals("pathgroup")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx spawngroup pathgroup spawngroupid pathgroupid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE spawngroup SET pathgroupid = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(mySpawngroup sg : universe.spawngroups.values()) { if (sg.id == Integer.parseInt(args[2])) { if (Integer.parseInt(args[3]) != 0) { sg.pathgroup = getPathgroupByID(Integer.parseInt(args[3])); for (myNPC n : universe.npcs.values()) { if (n.spawngroup == sg) { n.pathgroup = sg.pathgroup; } } player.sendMessage("npcx : Updated spawngroups cached pathgroup ("+args[3]+"): "+sg.pathgroup.name); } else { sg.pathgroup = null; sg.pathgroup = getPathgroupByID(Integer.parseInt(args[3])); for (myNPC n : universe.npcs.values()) { if (n.spawngroup == sg) { n.pathgroup = null; } } player.sendMessage("npcx : Updated spawngroups cached pathgroup (0)"); } } } player.sendMessage("Updated pathgroup ID:" + args[3] + " on spawngroup ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("add")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx spawngroup add spawngroup npcid"); } else { player.sendMessage("Added to spawngroup " + args[2] + "<"+ args[3]+ "."); // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO spawngroup_entries (spawngroupid,npcid) VALUES (?,?);",Statement.RETURN_GENERATED_KEYS); s2.setString(1,args[2]); s2.setString(2,args[3]); s2.executeUpdate(); player.sendMessage("NPC ["+ args[3] + "] added to group ["+ args[2] + "]"); // add to cached spawngroup for (mySpawngroup sg : universe.spawngroups.values()) { if (sg.id == Integer.parseInt(args[2])) { PreparedStatement stmtNPC = this.universe.conn.prepareStatement("SELECT * FROM npc WHERE id = ?;"); stmtNPC.setString(1,args[3]); stmtNPC.executeQuery(); ResultSet rsNPC = stmtNPC.getResultSet (); int count = 0; while (rsNPC.next ()) { Location loc = new Location(getServer().getWorld(this.universe.defaultworld),0,0,0,0,0); myNPC npc = new myNPC(this,universe.fetchTriggerWords(Integer.parseInt(args[3])), loc, "dummy"); npc.name = rsNPC.getString ("name"); npc.category = rsNPC.getString ("category"); npc.faction = dbGetNPCfaction(args[3]); npc.loottable = dbGetNPCloottable(args[3]); npc.helmet = rsNPC.getInt ("helmet"); npc.pathgroup = sg.pathgroup; npc.chest = rsNPC.getInt ("chest"); npc.legs = rsNPC.getInt ("legs"); npc.boots = rsNPC.getInt ("boots"); npc.weapon = rsNPC.getInt ("weapon"); npc.spawngroup = sg; npc.id = args[3]; sg.npcs.put(sg.id+"-"+npc.id, npc); universe.npcs.put(sg.id+"-"+npc.id, npc); ++count; } rsNPC.close(); stmtNPC.close(); dbg(1,"npcx : + cached new spawngroup entry("+ args[3] + ")"); } } mySpawngroup sg = new mySpawngroup(this); // close db s2.close(); } } if (args[1].equals("updatepos")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx spawngroup updatepos spawngroupid"); } else { Location loc = player.getLocation(); PreparedStatement s2 = this.universe.conn.prepareStatement("UPDATE spawngroup SET x=?,y=?,z=?,yaw=?,pitch=? WHERE id = ?;"); s2.setString(1,Double.toString(loc.getX())); s2.setString(2,Double.toString(loc.getY())); s2.setString(3,Double.toString(loc.getZ())); s2.setString(4,Double.toString(loc.getYaw())); s2.setString(5,Double.toString(loc.getPitch())); s2.setString(6,args[2]); s2.executeUpdate(); player.sendMessage("Updated Spawngroup " + args[2] + " to your position"); // Update cached spawngroups for (mySpawngroup sg : this.universe.spawngroups.values()) { if (sg.id == Integer.parseInt(args[2])) { // update the spawngroup sg.x = loc.getX(); sg.y = loc.getY(); sg.z = loc.getZ(); sg.yaw = loc.getYaw(); sg.pitch = loc.getPitch(); dbg(1,"npcx : + cached updated spawngroup ("+ args[2] + ")"); // Found the spawngroup, lets make sure the NPCs have their spawn values set right for (myNPC np : sg.npcs.values()) { if (np.npc != null) { np.npc.spawnx = sg.x; np.npc.spawny = sg.y; np.npc.spawnz = sg.z; np.npc.spawnyaw = sg.yaw; np.npc.spawnpitch = sg.pitch; Location locnpc = new Location(getServer().getWorld(this.universe.defaultworld),loc.getX(),loc.getY(),loc.getZ(),loc.getYaw(),loc.getPitch()); np.npc.forceMove(locnpc); } } } } // close statement s2.close(); } } if (args[1].equals("list")) { player.sendMessage("Spawngroups:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM spawngroup ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM spawngroup WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } } // // START CIV // if (subCommand.equals("civ")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx civ givemoney playername amount"); player.sendMessage("Insufficient arguments /npcx civ money playername"); player.sendMessage("Insufficient arguments /npcx civ unclaim"); return false; } if (args[1].matches("money")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx civ money playername"); return false; } else { for (myPlayer p : this.universe.players.values()) { if (p.player.getName().matches(args[2])) { player.sendMessage("Balance: " + p.getNPCXBalance()); } } } } if (args[1].matches("givemoney")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx civ givemoney playername amount"); return false; } else { for (myPlayer p : this.universe.players.values()) { if (p.player.getName().matches(args[2])) { p.setNPCXBalance(p.getNPCXBalance() + (Integer.parseInt(args[3]))); player.sendMessage("Added to balance " + args[2] + "<"+ args[3]); } } } } if (args[1].matches("unclaim")) { myZone z = this.universe.getZoneFromChunkAndLoc(this.universe.getZoneCoord(player.getLocation().getX()),this.universe.getZoneCoord(player.getLocation().getZ()), player.getLocation().getWorld()); if (z != null) { z.setOwner(""); z.name = "Refurbished land"; player.sendMessage("You just released region: ["+ChatColor.LIGHT_PURPLE+z.x+","+z.z+""+ChatColor.WHITE+"]!"); this.universe.setPlayerLastChunkX(player,z.x); this.universe.setPlayerLastChunkZ(player,z.z); this.universe.setPlayerLastChunkName(player,"Refurbished land"); } else { player.sendMessage("Failed to buy zone at your location - target zone does not exist"); } } } // // START LOOTTABLE // if (subCommand.equals("loottable")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx loottable create loottablename"); player.sendMessage("Insufficient arguments /npcx loottable list"); player.sendMessage("Insufficient arguments /npcx loottable add loottableid itemid amount"); return false; } if (args[1].equals("add")) { if (args.length < 5) { player.sendMessage("Insufficient arguments /npcx loottable add loottableid itemid amount"); return false; } else { player.sendMessage("Added to loottable " + args[2] + "<"+ args[3]+ "x"+args[4]+"."); // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO loottable_entries (loottable_id,item_id,amount) VALUES (?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setString(1,args[2]); s2.setString(2,args[3]); s2.setString(3,args[4]); s2.executeUpdate(); player.sendMessage("NPC ["+ args[3] + "x"+args[4]+"] added to group ["+ args[2] + "]"); // add to cached loottable for (myLoottable lt : this.universe.loottables) { if (lt.id == Integer.parseInt(args[2])) { myLoottable_entry entry = new myLoottable_entry(); entry.id = Integer.parseInt(args[2]); entry.itemid = Integer.parseInt(args[3]); entry.amount = Integer.parseInt(args[4]); dbg(1,"npcx : + cached new loottable entry("+ args[3] + ")"); lt.loottable_entries.add(entry); } } mySpawngroup sg = new mySpawngroup(this); // close statement s2.close(); } } if (args[1].equals("create")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx loottable create loottablename"); return false; } else { try { PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO loottables (name) VALUES (?);",Statement.RETURN_GENERATED_KEYS); stmt.setString(1,args[2]); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } stmt.close(); player.sendMessage("Loottable ["+ key + "] now active"); myLoottable fa = new myLoottable(key,args[2]); fa.id = key; fa.name = args[2]; this.universe.loottables.add(fa); dbg(1,"npcx : + cached new loottable ("+ args[2] + ")"); } catch (IndexOutOfBoundsException e) { player.sendMessage("Insufficient arguments"); } } } if (args[1].equals("list")) { player.sendMessage("Loottables:"); Statement s = this.universe.conn.createStatement (); s.executeQuery ("SELECT id, name FROM loottables"); ResultSet rs = s.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); player.sendMessage( "id = " + idVal + ", name = " + nameVal); Statement sFindEntries = this.universe.conn.createStatement(); sFindEntries.executeQuery("SELECT * FROM loottable_entries WHERE loottable_id = " + idVal); ResultSet rsEntries = sFindEntries.getResultSet (); int countentries = 0; while (rsEntries.next ()) { int id = rsEntries.getInt("id"); int itemid = rsEntries.getInt("item_id"); int loottableid = rsEntries.getInt("loottable_id"); int amount = rsEntries.getInt("amount"); player.sendMessage( " + id = " + id + ", loottableid = " + loottableid + ", itemid = " + itemid + ", amount = " + amount); countentries++; } player.sendMessage (countentries + " entries in this set"); ++count; } rs.close (); s.close (); player.sendMessage (count + " loottables were retrieved"); } } // END LOOTTABLE // // START FACTION // if (subCommand.equals("faction")) { if (args.length < 2) { player.sendMessage("Insufficient arguments /npcx faction create baseamount factionname"); player.sendMessage("Insufficient arguments /npcx faction list"); player.sendMessage("Insufficient arguments /npcx faction npc npcid factionid amount"); return false; } if (args[1].equals("npc")) { if (args.length < 5) { player.sendMessage("Insufficient arguments /npcx faction npc add npcid factionid amount"); } else { // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO npc_faction (npc_id,faction_id,amount) VALUES (?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setInt(1,Integer.parseInt(args[2])); s2.setInt(2,Integer.parseInt(args[3])); s2.setInt(3,Integer.parseInt(args[4])); s2.executeUpdate(); ResultSet keyset = s2.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } s2.close(); myNpc_faction nf = new myNpc_faction(key, Integer.parseInt(args[2]), Integer.parseInt(args[3]), Integer.parseInt(args[4])); player.sendMessage("Added to npc faction ["+key+"] "+args[2]+"<" + args[3] + "="+ args[4]+ "."); this.universe.npcfactions.put(Integer.toString(nf.id), nf); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx faction create baseamount factionname"); } else { try { PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO faction_list (name,base) VALUES (?,?);",Statement.RETURN_GENERATED_KEYS); stmt.setString(1,args[3]); stmt.setInt(2,Integer.parseInt(args[2])); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } stmt.close(); player.sendMessage("Faction ["+ key + "] now active"); myFaction fa = new myFaction(); fa.id = key; fa.name = args[3]; fa.base = Integer.parseInt(args[2]); this.universe.factions.add(fa); dbg(1,"npcx : + cached new faction("+ args[3] + ")"); } catch (IndexOutOfBoundsException e) { player.sendMessage("Insufficient arguments"); } } } if (args[1].equals("list")) { player.sendMessage("Factions:"); Statement s = this.universe.conn.createStatement (); s.executeQuery ("SELECT id, name, base FROM faction_list"); ResultSet rs = s.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String baseVal = rs.getString ("base"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", base = " + baseVal); ++count; } rs.close (); s.close (); player.sendMessage (count + " rows were retrieved"); } } // END FACTION if (subCommand.equals("pathgroup")) { if (args.length < 2) { // todo: need to implement npc types here ie: 0 = default 1 = banker 2 = merchant // todo: need to implement '/npcx npc edit' here player.sendMessage("Insufficient arguments /npcx pathgroup create name"); // todo needs to force the player to provide a search term to not spam them with lots of results in the event of a huge npc list player.sendMessage("Insufficient arguments /npcx pathgroup list"); player.sendMessage("Insufficient arguments /npcx pathgroup add pathgroupid order"); player.sendMessage("Insufficient arguments /npcx pathgroup inspect pathgroupid"); return false; } if (args[1].equals("inspect")) { player.sendMessage("Pathgroup Entries:"); if (args.length >= 3) { PreparedStatement pginspect = this.universe.conn.prepareStatement("SELECT id,s,x,y,z,pathgroup,name FROM pathgroup_entries WHERE pathgroup = ? ORDER BY s ASC"); pginspect.setInt(1, Integer.parseInt(args[2])); pginspect.executeQuery (); ResultSet rspginspect = pginspect.getResultSet (); int count = 0; while (rspginspect.next ()) { int idVal = rspginspect.getInt ("id"); String nameVal = rspginspect.getString ("name"); int s = rspginspect.getInt ("s"); int pgid = rspginspect.getInt ("pathgroup"); String x = rspginspect.getString ("x"); String y = rspginspect.getString ("y"); String z = rspginspect.getString ("z"); player.sendMessage("s: "+s+" pgid: "+pgid+" XYZ: "+x+","+y+","+z); ++count; } rspginspect.close (); pginspect.close (); player.sendMessage (count + " rows were retrieved"); } else { player.sendMessage("Insufficient arguments /npcx pathgroup inspect pathgroupid"); } } if (args[1].equals("add")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx pathgroup add pathgroupid order"); } else { player.sendMessage("Added to pathgroup " + args[2] + "<"+ args[3]+ "."); // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO pathgroup_entries (pathgroup,s,x,y,z,pitch,yaw) VALUES (?,?,?,?,?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setString(1,args[2]); s2.setString(2,args[3]); s2.setDouble(3,player.getLocation().getX()); s2.setDouble(4,player.getLocation().getY()); s2.setDouble(5,player.getLocation().getZ()); s2.setFloat(6,player.getLocation().getPitch()); s2.setFloat(7,player.getLocation().getYaw()); s2.executeUpdate(); player.sendMessage("Pathing Position ["+ args[3] + "] added to pathggroup ["+ args[2] + "]"); // add to cached spawngroup for (myPathgroup pg : this.universe.pathgroups) { if (pg.id == Integer.parseInt(args[2])) { int dpathgroupid = Integer.parseInt(args[2]); int dspot = Integer.parseInt(args[3]); myPathgroup_entry pge = new myPathgroup_entry(player.getLocation(),dpathgroupid,pg,dspot); dbg(1,"npcx : + cached new pathgroup entry("+ args[3] + ")"); // add new pathgroup entry object to the pathgroups entry list pg.pathgroupentries.add(pge); } } // close db s2.close(); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx pathgroup create name"); } else { PreparedStatement statementPCreate = this.universe.conn.prepareStatement("INSERT INTO pathgroup (name) VALUES (?)",Statement.RETURN_GENERATED_KEYS); statementPCreate.setString(1, args[2]); statementPCreate.executeUpdate(); ResultSet keyset = statementPCreate.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } myPathgroup pathgroup = new myPathgroup(); pathgroup.id = key; pathgroup.name = args[2]; this.universe.pathgroups.add(pathgroup); statementPCreate.close(); player.sendMessage("Created pathgroup ["+key+"]: " + args[2]); } } if (args[1].equals("list")) { player.sendMessage("Pathgroups:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM pathgroup ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM pathgroup WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } } if (subCommand.equals("merchant")) { if (args.length < 2) { // todo: need to implement npc types here ie: 0 = default 1 = banker 2 = merchant // todo: need to implement '/npcx npc edit' here player.sendMessage("Insufficient arguments /npcx merchant create name"); // todo needs to force the player to provide a search term to not spam them with lots of results in the event of a huge npc list player.sendMessage("Insufficient arguments /npcx merchant list"); player.sendMessage("Insufficient arguments /npcx merchant add merchantid item amount pricebuyat pricesellat"); player.sendMessage("Insufficient arguments /npcx merchant inspect merchantid"); player.sendMessage("Insufficient arguments /npcx merchant category merchantid category"); return false; } if (args[1].equals("category")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx merchant category merchantid category"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE merchant SET category = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myMerchant n : universe.merchants) { if (n.id == Integer.parseInt(args[2])) { n.category = args[3]; player.sendMessage("npcx : Updated merchant to cached category ("+args[3]+"): "+n.category); // when faction changes reset aggro and follow status } } player.sendMessage("Updated merchant category :" + args[3] + " on Merchant ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("inspect")) { player.sendMessage("Merchant Entries:"); if (args.length >= 3) { PreparedStatement pginspect = this.universe.conn.prepareStatement("SELECT id,merchantid,itemid,amount,pricebuy,pricesell FROM merchant_entries WHERE merchantid = ? ORDER BY id ASC"); pginspect.setInt(1, Integer.parseInt(args[2])); pginspect.executeQuery (); ResultSet rspginspect = pginspect.getResultSet (); int count = 0; while (rspginspect.next ()) { int idVal = rspginspect.getInt ("id"); int merchantid = rspginspect.getInt ("merchantid"); int itemid = rspginspect.getInt ("itemid"); int amount = rspginspect.getInt ("amount"); int pricebuy = rspginspect.getInt ("pricebuy"); int pricesell = rspginspect.getInt ("pricesell"); player.sendMessage("EID:"+idVal+":MID:"+merchantid+" Item:"+itemid +" - Amount: "+amount+" Buying: "+pricebuy+"Selling: "+pricesell); ++count; } rspginspect.close (); pginspect.close (); player.sendMessage (count + " rows were retrieved"); } else { player.sendMessage("Insufficient arguments /npcx merchant inspect merchantid"); } } if (args[1].equals("add")) { if (args.length < 6) { player.sendMessage("Insufficient arguments /npcx merchant add merchantid itemid amount pricebuyat pricesellat"); } else { // add to database PreparedStatement s2 = this.universe.conn.prepareStatement("INSERT INTO merchant_entries (merchantid,itemid,amount,pricebuy,pricesell) VALUES (?,?,?,?,?);",Statement.RETURN_GENERATED_KEYS); s2.setInt (1,Integer.parseInt(args[2])); s2.setInt (2,Integer.parseInt(args[3])); s2.setInt (3,Integer.parseInt(args[4])); s2.setInt (4,Integer.parseInt(args[5])); s2.setInt (5,Integer.parseInt(args[6])); s2.executeUpdate(); player.sendMessage("Merchant Item ["+ args[3] + "x" + args[4] + "@"+args[5]+"/"+args[6]+"] added to Merchant: ["+ args[2] + "]"); // add to cached spawngroup for (myMerchant pg : this.universe.merchants) { if (pg.id == Integer.parseInt(args[2])) { int dmerchantid = Integer.parseInt(args[2]); int itemid = Integer.parseInt(args[3]); int amount = Integer.parseInt(args[4]); int pricebuy = Integer.parseInt(args[5]); int pricesell = Integer.parseInt(args[6]); myMerchant_entry pge = new myMerchant_entry(pg, dmerchantid,itemid,amount,pricebuy,pricesell); dbg("npcx : + cached new merchant entry("+ args[3] + ")"); // add new merchant entry object to the merchants entry list pg.merchantentries.add(pge); player.sendMessage("Added to merchant " + args[2] + "<"+ args[3]+ "x"+args[4]+"@"+args[5]+"."); } } // close db s2.close(); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx merchant create name"); } else { PreparedStatement statementPCreate = this.universe.conn.prepareStatement("INSERT INTO merchant (name) VALUES (?)",Statement.RETURN_GENERATED_KEYS); statementPCreate.setString(1, args[2]); statementPCreate.executeUpdate(); ResultSet keyset = statementPCreate.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } myMerchant merchant = new myMerchant(this,key,args[2]); merchant.id = key; merchant.name = args[2]; this.universe.merchants.add(merchant); statementPCreate.close(); player.sendMessage("Created merchant ["+key+"]: " + args[2]); } } if (args[1].equals("list")) { player.sendMessage("merchants:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM merchant ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM merchant WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + rs.getString ("category")); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } } if (subCommand.equals("version")) { PluginDescriptionFile pdfFile = this.getDescription(); player.sendMessage("npcx version "+ pdfFile.getVersion() + " db version: " + this.universe.dbversion); } if (subCommand.equals("npc")) { // Overview: // NPCs are just that, definitions of the mob you want to appear in game. There can be multiple of the same // npc in many spawngroups, for example if you wanted a custom npc called 'Thief' to spawn in several locations // you would put the npc into many spawn groups // In the future these npcs will support npctypes which determines how the npc will respond to right click, attack, etc events // ie for: bankers, normal npcs, merchants etc // Also loottables will be assignable // todo: functionality // creates a new npc with name if (args.length < 2) { // todo: need to implement npc types here ie: 0 = default 1 = banker 2 = merchant // todo: need to implement '/npcx npc edit' here player.sendMessage("Insufficient arguments /npcx npc create name"); // todo needs to force the player to provide a search term to not spam them with lots of results in the event of a huge npc list player.sendMessage("Insufficient arguments /npcx npc list [name]"); // spawns the npc temporarily at your current spot for testing //player.sendMessage("Insufficient arguments /npcx npc spawn name"); player.sendMessage("Insufficient arguments /npcx npc triggerword add npcid triggerword response"); player.sendMessage("Insufficient arguments /npcx npc faction npcid factionid"); player.sendMessage("Insufficient arguments /npcx npc loottable npcid loottableid"); player.sendMessage("Insufficient arguments /npcx npc category npcid category"); player.sendMessage("Insufficient arguments /npcx npc merchant npcid merchantid"); player.sendMessage("Insufficient arguments /npcx npc weapon npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc helmet npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc chest npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc legs npcid itemid"); player.sendMessage("Insufficient arguments /npcx npc boots npcid itemid"); return false; } if (args[1].equals("merchant")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc merchant npcid merchantid"); return false; } else { if (Integer.parseInt(args[3]) == 0) { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET merchantid = null WHERE id = ?;"); stmt.setString(1, args[2]); stmt.executeUpdate(); stmt.close(); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET merchantid = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); stmt.close(); } int count = 0; for(myNPC sg : universe.npcs.values()) { //player.sendMessage("npcx : Checking: "+sg.name); if (sg.id.matches(args[2])) { if (Integer.parseInt(args[3]) != 0) { sg.merchant = getMerchantByID(Integer.parseInt(args[3])); player.sendMessage("npcx : Updated NPCs cached merchant ("+args[3]+"): "+sg.merchant.name); count++; } else { sg.merchant = null; player.sendMessage("npcx : Updated NPCs cached merchant (0)"); count++; } } } player.sendMessage("Updated "+count+" entries."); } } if (args[1].equals("triggerword")) { if (args.length < 6) { player.sendMessage("Insufficient arguments /npcx npc triggerword add npcid triggerword response"); } else { String reply = ""; int current = 6; while (current <= args.length) { reply = reply + args[current-1]+" "; current++; } reply = reply.substring(0,reply.length()-1); PreparedStatement statementTword = this.universe.conn.prepareStatement("INSERT INTO npc_triggerwords (npcid,triggerword,reply) VALUES (?,?,?)",Statement.RETURN_GENERATED_KEYS); statementTword.setString(1,args[3]); statementTword.setString(2,args[4]); statementTword.setString(3,reply); statementTword.executeUpdate(); ResultSet keyset = statementTword.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } player.sendMessage("Added ("+universe.npcs.values().size()+") triggerword ["+key+"] to npc "+args[3]); // add it to any spawned npcs for (myNPC npc : universe.npcs.values()) { dbg(1,"my id="+npc.id.toString()); if (npc.id.equals(args[3])) { dbg(1,"npcx : adding reply because ("+ npc.id +") is ("+args[3]+") ("+ reply + ") and trigger ("+ reply +") for [" + args[3] + "] npc to npc: " + npc.id); myTriggerword tw = new myTriggerword(); tw.word = args[4]; tw.id = key; tw.response = reply; player.sendMessage("Added triggerword to Active npc "+args[3]); npc.triggerwords.put(Integer.toString(tw.id), tw); } } } } if (args[1].equals("chest")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc chest npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET chest = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.chest = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.chest); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setChestplate(i); player.sendMessage("npcx : Updated living npc to cached chest ("+args[3]+"): "+n.chest); stmt.executeUpdate(); } } player.sendMessage("Updated npc chest: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("helmet")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc helmet npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET helmet = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.helmet = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.helmet); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setHelmet(i); player.sendMessage("npcx : Updated living npc to cached helmet ("+args[3]+"): "+n.helmet); stmt.executeUpdate(); } } player.sendMessage("Updated npc helmet: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("weapon")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc weapon npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET weapon = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.weapon = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.weapon); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setItemInHand(i); player.sendMessage("npcx : Updated living npc to cached weapon ("+args[3]+"): "+n.weapon); stmt.executeUpdate(); } } player.sendMessage("Updated npc weapon: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("boots")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc boots npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET boots = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.boots = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.boots); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setBoots(i); player.sendMessage("npcx : Updated living npc to cached boots ("+args[3]+"): "+n.boots); stmt.executeUpdate(); } } player.sendMessage("Updated npc boots: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("legs")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc legs npcid itemid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET legs = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); //TODO not in schema yet //stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.legs = Integer.parseInt(args[3]); ItemStack i = new ItemStack(n.legs); i.setTypeId(Integer.parseInt(args[3])); n.npc.getBukkitEntity().getInventory().setLeggings(i); player.sendMessage("npcx : Updated living npc to cached legs ("+args[3]+"): "+n.legs); stmt.executeUpdate(); } } player.sendMessage("Updated npc legs: item ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("faction")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc faction npcid factionid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET faction_id = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.faction = getFactionByID(Integer.parseInt(args[3])); player.sendMessage("npcx : Updated living npc to cached faction ("+args[3]+"): "+n.faction.name); // when faction changes reset aggro and follow status n.npc.aggro = null; n.npc.follow = null; } } player.sendMessage("Updated npc faction ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("category")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc category npcid category"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET category = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.category = args[3]; player.sendMessage("npcx : Updated living npc to cached category ("+args[3]+"): "+n.category); // when faction changes reset aggro and follow status } } player.sendMessage("Updated npc category :" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("list")) { player.sendMessage("Npcs:"); PreparedStatement sglist; if (args.length < 3) { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM npc ORDER BY ID DESC LIMIT 10"); } else { sglist = this.universe.conn.prepareStatement("SELECT id, name, category FROM npc WHERE name LIKE '%"+args[2]+"%'"); } sglist.executeQuery (); ResultSet rs = sglist.getResultSet (); int count = 0; while (rs.next ()) { int idVal = rs.getInt ("id"); String nameVal = rs.getString ("name"); String catVal = rs.getString ("category"); player.sendMessage( "id = " + idVal + ", name = " + nameVal + ", category = " + catVal); ++count; } rs.close (); sglist.close (); player.sendMessage (count + " rows were retrieved"); } if (args[1].equals("loottable")) { if (args.length < 4) { player.sendMessage("Insufficient arguments /npcx npc loottable npcid loottableid"); } else { PreparedStatement stmt = this.universe.conn.prepareStatement("UPDATE npc SET loottable_id = ? WHERE id = ?;"); stmt.setString(1, args[3]); stmt.setString(2, args[2]); stmt.executeUpdate(); for(myNPC n : universe.npcs.values()) { if (n.id.matches(args[2])) { n.loottable = getLoottableByID(Integer.parseInt(args[3])); player.sendMessage("npcx : Updated living npc to cached loottable ("+args[3]+"): "+n.loottable.name); } } player.sendMessage("Updated npc loottable ID:" + args[3] + " on NPC ID:[" + args[2] + "]"); stmt.close(); } } if (args[1].equals("create")) { if (args.length < 3) { player.sendMessage("Insufficient arguments /npcx npc create npcname"); } else { Statement s2 = this.universe.conn.createStatement (); PreparedStatement stmt = this.universe.conn.prepareStatement("INSERT INTO npc (name,weapon,helmet,chest,legs,boots) VALUES (?,'267','0','307','308','309');",Statement.RETURN_GENERATED_KEYS); stmt.setString(1, args[2]); stmt.executeUpdate(); ResultSet keyset = stmt.getGeneratedKeys(); int key = 0; if ( keyset.next() ) { // Retrieve the auto generated key(s). key = keyset.getInt(1); } player.sendMessage("Created npc: " + args[2] + " ID:[" + key + "]"); s2.close(); } } /* * Disabled temporarily * if (args[1].equals("spawn")) { player.sendMessage("Spawning new (temporary) NPC: " + args[2]); // temporary Location loc = new Location(player.getWorld(),player.getLocation().getX(),player.getLocation().getY(),player.getLocation().getZ(),player.getLocation().getYaw(),player.getLocation().getPitch()); myNPC npc = new myNPC(this, null, loc, args[2]); npc.Spawn(args[2],loc); this.universe.npcs.put("ZZSpawns"+"-"+npc.id,npc); this.npclist.put(args[2], npc.npc); return true; } */ } } catch (Exception e) { sender.sendMessage("An error occured."); logger.log(Level.WARNING, "npcx: error: " + e.getMessage() + e.getStackTrace().toString()); e.printStackTrace(); return true; } return true; }
diff --git a/atlassian-jira-rest-java-client/src/test/java/it/JerseySearchRestClientTest.java b/atlassian-jira-rest-java-client/src/test/java/it/JerseySearchRestClientTest.java index aba3b34..0684be8 100644 --- a/atlassian-jira-rest-java-client/src/test/java/it/JerseySearchRestClientTest.java +++ b/atlassian-jira-rest-java-client/src/test/java/it/JerseySearchRestClientTest.java @@ -1,116 +1,121 @@ /* * Copyright (C) 2011 Atlassian * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it; import com.atlassian.jira.rest.client.IntegrationTestUtil; import com.atlassian.jira.rest.client.TestUtil; import com.atlassian.jira.rest.client.domain.SearchResult; import com.atlassian.jira.rest.client.internal.ServerVersionConstants; import com.google.common.collect.Iterables; import org.junit.Test; import javax.ws.rs.core.Response; public class JerseySearchRestClientTest extends AbstractRestoringJiraStateJerseyRestClientTest { @Test public void testJqlSearch() { if (!isJqlSupportedByRest()) { return; } final SearchResult searchResultForNull = client.getSearchClient().searchJql(null, pm); assertEquals(9, searchResultForNull.getTotal()); final SearchResult searchResultForReporterWseliga = client.getSearchClient().searchJql("reporter=wseliga", pm); assertEquals(1, searchResultForReporterWseliga.getTotal()); setAnonymousMode(); final SearchResult searchResultAsAnonymous = client.getSearchClient().searchJql(null, pm); assertEquals(1, searchResultAsAnonymous.getTotal()); final SearchResult searchResultForReporterWseligaAsAnonymous = client.getSearchClient().searchJql("reporter=wseliga", pm); assertEquals(0, searchResultForReporterWseligaAsAnonymous.getTotal()); } @Test public void testJqlSearchWithPaging() { if (!isJqlSupportedByRest()) { return; } final SearchResult searchResultForNull = client.getSearchClient().searchJql(null, 3, 3, pm); assertEquals(9, searchResultForNull.getTotal()); assertEquals(3, Iterables.size(searchResultForNull.getIssues())); assertEquals(3, searchResultForNull.getStartIndex()); assertEquals(3, searchResultForNull.getMaxResults()); // seems pagination works differently between 4.4 and 5.0 // check the rationale https://jdog.atlassian.com/browse/JRADEV-8889 final SearchResult search2 = client.getSearchClient().searchJql("assignee is not EMPTY", 2, 1, pm); assertEquals(9, search2.getTotal()); assertEquals(2, Iterables.size(search2.getIssues())); - assertEquals("TST-6", Iterables.get(search2.getIssues(), 0).getKey()); - assertEquals("TST-5", Iterables.get(search2.getIssues(), 1).getKey()); + if (IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER) { + assertEquals("TST-6", Iterables.get(search2.getIssues(), 0).getKey()); + assertEquals("TST-5", Iterables.get(search2.getIssues(), 1).getKey()); + } else { + assertEquals("TST-7", Iterables.get(search2.getIssues(), 0).getKey()); + assertEquals("TST-6", Iterables.get(search2.getIssues(), 1).getKey()); + } assertEquals(IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? 1 : 0, search2.getStartIndex()); assertEquals(2, search2.getMaxResults()); setUser1(); final SearchResult search3 = client.getSearchClient().searchJql("assignee is not EMPTY", 10, 5, pm); assertEquals(8, search3.getTotal()); assertEquals(IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? 3 : 8, Iterables.size(search3.getIssues())); assertEquals(IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? 5 : 0, search3.getStartIndex()); assertEquals(10, search3.getMaxResults()); } @Test public void testVeryLongJqlWhichWillBePost() { if (!isJqlSupportedByRest()) { return; } final String coreJql = "summary ~ fsdsfdfds"; StringBuilder sb = new StringBuilder(coreJql); for (int i = 0; i < 500; i++) { sb.append(" and (reporter is not empty)"); // building very long JQL query } sb.append(" or summary is not empty"); // so that effectively all issues are returned; final SearchResult searchResultForNull = client.getSearchClient().searchJql(sb.toString(), 3, 6, pm); assertEquals(9, searchResultForNull.getTotal()); assertEquals(3, Iterables.size(searchResultForNull.getIssues())); assertEquals(6, searchResultForNull.getStartIndex()); assertEquals(3, searchResultForNull.getMaxResults()); } @Test public void testJqlSearchUnescapedCharacter() { if (!isJqlSupportedByRest()) { return; } TestUtil.assertErrorCode(Response.Status.BAD_REQUEST, "Error in the JQL Query: The character '/' is a reserved JQL character. You must enclose it in a string or use the escape '\\u002f' instead. (line 1, character 11)", new Runnable() { @Override public void run() { client.getSearchClient().searchJql("reporter=a/user/with/slash", pm); } }); } private boolean isJqlSupportedByRest() { return client.getMetadataClient().getServerInfo(pm).getBuildNumber() >= ServerVersionConstants.BN_JIRA_4_3; } }
true
true
public void testJqlSearchWithPaging() { if (!isJqlSupportedByRest()) { return; } final SearchResult searchResultForNull = client.getSearchClient().searchJql(null, 3, 3, pm); assertEquals(9, searchResultForNull.getTotal()); assertEquals(3, Iterables.size(searchResultForNull.getIssues())); assertEquals(3, searchResultForNull.getStartIndex()); assertEquals(3, searchResultForNull.getMaxResults()); // seems pagination works differently between 4.4 and 5.0 // check the rationale https://jdog.atlassian.com/browse/JRADEV-8889 final SearchResult search2 = client.getSearchClient().searchJql("assignee is not EMPTY", 2, 1, pm); assertEquals(9, search2.getTotal()); assertEquals(2, Iterables.size(search2.getIssues())); assertEquals("TST-6", Iterables.get(search2.getIssues(), 0).getKey()); assertEquals("TST-5", Iterables.get(search2.getIssues(), 1).getKey()); assertEquals(IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? 1 : 0, search2.getStartIndex()); assertEquals(2, search2.getMaxResults()); setUser1(); final SearchResult search3 = client.getSearchClient().searchJql("assignee is not EMPTY", 10, 5, pm); assertEquals(8, search3.getTotal()); assertEquals(IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? 3 : 8, Iterables.size(search3.getIssues())); assertEquals(IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? 5 : 0, search3.getStartIndex()); assertEquals(10, search3.getMaxResults()); }
public void testJqlSearchWithPaging() { if (!isJqlSupportedByRest()) { return; } final SearchResult searchResultForNull = client.getSearchClient().searchJql(null, 3, 3, pm); assertEquals(9, searchResultForNull.getTotal()); assertEquals(3, Iterables.size(searchResultForNull.getIssues())); assertEquals(3, searchResultForNull.getStartIndex()); assertEquals(3, searchResultForNull.getMaxResults()); // seems pagination works differently between 4.4 and 5.0 // check the rationale https://jdog.atlassian.com/browse/JRADEV-8889 final SearchResult search2 = client.getSearchClient().searchJql("assignee is not EMPTY", 2, 1, pm); assertEquals(9, search2.getTotal()); assertEquals(2, Iterables.size(search2.getIssues())); if (IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER) { assertEquals("TST-6", Iterables.get(search2.getIssues(), 0).getKey()); assertEquals("TST-5", Iterables.get(search2.getIssues(), 1).getKey()); } else { assertEquals("TST-7", Iterables.get(search2.getIssues(), 0).getKey()); assertEquals("TST-6", Iterables.get(search2.getIssues(), 1).getKey()); } assertEquals(IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? 1 : 0, search2.getStartIndex()); assertEquals(2, search2.getMaxResults()); setUser1(); final SearchResult search3 = client.getSearchClient().searchJql("assignee is not EMPTY", 10, 5, pm); assertEquals(8, search3.getTotal()); assertEquals(IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? 3 : 8, Iterables.size(search3.getIssues())); assertEquals(IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? 5 : 0, search3.getStartIndex()); assertEquals(10, search3.getMaxResults()); }
diff --git a/grisu-swing/src/main/java/org/vpac/grisu/client/view/swing/mainPanel/Grisu.java b/grisu-swing/src/main/java/org/vpac/grisu/client/view/swing/mainPanel/Grisu.java index 98f087b..4be1d93 100644 --- a/grisu-swing/src/main/java/org/vpac/grisu/client/view/swing/mainPanel/Grisu.java +++ b/grisu-swing/src/main/java/org/vpac/grisu/client/view/swing/mainPanel/Grisu.java @@ -1,789 +1,789 @@ package org.vpac.grisu.client.view.swing.mainPanel; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.Arrays; import java.util.Date; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; 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.apache.log4j.Level; import org.apache.log4j.Logger; import org.vpac.grisu.client.control.EnvironmentManager; import org.vpac.grisu.client.control.files.FileManagerDeleteHelpers; import org.vpac.grisu.client.control.files.FileManagerTransferHelpers; import org.vpac.grisu.client.control.status.ApplicationStatusManager; import org.vpac.grisu.client.control.utils.progress.ProgressDisplay; import org.vpac.grisu.client.control.utils.progress.swing.SwingProgressDisplay; import org.vpac.grisu.client.view.swing.fileTransfers.FileTransferPanel; import org.vpac.grisu.client.view.swing.filemanager.GrisuFilePanel; import org.vpac.grisu.client.view.swing.jobs.GlazedJobMonitorPanel; import org.vpac.grisu.client.view.swing.login.LoginDialog; import org.vpac.grisu.client.view.swing.login.LoginSplashScreen; import org.vpac.grisu.client.view.swing.mountpoints.MountPointsManagementDialog; import org.vpac.grisu.client.view.swing.template.SubmissionPanel; import org.vpac.grisu.client.view.swing.utils.Utils; import org.vpac.grisu.control.ServiceInterface; import org.vpac.grisu.model.GrisuRegistry; import org.vpac.grisu.model.GrisuRegistryManager; import org.vpac.grisu.settings.ClientPropertiesManager; import org.vpac.grisu.settings.Environment; import org.vpac.grisu.utils.GrisuPluginFilenameFilter; import org.vpac.helpDesk.control.HelpDeskManager; import org.vpac.helpDesk.model.HelpDesk; import org.vpac.helpDesk.model.HelpDeskNotAvailableException; import org.vpac.helpDesk.view.TicketSubmissionDialogMultipleHelpdesks; import org.vpac.security.light.control.CertificateFiles; import au.org.arcs.auth.shibboleth.Shibboleth; import au.org.arcs.jcommons.dependencies.ClasspathHacker; public class Grisu implements WindowListener { static final Logger myLogger = Logger.getLogger(Grisu.class.getName()); public static final String apache2License = "http://www.apache.org/licenses/LICENSE-2.0"; public static final String GRISU_VERSION = "v0.3-SNAPSHOT"; /** * Launches this application */ public static void main(String[] args) { Shibboleth.initDefaultSecurityProvider(); if ((args.length > 0) && (Arrays.binarySearch(args, "--debug") >= 0)) { Level lvl = Level.toLevel("debug"); Logger.getRootLogger().setLevel(lvl); } SwingUtilities.invokeLater(new Runnable() { public void run() { final Grisu application = new Grisu(); Toolkit tk = Toolkit.getDefaultToolkit(); tk.addAWTEventListener(WindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK); try { UIManager.setLookAndFeel(UIManager .getSystemLookAndFeelClassName()); } catch (Exception e) { myLogger.debug("Could not set OS look & feel."); } try { - CertificateFiles.copyCACerts(); + CertificateFiles.copyCACerts(true); } catch (Exception e1) { // TODO Auto-generated catch block // e1.printStackTrace(); } myLogger.debug("Starting login dialog."); LoginDialog ld = new LoginDialog(); ld.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); ld.setVisible(true); if (ld.userCancelledLogin()) { myLogger.debug("User cancelled login dialog."); System.exit(0); } application.serviceInterface = ld.getServiceInterface(); myLogger.debug("Removing login dialog."); ld.dispose(); myLogger.debug("Creating splash screen."); final LoginSplashScreen lss = new LoginSplashScreen(); lss.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); ApplicationStatusManager.getDefaultManager().addStatusListener( lss); lss.setVisible(true); new Thread() { @Override public void run() { myLogger.debug("Creating progress bars."); try { application.em = new EnvironmentManager( application.serviceInterface); // GrisuRegistry defaultRegistry; // try { // // throw new RuntimeException(); // defaultRegistry = new // ClientSideGrisuRegistry(application.serviceInterface); // myLogger.info("Using client side mds library."); // } catch (Exception e) { // myLogger.info("Couldn't use client side mds library: "+e.getLocalizedMessage()); // myLogger.info("Using grisu service interface to calculate mds information..."); // defaultRegistry = new // GrisuRegistryImpl(application.serviceInterface); // } // // GrisuRegistryManager.setDefault(application.serviceInterface, // defaultRegistry); GrisuRegistry temp = GrisuRegistryManager .getDefault(application.serviceInterface); temp.setUserEnvironmentManager(application.em); application.em.initializeHistoryManager(); if (application.serviceInterface == null) { myLogger .debug("Could not create/find service interface. Exiting."); Utils.showErrorMessage(application.em, null, "startupError", null); System.exit(1); } } catch (Exception e) { // TODO Auto-generated catch block Utils.showErrorMessage(application.em, null, "startupError", e); e.printStackTrace(); System.exit(1); } // application.em.getFileManager().initAllFileSystemsInBackground(); // application.em.buildInfoCacheInBackground(); // application.em.getGlazedJobManagement().loadAllJobsInBackground(); // ProgressDisplay pg_environment = new // SwingProgressDisplay(application.getJFrame()); // ProgressDisplay pg_submission = new // SwingProgressDisplay(application.getJFrame()); ProgressDisplay pg_file_managementTransfer = new SwingProgressDisplay( application.getJFrame()); ProgressDisplay pg_file_deletion = new SwingProgressDisplay( application.getJFrame()); // EnvironmentManager.progressDisplay = pg_environment; FileManagerTransferHelpers.progressDisplay = pg_file_managementTransfer; FileManagerDeleteHelpers.progressDisplay = pg_file_deletion; myLogger.debug("Setting application window visible."); application.getJFrame().setVisible(true); Thread .setDefaultUncaughtExceptionHandler(new GrisuRuntimeExceptionHandler( application.getJFrame())); ApplicationStatusManager.getDefaultManager() .removeStatusListener(lss); myLogger.debug("Removing splash screen."); lss.dispose(); // now test whether there is a VO available int availFqans = application.em.getAvailableFqans().length; myLogger.debug("Number of avail Fqans: " + availFqans); int usedFqans = application.em.getAllUsedFqans().size(); myLogger.debug("Number of used Fqans: " + usedFqans); if (availFqans == 0) { Utils.showErrorMessage(application.em, application .getJFrame(), "noVOs", null); } else if (usedFqans == 0) { Utils.showErrorMessage(application.em, application .getJFrame(), "noUsableVOs", null); } } }.start(); } }); } private JFrame jFrame = null; // @jve:decl-index=0:visual-constraint="10,10" private JPanel jContentPane = null; private JMenuBar jJMenuBar = null; private JMenu fileMenu = null; private JMenu toolsMenu = null; private JMenu helpMenu = null; private JMenuItem exitMenuItem = null; private JMenuItem addLocalTemplateItem = null; private JMenuItem aboutMenuItem = null; private JMenuItem requestHelpMenuItem = null; private JMenuItem proxyEndTimeMenuItem = null; private JMenuItem mountsMenuItem = null; private JDialog aboutDialog = null; // @jve:decl-index=0:visual-constraint="739,169" private MountPointsManagementDialog mountsDialog = null; private JPanel aboutContentPane = null; private JLabel aboutVersionLabel = null; private ServiceInterface serviceInterface = null; // private JPanel jobSubmissionPanel = null; private EnvironmentManager em = null; private SubmissionPanel submissionPanel = null; private GlazedJobMonitorPanel jobMonitorPanel = null; private FileTransferPanel fileTransferPanel = null; private JTabbedPane jTabbedPane = null; public Grisu() { addPluginsToClasspath(); } private void addPluginsToClasspath() { ClasspathHacker.initFolder(Environment.getGrisuPluginDirectory(), new GrisuPluginFilenameFilter()); } private void exit() { try { serviceInterface.logout(); } catch (Exception e) { e.printStackTrace(); } finally { WindowSaver.saveSettings(); System.exit(0); } } /** * This method initializes aboutContentPane * * @return javax.swing.JPanel */ private JPanel getAboutContentPane() { if (aboutContentPane == null) { aboutContentPane = new JPanel(); aboutContentPane.setLayout(new BorderLayout()); aboutContentPane.add(getAboutVersionLabel(), BorderLayout.CENTER); } return aboutContentPane; } /** * This method initializes aboutDialog * * @return javax.swing.JDialog */ private JDialog getAboutDialog() { if (aboutDialog == null) { // List<String> contributors = new LinkedList<String>(); // contributors.add("Markus Binsteiner"); // // URL picURL = // getClass().getResource("/images/ARCS_LogoTag_even_smaller.jpg"); // ImageIcon grisu = new ImageIcon(picURL); // // ProjectInfo info = new ProjectInfo("Grisu", GRISU_VERSION, // "The Grisu Swing client.", // grisu.getImage(), "ARCS", "Apache2", apache2License); // aboutDialog = new AboutDialog(getJFrame(), "Grisu", info); aboutDialog = new GrisuAboutDialog(); } return aboutDialog; } /** * This method initializes jMenuItem * * @return javax.swing.JMenuItem */ private JMenuItem getAboutMenuItem() { if (aboutMenuItem == null) { aboutMenuItem = new JMenuItem(); aboutMenuItem.setText("About"); aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JDialog aboutDialog = getAboutDialog(); aboutDialog.pack(); Point loc = getJFrame().getLocation(); loc.translate(20, 20); aboutDialog.setLocation(loc); aboutDialog.setVisible(true); } }); } return aboutMenuItem; } /** * This method initializes aboutVersionLabel * * @return javax.swing.JLabel */ private JLabel getAboutVersionLabel() { if (aboutVersionLabel == null) { aboutVersionLabel = new JLabel(); aboutVersionLabel.setText(GRISU_VERSION); aboutVersionLabel.setHorizontalAlignment(SwingConstants.CENTER); } return aboutVersionLabel; } /** * This method initializes jMenuItem * * @return javax.swing.JMenuItem */ private JMenuItem getAddLocalMenuItem() { if (addLocalTemplateItem == null) { addLocalTemplateItem = new JMenuItem(); addLocalTemplateItem .setText("Add template to local template store"); addLocalTemplateItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getSubmissionPanel().addLocalTemplate(); } }); } return addLocalTemplateItem; } /** * This method initializes jMenuItem * * @return javax.swing.JMenuItem */ private JMenuItem getExitMenuItem() { if (exitMenuItem == null) { exitMenuItem = new JMenuItem(); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exit(); } }); } return exitMenuItem; } /** * This method initializes jMenu * * @return javax.swing.JMenu */ private JMenu getFileMenu() { if (fileMenu == null) { fileMenu = new JMenu(); fileMenu.setText("File"); fileMenu.add(getAddLocalMenuItem()); fileMenu.add(getExitMenuItem()); } return fileMenu; } private FileTransferPanel getFileTransferPanel() { if (fileTransferPanel == null) { fileTransferPanel = new FileTransferPanel(); fileTransferPanel.initialize(em.getFileTransferManager()); } return fileTransferPanel; } /** * This method initializes jMenu * * @return javax.swing.JMenu */ private JMenu getHelpMenu() { if (helpMenu == null) { helpMenu = new JMenu(); helpMenu.setText("Help"); helpMenu.add(getRequestSupportMenuItem()); helpMenu.add(getProxyEndTimeMenuItem()); helpMenu.add(getAboutMenuItem()); } return helpMenu; } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { jContentPane = new JPanel(); jContentPane.setLayout(new BorderLayout()); try { jContentPane.add(getJTabbedPane(), BorderLayout.CENTER); } catch (RuntimeException e) { // something's gone wrong with something. Exiting... e.printStackTrace(); Utils.showErrorMessage(jFrame, em.getUser(), "severeError", Utils.getStackTrace(e), e); System.exit(1); } } return jContentPane; } /** * This method initializes jFrame * * @return javax.swing.JFrame */ private JFrame getJFrame() { if (jFrame == null) { jFrame = new JFrame(); jFrame.setName("GrisuMainWindow"); jFrame.setSize(740, 640); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.setJMenuBar(getJJMenuBar()); jFrame.setContentPane(getJContentPane()); jFrame.setTitle("Grisu client"); jFrame.setLocationByPlatform(true); jFrame.addWindowListener(this); } return jFrame; } // private JDialog getMountsDialog() { // if (mountsDialog == null) { // mountsDialog = new MountsDialog(em, this.getJFrame()); // } // return mountsDialog; // } /** * This method initializes jJMenuBar * * @return javax.swing.JMenuBar */ private JMenuBar getJJMenuBar() { if (jJMenuBar == null) { jJMenuBar = new JMenuBar(); jJMenuBar.add(getFileMenu()); jJMenuBar.add(getToolsMenu()); jJMenuBar.add(getHelpMenu()); } return jJMenuBar; } private GlazedJobMonitorPanel getJobMonitorPanel() { if (jobMonitorPanel == null) { // jobMonitorPanel = new JobMonitorPanel(em); jobMonitorPanel = new GlazedJobMonitorPanel(em); } return jobMonitorPanel; } /** * This method initializes jTabbedPane * * @return javax.swing.JTabbedPane */ private JTabbedPane getJTabbedPane() { if (jTabbedPane == null) { jTabbedPane = new JTabbedPane(); jTabbedPane.addTab("Job submission", getSubmissionPanel()); jTabbedPane.addTab("Monitoring", getJobMonitorPanel()); // jTabbedPane.addTab("File Management", new // GrisuFileCommanderPanel()); jTabbedPane.addTab("File management", new GrisuFilePanel(em)); jTabbedPane.addTab("File transfers", getFileTransferPanel()); } return jTabbedPane; } // /** // * This method initializes jobPreparationPanel // * // * @return javax.swing.JPanel // */ // private JPanel getJobPreparationPanel() { // if (jobPreparationPanel == null) { // jobPreparationPanel = new JobPreparationPanel(new // InputFile("/home/markus/workspace/nw-core/simpleTemplateJob.xml"), // serviceInterface); // } // return jobPreparationPanel; // } // private JPanel getJobSubmissionPanel() { // if (jobSubmissionPanel == null) { // jobSubmissionPanel = new JobSubmissionPanel(serviceInterface); // } // return jobSubmissionPanel; // } private JDialog getMountPointsManagementDialog() { if (mountsDialog == null) { mountsDialog = new MountPointsManagementDialog(); mountsDialog.initialize(em); } return mountsDialog; } /** * This method initializes jMenuItem * * @return javax.swing.JMenuItem */ private JMenuItem getMountsMenuItem() { if (mountsMenuItem == null) { mountsMenuItem = new JMenuItem(); mountsMenuItem.setText("Fileshares"); mountsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // JDialog mountsDialog = getMountsDialog(); getMountPointsManagementDialog().pack(); Point loc = getJFrame().getLocation(); loc.translate(20, 20); getMountPointsManagementDialog().setLocation(loc); getMountPointsManagementDialog().setVisible(true); } }); } return mountsMenuItem; } private JMenuItem getProxyEndTimeMenuItem() { if (proxyEndTimeMenuItem == null) { proxyEndTimeMenuItem = new JMenuItem(); proxyEndTimeMenuItem.setText("Proxy time left"); proxyEndTimeMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Thread() { @Override public void run() { JOptionPane.showMessageDialog(null, "Proxy endtime: " + new Date(serviceInterface .getCredentialEndTime()), "Proxy endtime", JOptionPane.INFORMATION_MESSAGE); } }.start(); } }); } return proxyEndTimeMenuItem; } /** * This method initializes jMenuItem * * @return javax.swing.JMenuItem */ private JMenuItem getRequestSupportMenuItem() { if (requestHelpMenuItem == null) { requestHelpMenuItem = new JMenuItem(); requestHelpMenuItem.setText("Request support"); requestHelpMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Runnable() { public void run() { HelpDesk[] helpDesks = new HelpDesk[ClientPropertiesManager .getDefaultHelpDesks().length]; Configuration config = null; try { try { config = new PropertiesConfiguration( ClientPropertiesManager .getHelpDeskConfig()); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new HelpDeskNotAvailableException( "Could not init helpdesks because of misconfiguration."); } for (int i = 0; i < ClientPropertiesManager .getDefaultHelpDesks().length; i++) { String helpDeskClass = ClientPropertiesManager .getDefaultHelpDesks()[i]; HelpDesk hd = HelpDeskManager .createHelpDesk(helpDeskClass, config); if (hd != null) { helpDesks[i] = hd; } else { throw new HelpDeskNotAvailableException( "Could not create helpdesk for class: " + helpDeskClass); } } } catch (HelpDeskNotAvailableException hdnae) { JOptionPane.showMessageDialog(null, "Could not create help desk dialog:\n" + hdnae.getLocalizedMessage(), "Connection error", JOptionPane.ERROR_MESSAGE); } TicketSubmissionDialogMultipleHelpdesks tsd = new TicketSubmissionDialogMultipleHelpdesks(); tsd.initialize(helpDesks, null, "Generic help request", "[Please insert your support request]", null); tsd.setVisible(true); // Configuration config = null; // try { // config = new // PropertiesConfiguration("support.properties"); // } catch (ConfigurationException e) { // myLogger.error("Could not initialize irc helpdesk: "+e.getLocalizedMessage()); // JOptionPane.showMessageDialog(null, // "Could not connect to irc help desk: "+e.getLocalizedMessage(), // "Connection error", // JOptionPane.ERROR_MESSAGE); // } // // // Utils.showErrorMessage(em, getJFrame(), // "genericRequest", null); // HelpDesk hd = // HelpDeskManager.createHelpDesk("org.vpac.helpDesk.model.irc.IrcHelpDesk", // config); // // try { // hd.initiate(EnvironmentManager.getDefaultManager().getUser()); // hd.submitTicket("Grisu", // "General Grisu support request.", new // Object[]{}); // } catch (HelpDeskNotAvailableException e) { // myLogger.error("Could not connect to irc support."); // JOptionPane.showMessageDialog(null, // "Could not connect to irc help desk: "+e.getLocalizedMessage(), // "Connection error", // JOptionPane.ERROR_MESSAGE); // } } }.run(); // JDialog supportDialog = getRequestSupportDialog(); // supportDialog.pack(); // Point loc = getJFrame().getLocation(); // loc.translate(20, 20); // supportDialog.setLocation(loc); // supportDialog.setVisible(true); } }); } return requestHelpMenuItem; } private SubmissionPanel getSubmissionPanel() { if (submissionPanel == null) { submissionPanel = new SubmissionPanel(em); submissionPanel.setTemplateManager(em.getTemplateManager()); String application = System.getProperty("grisu.defaultApplication"); if ( StringUtils.isNotBlank(application) ) { submissionPanel.setRemoteApplication(application); } } return submissionPanel; } /** * This method initializes jMenu * * @return javax.swing.JMenu */ private JMenu getToolsMenu() { if (toolsMenu == null) { toolsMenu = new JMenu(); toolsMenu.setText("Settings"); // toolsMenu.add(getCutMenuItem()); // toolsMenu.add(getCopyMenuItem()); // toolsMenu.add(getPasteMenuItem()); toolsMenu.add(getMountsMenuItem()); } return toolsMenu; } public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { exit(); } public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } }
true
true
public static void main(String[] args) { Shibboleth.initDefaultSecurityProvider(); if ((args.length > 0) && (Arrays.binarySearch(args, "--debug") >= 0)) { Level lvl = Level.toLevel("debug"); Logger.getRootLogger().setLevel(lvl); } SwingUtilities.invokeLater(new Runnable() { public void run() { final Grisu application = new Grisu(); Toolkit tk = Toolkit.getDefaultToolkit(); tk.addAWTEventListener(WindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK); try { UIManager.setLookAndFeel(UIManager .getSystemLookAndFeelClassName()); } catch (Exception e) { myLogger.debug("Could not set OS look & feel."); } try { CertificateFiles.copyCACerts(); } catch (Exception e1) { // TODO Auto-generated catch block // e1.printStackTrace(); } myLogger.debug("Starting login dialog."); LoginDialog ld = new LoginDialog(); ld.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); ld.setVisible(true); if (ld.userCancelledLogin()) { myLogger.debug("User cancelled login dialog."); System.exit(0); } application.serviceInterface = ld.getServiceInterface(); myLogger.debug("Removing login dialog."); ld.dispose(); myLogger.debug("Creating splash screen."); final LoginSplashScreen lss = new LoginSplashScreen(); lss.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); ApplicationStatusManager.getDefaultManager().addStatusListener( lss); lss.setVisible(true); new Thread() { @Override public void run() { myLogger.debug("Creating progress bars."); try { application.em = new EnvironmentManager( application.serviceInterface); // GrisuRegistry defaultRegistry; // try { // // throw new RuntimeException(); // defaultRegistry = new // ClientSideGrisuRegistry(application.serviceInterface); // myLogger.info("Using client side mds library."); // } catch (Exception e) { // myLogger.info("Couldn't use client side mds library: "+e.getLocalizedMessage()); // myLogger.info("Using grisu service interface to calculate mds information..."); // defaultRegistry = new // GrisuRegistryImpl(application.serviceInterface); // } // // GrisuRegistryManager.setDefault(application.serviceInterface, // defaultRegistry); GrisuRegistry temp = GrisuRegistryManager .getDefault(application.serviceInterface); temp.setUserEnvironmentManager(application.em); application.em.initializeHistoryManager(); if (application.serviceInterface == null) { myLogger .debug("Could not create/find service interface. Exiting."); Utils.showErrorMessage(application.em, null, "startupError", null); System.exit(1); } } catch (Exception e) { // TODO Auto-generated catch block Utils.showErrorMessage(application.em, null, "startupError", e); e.printStackTrace(); System.exit(1); } // application.em.getFileManager().initAllFileSystemsInBackground(); // application.em.buildInfoCacheInBackground(); // application.em.getGlazedJobManagement().loadAllJobsInBackground(); // ProgressDisplay pg_environment = new // SwingProgressDisplay(application.getJFrame()); // ProgressDisplay pg_submission = new // SwingProgressDisplay(application.getJFrame()); ProgressDisplay pg_file_managementTransfer = new SwingProgressDisplay( application.getJFrame()); ProgressDisplay pg_file_deletion = new SwingProgressDisplay( application.getJFrame()); // EnvironmentManager.progressDisplay = pg_environment; FileManagerTransferHelpers.progressDisplay = pg_file_managementTransfer; FileManagerDeleteHelpers.progressDisplay = pg_file_deletion; myLogger.debug("Setting application window visible."); application.getJFrame().setVisible(true); Thread .setDefaultUncaughtExceptionHandler(new GrisuRuntimeExceptionHandler( application.getJFrame())); ApplicationStatusManager.getDefaultManager() .removeStatusListener(lss); myLogger.debug("Removing splash screen."); lss.dispose(); // now test whether there is a VO available int availFqans = application.em.getAvailableFqans().length; myLogger.debug("Number of avail Fqans: " + availFqans); int usedFqans = application.em.getAllUsedFqans().size(); myLogger.debug("Number of used Fqans: " + usedFqans); if (availFqans == 0) { Utils.showErrorMessage(application.em, application .getJFrame(), "noVOs", null); } else if (usedFqans == 0) { Utils.showErrorMessage(application.em, application .getJFrame(), "noUsableVOs", null); } } }.start(); } }); }
public static void main(String[] args) { Shibboleth.initDefaultSecurityProvider(); if ((args.length > 0) && (Arrays.binarySearch(args, "--debug") >= 0)) { Level lvl = Level.toLevel("debug"); Logger.getRootLogger().setLevel(lvl); } SwingUtilities.invokeLater(new Runnable() { public void run() { final Grisu application = new Grisu(); Toolkit tk = Toolkit.getDefaultToolkit(); tk.addAWTEventListener(WindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK); try { UIManager.setLookAndFeel(UIManager .getSystemLookAndFeelClassName()); } catch (Exception e) { myLogger.debug("Could not set OS look & feel."); } try { CertificateFiles.copyCACerts(true); } catch (Exception e1) { // TODO Auto-generated catch block // e1.printStackTrace(); } myLogger.debug("Starting login dialog."); LoginDialog ld = new LoginDialog(); ld.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); ld.setVisible(true); if (ld.userCancelledLogin()) { myLogger.debug("User cancelled login dialog."); System.exit(0); } application.serviceInterface = ld.getServiceInterface(); myLogger.debug("Removing login dialog."); ld.dispose(); myLogger.debug("Creating splash screen."); final LoginSplashScreen lss = new LoginSplashScreen(); lss.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); ApplicationStatusManager.getDefaultManager().addStatusListener( lss); lss.setVisible(true); new Thread() { @Override public void run() { myLogger.debug("Creating progress bars."); try { application.em = new EnvironmentManager( application.serviceInterface); // GrisuRegistry defaultRegistry; // try { // // throw new RuntimeException(); // defaultRegistry = new // ClientSideGrisuRegistry(application.serviceInterface); // myLogger.info("Using client side mds library."); // } catch (Exception e) { // myLogger.info("Couldn't use client side mds library: "+e.getLocalizedMessage()); // myLogger.info("Using grisu service interface to calculate mds information..."); // defaultRegistry = new // GrisuRegistryImpl(application.serviceInterface); // } // // GrisuRegistryManager.setDefault(application.serviceInterface, // defaultRegistry); GrisuRegistry temp = GrisuRegistryManager .getDefault(application.serviceInterface); temp.setUserEnvironmentManager(application.em); application.em.initializeHistoryManager(); if (application.serviceInterface == null) { myLogger .debug("Could not create/find service interface. Exiting."); Utils.showErrorMessage(application.em, null, "startupError", null); System.exit(1); } } catch (Exception e) { // TODO Auto-generated catch block Utils.showErrorMessage(application.em, null, "startupError", e); e.printStackTrace(); System.exit(1); } // application.em.getFileManager().initAllFileSystemsInBackground(); // application.em.buildInfoCacheInBackground(); // application.em.getGlazedJobManagement().loadAllJobsInBackground(); // ProgressDisplay pg_environment = new // SwingProgressDisplay(application.getJFrame()); // ProgressDisplay pg_submission = new // SwingProgressDisplay(application.getJFrame()); ProgressDisplay pg_file_managementTransfer = new SwingProgressDisplay( application.getJFrame()); ProgressDisplay pg_file_deletion = new SwingProgressDisplay( application.getJFrame()); // EnvironmentManager.progressDisplay = pg_environment; FileManagerTransferHelpers.progressDisplay = pg_file_managementTransfer; FileManagerDeleteHelpers.progressDisplay = pg_file_deletion; myLogger.debug("Setting application window visible."); application.getJFrame().setVisible(true); Thread .setDefaultUncaughtExceptionHandler(new GrisuRuntimeExceptionHandler( application.getJFrame())); ApplicationStatusManager.getDefaultManager() .removeStatusListener(lss); myLogger.debug("Removing splash screen."); lss.dispose(); // now test whether there is a VO available int availFqans = application.em.getAvailableFqans().length; myLogger.debug("Number of avail Fqans: " + availFqans); int usedFqans = application.em.getAllUsedFqans().size(); myLogger.debug("Number of used Fqans: " + usedFqans); if (availFqans == 0) { Utils.showErrorMessage(application.em, application .getJFrame(), "noVOs", null); } else if (usedFqans == 0) { Utils.showErrorMessage(application.em, application .getJFrame(), "noUsableVOs", null); } } }.start(); } }); }
diff --git a/src/main/java/org/lastbamboo/common/ice/GeneralIceMediaStreamFactoryImpl.java b/src/main/java/org/lastbamboo/common/ice/GeneralIceMediaStreamFactoryImpl.java index 4a75fbb..bcbcdc4 100644 --- a/src/main/java/org/lastbamboo/common/ice/GeneralIceMediaStreamFactoryImpl.java +++ b/src/main/java/org/lastbamboo/common/ice/GeneralIceMediaStreamFactoryImpl.java @@ -1,204 +1,209 @@ package org.lastbamboo.common.ice; import java.io.IOException; import java.util.Collection; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceListener; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.lastbamboo.common.ice.candidate.IceCandidate; import org.lastbamboo.common.ice.candidate.IceCandidateGatherer; import org.lastbamboo.common.ice.candidate.IceCandidateGathererImpl; import org.lastbamboo.common.ice.candidate.IceCandidatePairFactory; import org.lastbamboo.common.ice.candidate.IceCandidatePairFactoryImpl; import org.lastbamboo.common.ice.transport.IceTcpConnector; import org.lastbamboo.common.ice.transport.IceUdpConnector; import org.lastbamboo.common.stun.client.StunClient; import org.lastbamboo.common.stun.stack.StunDemuxableProtocolCodecFactory; import org.lastbamboo.common.stun.stack.StunIoHandler; import org.lastbamboo.common.stun.stack.message.StunMessage; import org.lastbamboo.common.stun.stack.message.StunMessageVisitorFactory; import org.lastbamboo.common.stun.stack.transaction.StunTransactionTracker; import org.lastbamboo.common.stun.stack.transaction.StunTransactionTrackerImpl; import org.lastbamboo.common.tcp.frame.TcpFrameCodecFactory; import org.lastbamboo.common.turn.client.StunTcpFrameTurnClientListener; import org.lastbamboo.common.turn.client.TcpTurnClient; import org.lastbamboo.common.turn.client.TurnClientListener; import org.lastbamboo.common.turn.client.TurnStunDemuxableProtocolCodecFactory; import org.lastbamboo.common.upnp.UpnpManager; import org.lastbamboo.common.util.mina.DemuxableProtocolCodecFactory; import org.lastbamboo.common.util.mina.DemuxingIoHandler; import org.lastbamboo.common.util.mina.DemuxingProtocolCodecFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Factory for creating media streams. This factory offers a more complex * API intended for specialized ICE implementations of the simpler * {@link IceMediaStreamFactory} interface to use behind the scenes. */ public class GeneralIceMediaStreamFactoryImpl implements GeneralIceMediaStreamFactory { private final Logger m_log = LoggerFactory.getLogger(getClass()); public <T> IceMediaStream newIceMediaStream( final IceMediaStreamDesc streamDesc, final IceAgent iceAgent, final DemuxableProtocolCodecFactory protocolCodecFactory, final Class<T> protocolMessageClass, final IoHandler udpProtocolIoHandler, final TurnClientListener delegateTurnClientListener, final UpnpManager upnpManager, final IoServiceListener udpServiceListener) throws IceTcpConnectException, IceUdpConnectException { final DemuxableProtocolCodecFactory stunCodecFactory = new StunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory demuxingCodecFactory = new DemuxingProtocolCodecFactory( stunCodecFactory, protocolCodecFactory); final StunTransactionTracker<StunMessage> transactionTracker = new StunTransactionTrackerImpl(); final IceStunCheckerFactory checkerFactory = new IceStunCheckerFactoryImpl(transactionTracker); final StunMessageVisitorFactory messageVisitorFactory = new IceStunConnectivityCheckerFactoryImpl<StunMessage>(iceAgent, transactionTracker, checkerFactory); final IoHandler stunIoHandler = new StunIoHandler<StunMessage>(messageVisitorFactory); final IoHandler udpIoHandler = new DemuxingIoHandler<StunMessage, T>( StunMessage.class, stunIoHandler, protocolMessageClass, udpProtocolIoHandler); final StunClient udpStunPeer; if (streamDesc.isUdp()) { try { udpStunPeer = new IceStunUdpPeer(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling(), transactionTracker); } catch (final IOException e) { // Note the constructor of the peer attempts a connection, so // this is named correctly. m_log.warn("Error connecting UDP peer", e); throw new IceUdpConnectException("Could not create UDP peer", e); } udpStunPeer.addIoServiceListener(udpServiceListener); } else { udpStunPeer = null; } // This class just decodes the TCP frames. final IceStunTcpPeer tcpStunPeer; if (streamDesc.isTcp()) { final TurnClientListener turnClientListener = new StunTcpFrameTurnClientListener(messageVisitorFactory, delegateTurnClientListener); final DemuxableProtocolCodecFactory tcpFramingCodecFactory = new TcpFrameCodecFactory(); final TurnStunDemuxableProtocolCodecFactory mapper = new TurnStunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory codecFactory = new DemuxingProtocolCodecFactory(mapper, tcpFramingCodecFactory); // We only start a TURN client on the answerer to save resources -- // handled internally -- see IceStunTcpPeer connect. final StunClient tcpTurnClient = new TcpTurnClient(turnClientListener, codecFactory); tcpStunPeer = new IceStunTcpPeer(tcpTurnClient, messageVisitorFactory, iceAgent.isControlling(), upnpManager); } else { tcpStunPeer = null; } final IceCandidateGatherer gatherer = new IceCandidateGathererImpl(tcpStunPeer, udpStunPeer, iceAgent.isControlling(), streamDesc); final IceMediaStreamImpl stream = new IceMediaStreamImpl(iceAgent, streamDesc, gatherer); if (tcpStunPeer != null) { tcpStunPeer.addIoServiceListener(stream); } if (udpStunPeer != null) { udpStunPeer.addIoServiceListener(stream); } m_log.debug("Added media stream as listener...connecting..."); if (tcpStunPeer != null) { try { tcpStunPeer.connect(); } catch (final IOException e) { m_log.warn("Error connecting TCP peer", e); throw new IceTcpConnectException("Could not create TCP peer", e); } } if (udpStunPeer != null) { try { udpStunPeer.connect(); } catch (final IOException e) { // Note this will not occur because the connect at this // point is effectively a no-op -- the connection takes place // immediately in the constructor. m_log.warn("Error connecting UDP peer", e); + if (tcpStunPeer != null) + { + // We've got to make sure to close TCP too!! + tcpStunPeer.close(); + } throw new IceUdpConnectException("Could not create UDP peer", e); } } final Collection<IceCandidate> localCandidates = gatherer.gatherCandidates(); final IceUdpConnector udpConnector = new IceUdpConnector(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling()); udpConnector.addIoServiceListener(stream); udpConnector.addIoServiceListener(udpServiceListener); final IceTcpConnector tcpConnector = new IceTcpConnector(messageVisitorFactory, iceAgent.isControlling()); tcpConnector.addIoServiceListener(stream); final IceCandidatePairFactory candidatePairFactory = new IceCandidatePairFactoryImpl( checkerFactory, udpConnector, tcpConnector); final IceCheckList checkList = new IceCheckListImpl(candidatePairFactory, localCandidates); final ExistingSessionIceCandidatePairFactory existingSessionPairFactory = new ExistingSessionIceCandidatePairFactoryImpl(checkerFactory); final IceCheckScheduler scheduler = new IceCheckSchedulerImpl(iceAgent, stream, checkList, existingSessionPairFactory); stream.start(checkList, localCandidates, scheduler); return stream; } }
true
true
public <T> IceMediaStream newIceMediaStream( final IceMediaStreamDesc streamDesc, final IceAgent iceAgent, final DemuxableProtocolCodecFactory protocolCodecFactory, final Class<T> protocolMessageClass, final IoHandler udpProtocolIoHandler, final TurnClientListener delegateTurnClientListener, final UpnpManager upnpManager, final IoServiceListener udpServiceListener) throws IceTcpConnectException, IceUdpConnectException { final DemuxableProtocolCodecFactory stunCodecFactory = new StunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory demuxingCodecFactory = new DemuxingProtocolCodecFactory( stunCodecFactory, protocolCodecFactory); final StunTransactionTracker<StunMessage> transactionTracker = new StunTransactionTrackerImpl(); final IceStunCheckerFactory checkerFactory = new IceStunCheckerFactoryImpl(transactionTracker); final StunMessageVisitorFactory messageVisitorFactory = new IceStunConnectivityCheckerFactoryImpl<StunMessage>(iceAgent, transactionTracker, checkerFactory); final IoHandler stunIoHandler = new StunIoHandler<StunMessage>(messageVisitorFactory); final IoHandler udpIoHandler = new DemuxingIoHandler<StunMessage, T>( StunMessage.class, stunIoHandler, protocolMessageClass, udpProtocolIoHandler); final StunClient udpStunPeer; if (streamDesc.isUdp()) { try { udpStunPeer = new IceStunUdpPeer(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling(), transactionTracker); } catch (final IOException e) { // Note the constructor of the peer attempts a connection, so // this is named correctly. m_log.warn("Error connecting UDP peer", e); throw new IceUdpConnectException("Could not create UDP peer", e); } udpStunPeer.addIoServiceListener(udpServiceListener); } else { udpStunPeer = null; } // This class just decodes the TCP frames. final IceStunTcpPeer tcpStunPeer; if (streamDesc.isTcp()) { final TurnClientListener turnClientListener = new StunTcpFrameTurnClientListener(messageVisitorFactory, delegateTurnClientListener); final DemuxableProtocolCodecFactory tcpFramingCodecFactory = new TcpFrameCodecFactory(); final TurnStunDemuxableProtocolCodecFactory mapper = new TurnStunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory codecFactory = new DemuxingProtocolCodecFactory(mapper, tcpFramingCodecFactory); // We only start a TURN client on the answerer to save resources -- // handled internally -- see IceStunTcpPeer connect. final StunClient tcpTurnClient = new TcpTurnClient(turnClientListener, codecFactory); tcpStunPeer = new IceStunTcpPeer(tcpTurnClient, messageVisitorFactory, iceAgent.isControlling(), upnpManager); } else { tcpStunPeer = null; } final IceCandidateGatherer gatherer = new IceCandidateGathererImpl(tcpStunPeer, udpStunPeer, iceAgent.isControlling(), streamDesc); final IceMediaStreamImpl stream = new IceMediaStreamImpl(iceAgent, streamDesc, gatherer); if (tcpStunPeer != null) { tcpStunPeer.addIoServiceListener(stream); } if (udpStunPeer != null) { udpStunPeer.addIoServiceListener(stream); } m_log.debug("Added media stream as listener...connecting..."); if (tcpStunPeer != null) { try { tcpStunPeer.connect(); } catch (final IOException e) { m_log.warn("Error connecting TCP peer", e); throw new IceTcpConnectException("Could not create TCP peer", e); } } if (udpStunPeer != null) { try { udpStunPeer.connect(); } catch (final IOException e) { // Note this will not occur because the connect at this // point is effectively a no-op -- the connection takes place // immediately in the constructor. m_log.warn("Error connecting UDP peer", e); throw new IceUdpConnectException("Could not create UDP peer", e); } } final Collection<IceCandidate> localCandidates = gatherer.gatherCandidates(); final IceUdpConnector udpConnector = new IceUdpConnector(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling()); udpConnector.addIoServiceListener(stream); udpConnector.addIoServiceListener(udpServiceListener); final IceTcpConnector tcpConnector = new IceTcpConnector(messageVisitorFactory, iceAgent.isControlling()); tcpConnector.addIoServiceListener(stream); final IceCandidatePairFactory candidatePairFactory = new IceCandidatePairFactoryImpl( checkerFactory, udpConnector, tcpConnector); final IceCheckList checkList = new IceCheckListImpl(candidatePairFactory, localCandidates); final ExistingSessionIceCandidatePairFactory existingSessionPairFactory = new ExistingSessionIceCandidatePairFactoryImpl(checkerFactory); final IceCheckScheduler scheduler = new IceCheckSchedulerImpl(iceAgent, stream, checkList, existingSessionPairFactory); stream.start(checkList, localCandidates, scheduler); return stream; }
public <T> IceMediaStream newIceMediaStream( final IceMediaStreamDesc streamDesc, final IceAgent iceAgent, final DemuxableProtocolCodecFactory protocolCodecFactory, final Class<T> protocolMessageClass, final IoHandler udpProtocolIoHandler, final TurnClientListener delegateTurnClientListener, final UpnpManager upnpManager, final IoServiceListener udpServiceListener) throws IceTcpConnectException, IceUdpConnectException { final DemuxableProtocolCodecFactory stunCodecFactory = new StunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory demuxingCodecFactory = new DemuxingProtocolCodecFactory( stunCodecFactory, protocolCodecFactory); final StunTransactionTracker<StunMessage> transactionTracker = new StunTransactionTrackerImpl(); final IceStunCheckerFactory checkerFactory = new IceStunCheckerFactoryImpl(transactionTracker); final StunMessageVisitorFactory messageVisitorFactory = new IceStunConnectivityCheckerFactoryImpl<StunMessage>(iceAgent, transactionTracker, checkerFactory); final IoHandler stunIoHandler = new StunIoHandler<StunMessage>(messageVisitorFactory); final IoHandler udpIoHandler = new DemuxingIoHandler<StunMessage, T>( StunMessage.class, stunIoHandler, protocolMessageClass, udpProtocolIoHandler); final StunClient udpStunPeer; if (streamDesc.isUdp()) { try { udpStunPeer = new IceStunUdpPeer(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling(), transactionTracker); } catch (final IOException e) { // Note the constructor of the peer attempts a connection, so // this is named correctly. m_log.warn("Error connecting UDP peer", e); throw new IceUdpConnectException("Could not create UDP peer", e); } udpStunPeer.addIoServiceListener(udpServiceListener); } else { udpStunPeer = null; } // This class just decodes the TCP frames. final IceStunTcpPeer tcpStunPeer; if (streamDesc.isTcp()) { final TurnClientListener turnClientListener = new StunTcpFrameTurnClientListener(messageVisitorFactory, delegateTurnClientListener); final DemuxableProtocolCodecFactory tcpFramingCodecFactory = new TcpFrameCodecFactory(); final TurnStunDemuxableProtocolCodecFactory mapper = new TurnStunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory codecFactory = new DemuxingProtocolCodecFactory(mapper, tcpFramingCodecFactory); // We only start a TURN client on the answerer to save resources -- // handled internally -- see IceStunTcpPeer connect. final StunClient tcpTurnClient = new TcpTurnClient(turnClientListener, codecFactory); tcpStunPeer = new IceStunTcpPeer(tcpTurnClient, messageVisitorFactory, iceAgent.isControlling(), upnpManager); } else { tcpStunPeer = null; } final IceCandidateGatherer gatherer = new IceCandidateGathererImpl(tcpStunPeer, udpStunPeer, iceAgent.isControlling(), streamDesc); final IceMediaStreamImpl stream = new IceMediaStreamImpl(iceAgent, streamDesc, gatherer); if (tcpStunPeer != null) { tcpStunPeer.addIoServiceListener(stream); } if (udpStunPeer != null) { udpStunPeer.addIoServiceListener(stream); } m_log.debug("Added media stream as listener...connecting..."); if (tcpStunPeer != null) { try { tcpStunPeer.connect(); } catch (final IOException e) { m_log.warn("Error connecting TCP peer", e); throw new IceTcpConnectException("Could not create TCP peer", e); } } if (udpStunPeer != null) { try { udpStunPeer.connect(); } catch (final IOException e) { // Note this will not occur because the connect at this // point is effectively a no-op -- the connection takes place // immediately in the constructor. m_log.warn("Error connecting UDP peer", e); if (tcpStunPeer != null) { // We've got to make sure to close TCP too!! tcpStunPeer.close(); } throw new IceUdpConnectException("Could not create UDP peer", e); } } final Collection<IceCandidate> localCandidates = gatherer.gatherCandidates(); final IceUdpConnector udpConnector = new IceUdpConnector(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling()); udpConnector.addIoServiceListener(stream); udpConnector.addIoServiceListener(udpServiceListener); final IceTcpConnector tcpConnector = new IceTcpConnector(messageVisitorFactory, iceAgent.isControlling()); tcpConnector.addIoServiceListener(stream); final IceCandidatePairFactory candidatePairFactory = new IceCandidatePairFactoryImpl( checkerFactory, udpConnector, tcpConnector); final IceCheckList checkList = new IceCheckListImpl(candidatePairFactory, localCandidates); final ExistingSessionIceCandidatePairFactory existingSessionPairFactory = new ExistingSessionIceCandidatePairFactoryImpl(checkerFactory); final IceCheckScheduler scheduler = new IceCheckSchedulerImpl(iceAgent, stream, checkList, existingSessionPairFactory); stream.start(checkList, localCandidates, scheduler); return stream; }
diff --git a/src/cs447/PuzzleFighter/PuzzleFighter.java b/src/cs447/PuzzleFighter/PuzzleFighter.java index 88215f9..2ddb13b 100644 --- a/src/cs447/PuzzleFighter/PuzzleFighter.java +++ b/src/cs447/PuzzleFighter/PuzzleFighter.java @@ -1,173 +1,173 @@ package cs447.PuzzleFighter; import java.awt.Font; import java.awt.event.KeyEvent; import java.awt.geom.AffineTransform; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; import jig.engine.FontResource; import jig.engine.RenderingContext; import jig.engine.ResourceFactory; import jig.engine.hli.StaticScreenGame; public class PuzzleFighter extends StaticScreenGame { final static double SCALE = 1.0; AffineTransform LEFT_TRANSFORM; AffineTransform RIGHT_TRANSFORM; public final static int height = (int) (416 * SCALE); public final static int width = (int) (700 * SCALE); private PlayField pfLeft; private PlayField pfRight; public Socket socket = null; public ServerSocket serv = null; private boolean playing = false; final static String RSC_PATH = "cs447/PuzzleFighter/resources/"; final static String GEM_SHEET = RSC_PATH + "gems.png"; final static String CUT_SHEET = RSC_PATH + "cutman.png"; final static String MEGA_SHEET = RSC_PATH + "megaman.png"; public static void main(String[] args) throws IOException { PuzzleFighter game = new PuzzleFighter(); game.run(); } public PuzzleFighter() throws IOException { super(width, height, false); ResourceFactory.getFactory().loadResources(RSC_PATH, "resources.xml"); LEFT_TRANSFORM = AffineTransform.getScaleInstance(SCALE, SCALE); RIGHT_TRANSFORM = (AffineTransform) LEFT_TRANSFORM.clone(); RIGHT_TRANSFORM.translate(508, 0); } private void localMultiplayer() throws IOException { socket = null; pfLeft = new PlayField(6, 13, socket, false); pfRight = new PlayField(6, 13, socket, true); } public void remoteClient(String host) throws IOException { connectTo(host); pfLeft = new PlayField(6, 13, socket, false); pfRight = new RemotePlayfield(6, 13, socket); } public void remoteServer() throws IOException { host(); pfLeft = new PlayField(6, 13, socket, false); pfRight = new RemotePlayfield(6, 13, socket); } public void render(RenderingContext rc) { super.render(rc); if (playing) { rc.setTransform(LEFT_TRANSFORM); pfLeft.render(rc); rc.setTransform(RIGHT_TRANSFORM); pfRight.render(rc); return; }else{ FontResource font = ResourceFactory.getFactory().getFontResource(new Font("Sans Serif", Font.BOLD, 30), java.awt.Color.red, null ); font.render("Puzzle Fighter", rc, AffineTransform.getTranslateInstance(280, 100)); font.render("1 - local multiplayer", rc, AffineTransform.getTranslateInstance(280, 150)); font.render("2 - remote host", rc, AffineTransform.getTranslateInstance(280, 200)); font.render("3 - remote client", rc, AffineTransform.getTranslateInstance(280, 250)); } } public void update(long deltaMs) { if (playing) { boolean down1 = keyboard.isPressed(KeyEvent.VK_S); boolean left1 = keyboard.isPressed(KeyEvent.VK_A); boolean right1 = keyboard.isPressed(KeyEvent.VK_D); boolean ccw1 = keyboard.isPressed(KeyEvent.VK_Q); boolean cw1 = keyboard.isPressed(KeyEvent.VK_E); int garbage = pfLeft.update(deltaMs, down1, left1, right1, ccw1, cw1); pfRight.garbage += garbage; boolean down2 = keyboard.isPressed(KeyEvent.VK_K); boolean left2 = keyboard.isPressed(KeyEvent.VK_J); boolean right2 = keyboard.isPressed(KeyEvent.VK_L); boolean ccw2 = keyboard.isPressed(KeyEvent.VK_U); boolean cw2 = keyboard.isPressed(KeyEvent.VK_O); int garbage2 = pfRight.update(deltaMs, down2, left2, right2, ccw2, cw2); - pfLeft.garbage += garbage; + pfLeft.garbage += garbage2; if(garbage2 == -1 || garbage == -1){ pfLeft.close(); pfRight.close(); playing = false; if(socket != null){ try { socket.close(); } catch (IOException ex) { Logger.getLogger(PuzzleFighter.class.getName()).log(Level.SEVERE, null, ex); } } } return; } if (keyboard.isPressed(KeyEvent.VK_1)) { try { localMultiplayer(); playing = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (keyboard.isPressed(KeyEvent.VK_2)) { try { remoteServer(); playing = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (keyboard.isPressed(KeyEvent.VK_3)) { try { remoteClient("71.193.145.84"); playing = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void connectTo(String host){ try { socket = new Socket(host, 50623); } catch (UnknownHostException ex) { Logger.getLogger(PuzzleFighter.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PuzzleFighter.class.getName()).log(Level.SEVERE, null, ex); } } public void host(){ try { serv = new ServerSocket(50623); socket = serv.accept(); serv.close(); } catch (IOException ex) { Logger.getLogger(PuzzleFighter.class.getName()).log(Level.SEVERE, null, ex); } } }
true
true
public void update(long deltaMs) { if (playing) { boolean down1 = keyboard.isPressed(KeyEvent.VK_S); boolean left1 = keyboard.isPressed(KeyEvent.VK_A); boolean right1 = keyboard.isPressed(KeyEvent.VK_D); boolean ccw1 = keyboard.isPressed(KeyEvent.VK_Q); boolean cw1 = keyboard.isPressed(KeyEvent.VK_E); int garbage = pfLeft.update(deltaMs, down1, left1, right1, ccw1, cw1); pfRight.garbage += garbage; boolean down2 = keyboard.isPressed(KeyEvent.VK_K); boolean left2 = keyboard.isPressed(KeyEvent.VK_J); boolean right2 = keyboard.isPressed(KeyEvent.VK_L); boolean ccw2 = keyboard.isPressed(KeyEvent.VK_U); boolean cw2 = keyboard.isPressed(KeyEvent.VK_O); int garbage2 = pfRight.update(deltaMs, down2, left2, right2, ccw2, cw2); pfLeft.garbage += garbage; if(garbage2 == -1 || garbage == -1){ pfLeft.close(); pfRight.close(); playing = false; if(socket != null){ try { socket.close(); } catch (IOException ex) { Logger.getLogger(PuzzleFighter.class.getName()).log(Level.SEVERE, null, ex); } } } return; } if (keyboard.isPressed(KeyEvent.VK_1)) { try { localMultiplayer(); playing = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (keyboard.isPressed(KeyEvent.VK_2)) { try { remoteServer(); playing = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (keyboard.isPressed(KeyEvent.VK_3)) { try { remoteClient("71.193.145.84"); playing = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public void update(long deltaMs) { if (playing) { boolean down1 = keyboard.isPressed(KeyEvent.VK_S); boolean left1 = keyboard.isPressed(KeyEvent.VK_A); boolean right1 = keyboard.isPressed(KeyEvent.VK_D); boolean ccw1 = keyboard.isPressed(KeyEvent.VK_Q); boolean cw1 = keyboard.isPressed(KeyEvent.VK_E); int garbage = pfLeft.update(deltaMs, down1, left1, right1, ccw1, cw1); pfRight.garbage += garbage; boolean down2 = keyboard.isPressed(KeyEvent.VK_K); boolean left2 = keyboard.isPressed(KeyEvent.VK_J); boolean right2 = keyboard.isPressed(KeyEvent.VK_L); boolean ccw2 = keyboard.isPressed(KeyEvent.VK_U); boolean cw2 = keyboard.isPressed(KeyEvent.VK_O); int garbage2 = pfRight.update(deltaMs, down2, left2, right2, ccw2, cw2); pfLeft.garbage += garbage2; if(garbage2 == -1 || garbage == -1){ pfLeft.close(); pfRight.close(); playing = false; if(socket != null){ try { socket.close(); } catch (IOException ex) { Logger.getLogger(PuzzleFighter.class.getName()).log(Level.SEVERE, null, ex); } } } return; } if (keyboard.isPressed(KeyEvent.VK_1)) { try { localMultiplayer(); playing = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (keyboard.isPressed(KeyEvent.VK_2)) { try { remoteServer(); playing = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (keyboard.isPressed(KeyEvent.VK_3)) { try { remoteClient("71.193.145.84"); playing = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
diff --git a/src/main/java/hudson/plugins/promoted_builds/Status.java b/src/main/java/hudson/plugins/promoted_builds/Status.java index cbe0df3..a4c4cac 100644 --- a/src/main/java/hudson/plugins/promoted_builds/Status.java +++ b/src/main/java/hudson/plugins/promoted_builds/Status.java @@ -1,227 +1,227 @@ package hudson.plugins.promoted_builds; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.Cause.UserCause; import hudson.model.Result; import hudson.util.Iterators; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.GregorianCalendar; import java.util.List; /** * Promotion status of a build wrt a specific {@link PromotionProcess}. * * @author Kohsuke Kawaguchi * @see PromotedBuildAction#statuses */ public final class Status { /** * Matches with {@link PromotionProcess#name}. */ public final String name; private final PromotionBadge[] badges; /** * When did the build qualify for a promotion? */ public final Calendar timestamp = new GregorianCalendar(); /** * If the build is successfully promoted, the build number of {@link Promotion} * that represents that record. * * -1 to indicate that the promotion was not successful yet. */ private int promotion = -1; /** * Bulid numbers of {@link Promotion}s that are attempted. * If {@link Promotion} fails, this field can have multiple values. * Sorted in the ascending order. */ private List<Integer> promotionAttempts = new ArrayList<Integer>(); /*package*/ transient PromotedBuildAction parent; public Status(PromotionProcess process, Collection<? extends PromotionBadge> badges) { this.name = process.getName(); this.badges = badges.toArray(new PromotionBadge[badges.size()]); } public String getName() { return name; } /** * Gets the parent {@link Status} that owns this object. */ public PromotedBuildAction getParent() { return parent; } /** * Gets the {@link PromotionProcess} that this object deals with. */ public PromotionProcess getProcess() { JobPropertyImpl jp = parent.getProject().getProperty(JobPropertyImpl.class); if(jp==null) return null; return jp.getItem(name); } /** * Gets the build that was qualified for a promotion. */ public AbstractBuild<?,?> getTarget() { return getParent().owner; } /** * Gets the string that says how long since this promotion had happened. * * @return * string like "3 minutes" "1 day" etc. */ public String getTimestampString() { long duration = new GregorianCalendar().getTimeInMillis()-timestamp.getTimeInMillis(); return Util.getTimeSpanString(duration); } /** * Gets the string that says how long did it toook for this build to be promoted. */ public String getDelayString(AbstractBuild<?,?> owner) { long duration = timestamp.getTimeInMillis() - owner.getTimestamp().getTimeInMillis() - owner.getDuration(); return Util.getTimeSpanString(duration); } public boolean isFor(PromotionProcess process) { return process.getName().equals(this.name); } /** * Returns the {@link Promotion} object that represents the successful promotion. * * @return * null if the promotion has never been successful, or if it was but * the record is already lost. */ public Promotion getSuccessfulPromotion(JobPropertyImpl jp) { if(promotion>=0) { PromotionProcess p = jp.getItem(name); if(p!=null) return p.getBuildByNumber(promotion); } return null; } /** * Returns true if the promotion was successfully completed. */ public boolean isPromotionSuccessful() { return promotion>=0; } /** * Returns true if at least one {@link Promotion} activity is attempted. * False if none is executed yet (this includes the case where it's in the queue.) */ public boolean isPromotionAttempted() { return !promotionAttempts.isEmpty(); } /** * Returns true if the promotion for this is pending in the queue, * waiting to be executed. */ public boolean isInQueue() { PromotionProcess p = getProcess(); return p!=null && p.isInQueue(getTarget()); } /** * Gets the badges indicating how did a build qualify for a promotion. */ public List<PromotionBadge> getBadges() { return Arrays.asList(badges); } /** * Called when a new promotion attempts for this build starts. */ /*package*/ void addPromotionAttempt(Promotion p) { promotionAttempts.add(p.getNumber()); } /** * Called when a promotion succeeds. */ /*package*/ void onSuccessfulPromotion(Promotion p) { promotion = p.getNumber(); } // // web bound methods // /** * Gets the last successful {@link Promotion}. */ public Promotion getLastSuccessful() { PromotionProcess p = getProcess(); for( Integer n : Iterators.reverse(promotionAttempts) ) { Promotion b = p.getBuildByNumber(n); if(b!=null && b.getResult()== Result.SUCCESS) return b; } return null; } /** * Gets the last successful {@link Promotion}. */ public Promotion getLastFailed() { PromotionProcess p = getProcess(); for( Integer n : Iterators.reverse(promotionAttempts) ) { Promotion b = p.getBuildByNumber(n); if(b!=null && b.getResult()!=Result.SUCCESS) return b; } return null; } /** * Gets all the promotion builds. */ public List<Promotion> getPromotionBuilds() { PromotionProcess p = getProcess(); List<Promotion> builds = new ArrayList<Promotion>(); - for( Integer n : promotionAttempts ) { + for( Integer n : Iterators.reverse(promotionAttempts) ) { Promotion b = p.getBuildByNumber(n); if (b != null) { builds.add(b); } } return builds; } /** * Schedules a new build. */ public void doBuild(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { if(!getTarget().hasPermission(Promotion.PROMOTE)) return; getProcess().scheduleBuild(getTarget(),new UserCause()); // TODO: we need better visual feed back so that the user knows that the build happened. rsp.forwardToPreviousPage(req); } }
true
true
public List<Promotion> getPromotionBuilds() { PromotionProcess p = getProcess(); List<Promotion> builds = new ArrayList<Promotion>(); for( Integer n : promotionAttempts ) { Promotion b = p.getBuildByNumber(n); if (b != null) { builds.add(b); } } return builds; }
public List<Promotion> getPromotionBuilds() { PromotionProcess p = getProcess(); List<Promotion> builds = new ArrayList<Promotion>(); for( Integer n : Iterators.reverse(promotionAttempts) ) { Promotion b = p.getBuildByNumber(n); if (b != null) { builds.add(b); } } return builds; }
diff --git a/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java b/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java index b90cf24..e74f923 100644 --- a/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java +++ b/Toolbox/src/biz/shadowservices/DegreesToolbox/DataFetcher.java @@ -1,428 +1,428 @@ /******************************************************************************* * Copyright (c) 2011 Jordan Thoms. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package biz.shadowservices.DegreesToolbox; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.message.BasicNameValuePair; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import de.quist.app.errorreporter.ExceptionReporter; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.preference.PreferenceManager; import android.util.Log; public class DataFetcher { // This class handles the actual fetching of the data from 2Degrees. public double result; public static final String LASTMONTHCHARGES = "Your last month's charges"; private static String TAG = "2DegreesDataFetcher"; private ExceptionReporter exceptionReporter; public enum FetchResult { SUCCESS, NOTONLINE, LOGINFAILED, USERNAMEPASSWORDNOTSET, NETWORKERROR, NOTALLOWED } public DataFetcher(ExceptionReporter e) { exceptionReporter = e; } public boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info == null) { return false; } else { return info.isConnected(); } } public boolean isWifi(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (info == null) { return false; } else { return info.isConnected(); } } public boolean isRoaming(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (info == null) { return false; } else { return info.isRoaming(); } } public boolean isBackgroundDataEnabled(Context context) { ConnectivityManager mgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); return(mgr.getBackgroundDataSetting()); } public boolean isAutoSyncEnabled() { // Get the autosync setting, if on a phone which has one. // There are better ways of doing this than reflection, but it's easy in this case // since then we can keep linking against the 1.6 SDK. if (android.os.Build.VERSION.SDK_INT >= 5) { Class<ContentResolver> contentResolverClass = ContentResolver.class; try { Method m = contentResolverClass.getMethod("getMasterSyncAutomatically", null); Log.d(TAG, m.toString()); Log.d(TAG, m.invoke(null, null).toString()); boolean bool = ((Boolean)m.invoke(null, null)).booleanValue(); return bool; } catch (Exception e) { Log.d(TAG, "could not determine if autosync is enabled, assuming yes"); return true; } } else { return true; } } public FetchResult updateData(Context context, boolean force) { //Open database DBOpenHelper dbhelper = new DBOpenHelper(context); SQLiteDatabase db = dbhelper.getWritableDatabase(); // check for internet connectivity try { if (!isOnline(context)) { Log.d(TAG, "We do not seem to be online. Skipping Update."); return FetchResult.NOTONLINE; } } catch (Exception e) { exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()"); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); if (!force) { try { if (sp.getBoolean("loginFailed", false) == true) { Log.d(TAG, "Previous login failed. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update."); return FetchResult.LOGINFAILED; } if(sp.getBoolean("autoupdates", true) == false) { Log.d(TAG, "Automatic updates not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) { Log.d(TAG, "Background data not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) { Log.d(TAG, "Auto sync not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) { Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update"); DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update"); return FetchResult.NOTALLOWED; } else if (!isWifi(context)){ Log.d(TAG, "We are not on wifi."); if (!isRoaming(context) && !sp.getBoolean("2DData", true)) { Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) { Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } } } catch (Exception e) { exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update."); } } else { Log.d(TAG, "Update Forced"); } try { String username = sp.getString("username", null); String password = sp.getString("password", null); if(username == null || password == null) { DBLog.insertMessage(context, "i", TAG, "Username or password not set."); return FetchResult.USERNAMEPASSWORDNOTSET; } // Find the URL of the page to send login data to. Log.d(TAG, "Finding Action. "); HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login"); String loginPageString = loginPageGet.execute(); if (loginPageString != null) { Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login"); Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first(); String loginAction = loginForm.attr("action"); // Send login form List<NameValuePair> loginValues = new ArrayList <NameValuePair>(); loginValues.add(new BasicNameValuePair("externalURLRedirect", "")); loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin")); loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M")); loginValues.add(new BasicNameValuePair("hdnlocale", "")); loginValues.add(new BasicNameValuePair("userid", username)); loginValues.add(new BasicNameValuePair("password", password)); Log.d(TAG, "Sending Login "); HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues); // Parse result Document homePage = Jsoup.parse(sendLoginPoster.execute()); // Determine if this is a pre-pay or post-paid account. boolean postPaid; if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) { Log.d(TAG, "Pre-pay account or no account."); postPaid = false; } else { Log.d(TAG, "Post-paid account."); postPaid = true; } Element accountSummary = homePage.getElementById("accountSummary"); if (accountSummary == null) { Log.d(TAG, "Login failed."); return FetchResult.LOGINFAILED; } db.delete("cache", "", null); /* This code fetched some extra details for postpaid users, but on reflection they aren't that useful. * Might reconsider this. * if (postPaid) { Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first(); Elements rows = accountBalanceSummaryTable.getElementsByTag("tr"); int rowno = 0; for (Element row : rows) { if (rowno > 1) { break; } //Log.d(TAG, "Starting row"); //Log.d(TAG, row.html()); Double value; try { Element amount = row.getElementsByClass("tableBillamount").first(); String amountHTML = amount.html(); Log.d(TAG, amountHTML.substring(1)); value = Double.parseDouble(amountHTML.substring(1)); } catch (Exception e) { Log.d(TAG, "Failed to parse amount from row."); value = null; } String expiresDetails = ""; String expiresDate = null; String name = null; try { Element details = row.getElementsByClass("tableBilldetail").first(); name = details.ownText(); Element expires = details.getElementsByTag("em").first(); if (expires != null) { expiresDetails = expires.text(); } Log.d(TAG, expiresDetails); Pattern pattern; pattern = Pattern.compile("\\(payment is due (.*)\\)"); Matcher matcher = pattern.matcher(expiresDetails); if (matcher.find()) { /*Log.d(TAG, "matched expires"); Log.d(TAG, "group 0:" + matcher.group(0)); Log.d(TAG, "group 1:" + matcher.group(1)); Log.d(TAG, "group 2:" + matcher.group(2)); * String expiresDateString = matcher.group(1); Date expiresDateObj; if (expiresDateString != null) { if (expiresDateString.length() > 0) { try { expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString); expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj); } catch (java.text.ParseException e) { Log.d(TAG, "Could not parse date: " + expiresDateString); } } } } } catch (Exception e) { Log.d(TAG, "Failed to parse details from row."); } String expirev = null; ContentValues values = new ContentValues(); values.put("name", name); values.put("value", value); values.put("units", "$NZ"); values.put("expires_value", expirev ); values.put("expires_date", expiresDate); db.insert("cache", "value", values ); rowno++; } } */ Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first(); Elements rows = accountSummaryTable.getElementsByTag("tr"); for (Element row : rows) { // We are now looking at each of the rows in the data table. //Log.d(TAG, "Starting row"); //Log.d(TAG, row.html()); Double value; String units; try { Element amount = row.getElementsByClass("tableBillamount").first(); String amountHTML = amount.html(); //Log.d(TAG, amountHTML); String[] amountParts = amountHTML.split("&nbsp;", 2); //Log.d(TAG, amountParts[0]); //Log.d(TAG, amountParts[1]); - if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) { + if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need") || amountParts[0].equals("Unlimited Text*")) { value = Values.INCLUDED; } else { try { value = Double.parseDouble(amountParts[0]); } catch (NumberFormatException e) { exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value."); value = 0.0; } } units = amountParts[1]; } catch (NullPointerException e) { //Log.d(TAG, "Failed to parse amount from row."); value = null; units = null; } Element details = row.getElementsByClass("tableBilldetail").first(); String name = details.getElementsByTag("strong").first().text(); Element expires = details.getElementsByTag("em").first(); String expiresDetails = ""; if (expires != null) { expiresDetails = expires.text(); } Log.d(TAG, expiresDetails); Pattern pattern; if (postPaid == false) { pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)"); } else { pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)"); } Matcher matcher = pattern.matcher(expiresDetails); Double expiresValue = null; String expiresDate = null; if (matcher.find()) { /*Log.d(TAG, "matched expires"); Log.d(TAG, "group 0:" + matcher.group(0)); Log.d(TAG, "group 1:" + matcher.group(1)); Log.d(TAG, "group 2:" + matcher.group(2)); */ try { expiresValue = Double.parseDouble(matcher.group(1)); } catch (NumberFormatException e) { expiresValue = null; } String expiresDateString = matcher.group(2); Date expiresDateObj; if (expiresDateString != null) { if (expiresDateString.length() > 0) { try { expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString); expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj); } catch (java.text.ParseException e) { Log.d(TAG, "Could not parse date: " + expiresDateString); } } } } ContentValues values = new ContentValues(); values.put("name", name); values.put("value", value); values.put("units", units); values.put("expires_value", expiresValue); values.put("expires_date", expiresDate); db.insert("cache", "value", values ); } if(postPaid == false) { Log.d(TAG, "Getting Value packs..."); // Find value packs HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack"); String valuePacksPageString = valuePacksPageGet.execute(); //DBLog.insertMessage(context, "d", "", valuePacksPageString); if(valuePacksPageString != null) { Document valuePacksPage = Jsoup.parse(valuePacksPageString); Elements enabledPacks = valuePacksPage.getElementsByClass("yellow"); for (Element enabledPack : enabledPacks) { Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first(); if (offerNameElemt != null) { String offerName = offerNameElemt.val(); DBLog.insertMessage(context, "d", "", "Got element: " + offerName); ValuePack[] packs = Values.valuePacks.get(offerName); if (packs == null) { DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched."); } else { for (ValuePack pack: packs) { ContentValues values = new ContentValues(); values.put("plan_startamount", pack.value); values.put("plan_name", offerName); DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value); db.update("cache", values, "name = '" + pack.type.id + "'", null); } } } } } } SharedPreferences.Editor prefedit = sp.edit(); Date now = new Date(); prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now)); prefedit.putBoolean("loginFailed", false); prefedit.putBoolean("networkError", false); prefedit.commit(); DBLog.insertMessage(context, "i", TAG, "Update Successful"); return FetchResult.SUCCESS; } } catch (ClientProtocolException e) { DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage()); return FetchResult.NETWORKERROR; } catch (IOException e) { DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage()); return FetchResult.NETWORKERROR; } finally { db.close(); } return null; } }
true
true
public FetchResult updateData(Context context, boolean force) { //Open database DBOpenHelper dbhelper = new DBOpenHelper(context); SQLiteDatabase db = dbhelper.getWritableDatabase(); // check for internet connectivity try { if (!isOnline(context)) { Log.d(TAG, "We do not seem to be online. Skipping Update."); return FetchResult.NOTONLINE; } } catch (Exception e) { exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()"); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); if (!force) { try { if (sp.getBoolean("loginFailed", false) == true) { Log.d(TAG, "Previous login failed. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update."); return FetchResult.LOGINFAILED; } if(sp.getBoolean("autoupdates", true) == false) { Log.d(TAG, "Automatic updates not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) { Log.d(TAG, "Background data not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) { Log.d(TAG, "Auto sync not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) { Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update"); DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update"); return FetchResult.NOTALLOWED; } else if (!isWifi(context)){ Log.d(TAG, "We are not on wifi."); if (!isRoaming(context) && !sp.getBoolean("2DData", true)) { Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) { Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } } } catch (Exception e) { exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update."); } } else { Log.d(TAG, "Update Forced"); } try { String username = sp.getString("username", null); String password = sp.getString("password", null); if(username == null || password == null) { DBLog.insertMessage(context, "i", TAG, "Username or password not set."); return FetchResult.USERNAMEPASSWORDNOTSET; } // Find the URL of the page to send login data to. Log.d(TAG, "Finding Action. "); HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login"); String loginPageString = loginPageGet.execute(); if (loginPageString != null) { Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login"); Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first(); String loginAction = loginForm.attr("action"); // Send login form List<NameValuePair> loginValues = new ArrayList <NameValuePair>(); loginValues.add(new BasicNameValuePair("externalURLRedirect", "")); loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin")); loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M")); loginValues.add(new BasicNameValuePair("hdnlocale", "")); loginValues.add(new BasicNameValuePair("userid", username)); loginValues.add(new BasicNameValuePair("password", password)); Log.d(TAG, "Sending Login "); HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues); // Parse result Document homePage = Jsoup.parse(sendLoginPoster.execute()); // Determine if this is a pre-pay or post-paid account. boolean postPaid; if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) { Log.d(TAG, "Pre-pay account or no account."); postPaid = false; } else { Log.d(TAG, "Post-paid account."); postPaid = true; } Element accountSummary = homePage.getElementById("accountSummary"); if (accountSummary == null) { Log.d(TAG, "Login failed."); return FetchResult.LOGINFAILED; } db.delete("cache", "", null); /* This code fetched some extra details for postpaid users, but on reflection they aren't that useful. * Might reconsider this. * if (postPaid) { Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first(); Elements rows = accountBalanceSummaryTable.getElementsByTag("tr"); int rowno = 0; for (Element row : rows) { if (rowno > 1) { break; } //Log.d(TAG, "Starting row"); //Log.d(TAG, row.html()); Double value; try { Element amount = row.getElementsByClass("tableBillamount").first(); String amountHTML = amount.html(); Log.d(TAG, amountHTML.substring(1)); value = Double.parseDouble(amountHTML.substring(1)); } catch (Exception e) { Log.d(TAG, "Failed to parse amount from row."); value = null; } String expiresDetails = ""; String expiresDate = null; String name = null; try { Element details = row.getElementsByClass("tableBilldetail").first(); name = details.ownText(); Element expires = details.getElementsByTag("em").first(); if (expires != null) { expiresDetails = expires.text(); } Log.d(TAG, expiresDetails); Pattern pattern; pattern = Pattern.compile("\\(payment is due (.*)\\)"); Matcher matcher = pattern.matcher(expiresDetails); if (matcher.find()) { /*Log.d(TAG, "matched expires"); Log.d(TAG, "group 0:" + matcher.group(0)); Log.d(TAG, "group 1:" + matcher.group(1)); Log.d(TAG, "group 2:" + matcher.group(2)); * String expiresDateString = matcher.group(1); Date expiresDateObj; if (expiresDateString != null) { if (expiresDateString.length() > 0) { try { expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString); expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj); } catch (java.text.ParseException e) { Log.d(TAG, "Could not parse date: " + expiresDateString); } } } } } catch (Exception e) { Log.d(TAG, "Failed to parse details from row."); } String expirev = null; ContentValues values = new ContentValues(); values.put("name", name); values.put("value", value); values.put("units", "$NZ"); values.put("expires_value", expirev ); values.put("expires_date", expiresDate); db.insert("cache", "value", values ); rowno++; } } */ Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first(); Elements rows = accountSummaryTable.getElementsByTag("tr"); for (Element row : rows) { // We are now looking at each of the rows in the data table. //Log.d(TAG, "Starting row"); //Log.d(TAG, row.html()); Double value; String units; try { Element amount = row.getElementsByClass("tableBillamount").first(); String amountHTML = amount.html(); //Log.d(TAG, amountHTML); String[] amountParts = amountHTML.split("&nbsp;", 2); //Log.d(TAG, amountParts[0]); //Log.d(TAG, amountParts[1]); if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) { value = Values.INCLUDED; } else { try { value = Double.parseDouble(amountParts[0]); } catch (NumberFormatException e) { exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value."); value = 0.0; } } units = amountParts[1]; } catch (NullPointerException e) { //Log.d(TAG, "Failed to parse amount from row."); value = null; units = null; } Element details = row.getElementsByClass("tableBilldetail").first(); String name = details.getElementsByTag("strong").first().text(); Element expires = details.getElementsByTag("em").first(); String expiresDetails = ""; if (expires != null) { expiresDetails = expires.text(); } Log.d(TAG, expiresDetails); Pattern pattern; if (postPaid == false) { pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)"); } else { pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)"); } Matcher matcher = pattern.matcher(expiresDetails); Double expiresValue = null; String expiresDate = null; if (matcher.find()) { /*Log.d(TAG, "matched expires"); Log.d(TAG, "group 0:" + matcher.group(0)); Log.d(TAG, "group 1:" + matcher.group(1)); Log.d(TAG, "group 2:" + matcher.group(2)); */ try { expiresValue = Double.parseDouble(matcher.group(1)); } catch (NumberFormatException e) { expiresValue = null; } String expiresDateString = matcher.group(2); Date expiresDateObj; if (expiresDateString != null) { if (expiresDateString.length() > 0) { try { expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString); expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj); } catch (java.text.ParseException e) { Log.d(TAG, "Could not parse date: " + expiresDateString); } } } } ContentValues values = new ContentValues(); values.put("name", name); values.put("value", value); values.put("units", units); values.put("expires_value", expiresValue); values.put("expires_date", expiresDate); db.insert("cache", "value", values ); } if(postPaid == false) { Log.d(TAG, "Getting Value packs..."); // Find value packs HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack"); String valuePacksPageString = valuePacksPageGet.execute(); //DBLog.insertMessage(context, "d", "", valuePacksPageString); if(valuePacksPageString != null) { Document valuePacksPage = Jsoup.parse(valuePacksPageString); Elements enabledPacks = valuePacksPage.getElementsByClass("yellow"); for (Element enabledPack : enabledPacks) { Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first(); if (offerNameElemt != null) { String offerName = offerNameElemt.val(); DBLog.insertMessage(context, "d", "", "Got element: " + offerName); ValuePack[] packs = Values.valuePacks.get(offerName); if (packs == null) { DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched."); } else { for (ValuePack pack: packs) { ContentValues values = new ContentValues(); values.put("plan_startamount", pack.value); values.put("plan_name", offerName); DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value); db.update("cache", values, "name = '" + pack.type.id + "'", null); } } } } } } SharedPreferences.Editor prefedit = sp.edit(); Date now = new Date(); prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now)); prefedit.putBoolean("loginFailed", false); prefedit.putBoolean("networkError", false); prefedit.commit(); DBLog.insertMessage(context, "i", TAG, "Update Successful"); return FetchResult.SUCCESS; } } catch (ClientProtocolException e) { DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage()); return FetchResult.NETWORKERROR; } catch (IOException e) { DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage()); return FetchResult.NETWORKERROR; } finally { db.close(); } return null; }
public FetchResult updateData(Context context, boolean force) { //Open database DBOpenHelper dbhelper = new DBOpenHelper(context); SQLiteDatabase db = dbhelper.getWritableDatabase(); // check for internet connectivity try { if (!isOnline(context)) { Log.d(TAG, "We do not seem to be online. Skipping Update."); return FetchResult.NOTONLINE; } } catch (Exception e) { exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()"); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); if (!force) { try { if (sp.getBoolean("loginFailed", false) == true) { Log.d(TAG, "Previous login failed. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update."); return FetchResult.LOGINFAILED; } if(sp.getBoolean("autoupdates", true) == false) { Log.d(TAG, "Automatic updates not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) { Log.d(TAG, "Background data not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) { Log.d(TAG, "Auto sync not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) { Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update"); DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update"); return FetchResult.NOTALLOWED; } else if (!isWifi(context)){ Log.d(TAG, "We are not on wifi."); if (!isRoaming(context) && !sp.getBoolean("2DData", true)) { Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) { Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update."); DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update."); return FetchResult.NOTALLOWED; } } } catch (Exception e) { exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update."); } } else { Log.d(TAG, "Update Forced"); } try { String username = sp.getString("username", null); String password = sp.getString("password", null); if(username == null || password == null) { DBLog.insertMessage(context, "i", TAG, "Username or password not set."); return FetchResult.USERNAMEPASSWORDNOTSET; } // Find the URL of the page to send login data to. Log.d(TAG, "Finding Action. "); HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login"); String loginPageString = loginPageGet.execute(); if (loginPageString != null) { Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login"); Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first(); String loginAction = loginForm.attr("action"); // Send login form List<NameValuePair> loginValues = new ArrayList <NameValuePair>(); loginValues.add(new BasicNameValuePair("externalURLRedirect", "")); loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin")); loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M")); loginValues.add(new BasicNameValuePair("hdnlocale", "")); loginValues.add(new BasicNameValuePair("userid", username)); loginValues.add(new BasicNameValuePair("password", password)); Log.d(TAG, "Sending Login "); HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues); // Parse result Document homePage = Jsoup.parse(sendLoginPoster.execute()); // Determine if this is a pre-pay or post-paid account. boolean postPaid; if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) { Log.d(TAG, "Pre-pay account or no account."); postPaid = false; } else { Log.d(TAG, "Post-paid account."); postPaid = true; } Element accountSummary = homePage.getElementById("accountSummary"); if (accountSummary == null) { Log.d(TAG, "Login failed."); return FetchResult.LOGINFAILED; } db.delete("cache", "", null); /* This code fetched some extra details for postpaid users, but on reflection they aren't that useful. * Might reconsider this. * if (postPaid) { Element accountBalanceSummaryTable = accountSummary.getElementsByClass("tableBillSummary").first(); Elements rows = accountBalanceSummaryTable.getElementsByTag("tr"); int rowno = 0; for (Element row : rows) { if (rowno > 1) { break; } //Log.d(TAG, "Starting row"); //Log.d(TAG, row.html()); Double value; try { Element amount = row.getElementsByClass("tableBillamount").first(); String amountHTML = amount.html(); Log.d(TAG, amountHTML.substring(1)); value = Double.parseDouble(amountHTML.substring(1)); } catch (Exception e) { Log.d(TAG, "Failed to parse amount from row."); value = null; } String expiresDetails = ""; String expiresDate = null; String name = null; try { Element details = row.getElementsByClass("tableBilldetail").first(); name = details.ownText(); Element expires = details.getElementsByTag("em").first(); if (expires != null) { expiresDetails = expires.text(); } Log.d(TAG, expiresDetails); Pattern pattern; pattern = Pattern.compile("\\(payment is due (.*)\\)"); Matcher matcher = pattern.matcher(expiresDetails); if (matcher.find()) { /*Log.d(TAG, "matched expires"); Log.d(TAG, "group 0:" + matcher.group(0)); Log.d(TAG, "group 1:" + matcher.group(1)); Log.d(TAG, "group 2:" + matcher.group(2)); * String expiresDateString = matcher.group(1); Date expiresDateObj; if (expiresDateString != null) { if (expiresDateString.length() > 0) { try { expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString); expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj); } catch (java.text.ParseException e) { Log.d(TAG, "Could not parse date: " + expiresDateString); } } } } } catch (Exception e) { Log.d(TAG, "Failed to parse details from row."); } String expirev = null; ContentValues values = new ContentValues(); values.put("name", name); values.put("value", value); values.put("units", "$NZ"); values.put("expires_value", expirev ); values.put("expires_date", expiresDate); db.insert("cache", "value", values ); rowno++; } } */ Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first(); Elements rows = accountSummaryTable.getElementsByTag("tr"); for (Element row : rows) { // We are now looking at each of the rows in the data table. //Log.d(TAG, "Starting row"); //Log.d(TAG, row.html()); Double value; String units; try { Element amount = row.getElementsByClass("tableBillamount").first(); String amountHTML = amount.html(); //Log.d(TAG, amountHTML); String[] amountParts = amountHTML.split("&nbsp;", 2); //Log.d(TAG, amountParts[0]); //Log.d(TAG, amountParts[1]); if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need") || amountParts[0].equals("Unlimited Text*")) { value = Values.INCLUDED; } else { try { value = Double.parseDouble(amountParts[0]); } catch (NumberFormatException e) { exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value."); value = 0.0; } } units = amountParts[1]; } catch (NullPointerException e) { //Log.d(TAG, "Failed to parse amount from row."); value = null; units = null; } Element details = row.getElementsByClass("tableBilldetail").first(); String name = details.getElementsByTag("strong").first().text(); Element expires = details.getElementsByTag("em").first(); String expiresDetails = ""; if (expires != null) { expiresDetails = expires.text(); } Log.d(TAG, expiresDetails); Pattern pattern; if (postPaid == false) { pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)"); } else { pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)"); } Matcher matcher = pattern.matcher(expiresDetails); Double expiresValue = null; String expiresDate = null; if (matcher.find()) { /*Log.d(TAG, "matched expires"); Log.d(TAG, "group 0:" + matcher.group(0)); Log.d(TAG, "group 1:" + matcher.group(1)); Log.d(TAG, "group 2:" + matcher.group(2)); */ try { expiresValue = Double.parseDouble(matcher.group(1)); } catch (NumberFormatException e) { expiresValue = null; } String expiresDateString = matcher.group(2); Date expiresDateObj; if (expiresDateString != null) { if (expiresDateString.length() > 0) { try { expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString); expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj); } catch (java.text.ParseException e) { Log.d(TAG, "Could not parse date: " + expiresDateString); } } } } ContentValues values = new ContentValues(); values.put("name", name); values.put("value", value); values.put("units", units); values.put("expires_value", expiresValue); values.put("expires_date", expiresDate); db.insert("cache", "value", values ); } if(postPaid == false) { Log.d(TAG, "Getting Value packs..."); // Find value packs HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack"); String valuePacksPageString = valuePacksPageGet.execute(); //DBLog.insertMessage(context, "d", "", valuePacksPageString); if(valuePacksPageString != null) { Document valuePacksPage = Jsoup.parse(valuePacksPageString); Elements enabledPacks = valuePacksPage.getElementsByClass("yellow"); for (Element enabledPack : enabledPacks) { Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first(); if (offerNameElemt != null) { String offerName = offerNameElemt.val(); DBLog.insertMessage(context, "d", "", "Got element: " + offerName); ValuePack[] packs = Values.valuePacks.get(offerName); if (packs == null) { DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched."); } else { for (ValuePack pack: packs) { ContentValues values = new ContentValues(); values.put("plan_startamount", pack.value); values.put("plan_name", offerName); DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value); db.update("cache", values, "name = '" + pack.type.id + "'", null); } } } } } } SharedPreferences.Editor prefedit = sp.edit(); Date now = new Date(); prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now)); prefedit.putBoolean("loginFailed", false); prefedit.putBoolean("networkError", false); prefedit.commit(); DBLog.insertMessage(context, "i", TAG, "Update Successful"); return FetchResult.SUCCESS; } } catch (ClientProtocolException e) { DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage()); return FetchResult.NETWORKERROR; } catch (IOException e) { DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage()); return FetchResult.NETWORKERROR; } finally { db.close(); } return null; }
diff --git a/src/net/oauth/j2me/Util.java b/src/net/oauth/j2me/Util.java index 99896e9..e98b8ea 100644 --- a/src/net/oauth/j2me/Util.java +++ b/src/net/oauth/j2me/Util.java @@ -1,321 +1,321 @@ /* * Util.java * * Created on November 20, 2007, 2:31 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package net.oauth.j2me; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import javax.microedition.io.HttpsConnection; /** * * @author Administrator */ public class Util { /** Creates a new instance of Util */ public Util() { } // if the same key occurs in h1 and h2, use the value from h1 public static final Hashtable hashtableMerge(Hashtable h1, Hashtable h2) { System.out.println("in hastableMerge"); Hashtable h=new Hashtable(); Enumeration keys=h1.keys(); while (keys.hasMoreElements()) { Object k=keys.nextElement(); if (h1.get(k)!=null) { h.put(k, h1.get(k)); } } keys=h2.keys(); while (keys.hasMoreElements()) { Object k=keys.nextElement(); if (!h.containsKey(k) && h2.get(k)!=null) { h.put(k, h2.get(k)); } } return h; } // sorts String values public static final Enumeration sort(Enumeration e){ Vector v=new Vector(); while (e.hasMoreElements()) { String s=(String)e.nextElement(); int i=0; for (i=0; i<v.size(); i++) { int c=s.compareTo((String)v.elementAt(i)); if (c<0) { // s should go before i v.insertElementAt(s, i); break; } else if (c==0) { // s already there break; } } if (i>=v.size()) { // add s at end v.addElement(s); } } return v.elements(); } /** Split string into multiple strings * @param original Original string * @param separator Separator string in original string * @return Splitted string array */ // TODO -- add in a max split param public static final String[] split(String original, String separator) { Vector nodes = new Vector(); // Parse nodes into vector int index = original.indexOf(separator); while(index>=0) { nodes.addElement( original.substring(0, index) ); original = original.substring(index+separator.length()); index = original.indexOf(separator); } // Get the last node nodes.addElement( original ); // Create splitted string array String[] result = new String[ nodes.size() ]; if( nodes.size()>0 ) { for(int loop=0; loop<nodes.size(); loop++) result[loop] = (String)nodes.elementAt(loop); } return result; } // this is an OAuth-friendly url encode -- should work fine for ordniary encoding also public static final String urlEncode(String s) { if (s == null) return s; StringBuffer sb = new StringBuffer(s.length() * 3); try { char c; for (int i = 0; i < s.length(); i++) { c = s.charAt(i); if (c == '&') { //sb.append("&amp;"); // don't do this sb.append("%26"); //} else if (c == ' ') { // sb.append('+'); // maybe don't do this either } else if ( // safe characters c == '-' || c == '_' || c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ) { sb.append(c); } else { sb.append('%'); if (c > 15) { // is it a non-control char, ie. >x0F so 2 chars sb.append(Integer.toHexString((int)c).toUpperCase()); // just add % and the string } else { sb.append("0" + Integer.toHexString((int)c).toUpperCase()); // otherwise need to add a leading 0 } } } } catch (Exception ex) { return (null); } return (sb.toString()); } public static final String postViaHttpsConnection(String fullUrl) throws IOException, OAuthServiceProviderException { String[] urlPieces=split(fullUrl, "?"); HttpsConnection c = null; DataInputStream dis = null; OutputStream os = null; int rc; String respBody = new String(""); // return empty string on bad things // TODO -- better way to handle unexpected responses try { System.out.println("UTIL -- posting to "+urlPieces[0]); - c = (HttpsConnection)Connector.open(fullUrl, Connector.READ_WRITE); // hack for emulator? + c = (HttpsConnection)Connector.open(urlPieces[0], Connector.READ_WRITE); // hack for emulator? // Set the request method and headers c.setRequestMethod(HttpConnection.POST); c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0"); c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); c.setRequestProperty("Content-Length", ""+urlPieces[1].length()); // TODO -- add'l headers for t-mobile? // Getting the output stream may flush the headers os = c.openOutputStream(); System.out.println("UTIL -- writing POST data: "+urlPieces[1]); os.write(urlPieces[1].getBytes()); os.flush(); // Optional, getResponseCode will flush // Getting the response code will open the connection, // send the request, and read the HTTP response headers. // The headers are stored until requested. rc = c.getResponseCode(); int len = c.getHeaderFieldInt("Content-Length", 0); //int len = (int)c.getLength(); System.out.println("content-length="+len); dis = c.openDataInputStream(); byte[] data = new byte[len]; if (len == 0) { System.out.println("UTIL -- no length, reading individual characters..."); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); int ch; while( ( ch = dis.read() ) != -1 ) { tmp.write( ch ); } data = tmp.toByteArray(); } else { System.out.println("UTIL -- got a length, reading..."); dis.readFully(data); } respBody=new String(data); } catch (ClassCastException e) { throw new IllegalArgumentException("Not an HTTP URL"); } finally { if (dis != null) dis.close(); if (os != null) os.close(); if (c != null) c.close(); } if (rc != HttpConnection.HTTP_OK) { throw new OAuthServiceProviderException("HTTP response code: " + rc, rc, respBody); } return respBody; } public static final String getViaHttpsConnection(String url) throws IOException, OAuthServiceProviderException { HttpsConnection c = null; DataInputStream dis = null; OutputStream os = null; int rc; String respBody = new String(""); // return empty string on bad things // TODO -- better way to handle unexpected responses try { System.out.println("UTIL -- opening connection"); c= (HttpsConnection) Connector.open(url, Connector.READ); c.setRequestMethod(HttpConnection.GET); c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0"); c.setRequestProperty("Cache-Control", "no-store"); c.setRequestProperty("Connection", "close"); // not sure this is a good idea, but HTTP/1.0 might be less error-prone, some clients have trouble with chunked responses System.out.println("UTIL -- connection open"); // Getting the response code will open the connection, // send the request, and read the HTTP response headers. // The headers are stored until requested. rc = c.getResponseCode(); System.out.println("UTIL -- got response code" + rc); // Get the length and process the data int len = c.getHeaderFieldInt("Content-Length", 0); System.out.println("content-length="+len); dis = c.openDataInputStream(); byte[] data = null; if (len == -1L) { System.out.println("UTIL -- no length, reading individual characters..."); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); int ch; while( ( ch = dis.read() ) != -1 ) { tmp.write( ch ); } data = tmp.toByteArray(); } else { System.out.println("UTIL -- got a length, reading..."); data = new byte[len]; dis.read(data); } respBody=new String(data); } catch (ClassCastException e) { throw new IllegalArgumentException("Not an HTTP URL"); } finally { if (dis != null) dis.close(); if (c != null) c.close(); } if (rc != HttpConnection.HTTP_OK) { throw new OAuthServiceProviderException("HTTP response code: " + rc, rc, respBody); } return respBody; } private static char[] map1 = new char[64]; static { int i = 0; for ( char c = 'A'; c <= 'Z'; c++ ) { map1[i++] = c; } for ( char c = 'a'; c <= 'z'; c++ ) { map1[i++] = c; } for ( char c = '0'; c <= '9'; c++ ) { map1[i++] = c; } map1[i++] = '+'; map1[i++] = '/'; } public static final String base64Encode( byte[] in ) { int iLen = in.length; int oDataLen = ( iLen * 4 + 2 ) / 3;// output length without padding int oLen = ( ( iLen + 2 ) / 3 ) * 4;// output length including padding char[] out = new char[oLen]; int ip = 0; int op = 0; int i0; int i1; int i2; int o0; int o1; int o2; int o3; while ( ip < iLen ) { i0 = in[ip++] & 0xff; i1 = ip < iLen ? in[ip++] & 0xff : 0; i2 = ip < iLen ? in[ip++] & 0xff : 0; o0 = i0 >>> 2; o1 = ( ( i0 & 3 ) << 4 ) | ( i1 >>> 4 ); o2 = ( ( i1 & 0xf ) << 2 ) | ( i2 >>> 6 ); o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return new String( out ); } }
true
true
public static final String postViaHttpsConnection(String fullUrl) throws IOException, OAuthServiceProviderException { String[] urlPieces=split(fullUrl, "?"); HttpsConnection c = null; DataInputStream dis = null; OutputStream os = null; int rc; String respBody = new String(""); // return empty string on bad things // TODO -- better way to handle unexpected responses try { System.out.println("UTIL -- posting to "+urlPieces[0]); c = (HttpsConnection)Connector.open(fullUrl, Connector.READ_WRITE); // hack for emulator? // Set the request method and headers c.setRequestMethod(HttpConnection.POST); c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0"); c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); c.setRequestProperty("Content-Length", ""+urlPieces[1].length()); // TODO -- add'l headers for t-mobile? // Getting the output stream may flush the headers os = c.openOutputStream(); System.out.println("UTIL -- writing POST data: "+urlPieces[1]); os.write(urlPieces[1].getBytes()); os.flush(); // Optional, getResponseCode will flush // Getting the response code will open the connection, // send the request, and read the HTTP response headers. // The headers are stored until requested. rc = c.getResponseCode(); int len = c.getHeaderFieldInt("Content-Length", 0); //int len = (int)c.getLength(); System.out.println("content-length="+len); dis = c.openDataInputStream(); byte[] data = new byte[len]; if (len == 0) { System.out.println("UTIL -- no length, reading individual characters..."); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); int ch; while( ( ch = dis.read() ) != -1 ) { tmp.write( ch ); } data = tmp.toByteArray(); } else { System.out.println("UTIL -- got a length, reading..."); dis.readFully(data); } respBody=new String(data); } catch (ClassCastException e) { throw new IllegalArgumentException("Not an HTTP URL"); } finally { if (dis != null) dis.close(); if (os != null) os.close(); if (c != null) c.close(); } if (rc != HttpConnection.HTTP_OK) { throw new OAuthServiceProviderException("HTTP response code: " + rc, rc, respBody); } return respBody; }
public static final String postViaHttpsConnection(String fullUrl) throws IOException, OAuthServiceProviderException { String[] urlPieces=split(fullUrl, "?"); HttpsConnection c = null; DataInputStream dis = null; OutputStream os = null; int rc; String respBody = new String(""); // return empty string on bad things // TODO -- better way to handle unexpected responses try { System.out.println("UTIL -- posting to "+urlPieces[0]); c = (HttpsConnection)Connector.open(urlPieces[0], Connector.READ_WRITE); // hack for emulator? // Set the request method and headers c.setRequestMethod(HttpConnection.POST); c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0"); c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); c.setRequestProperty("Content-Length", ""+urlPieces[1].length()); // TODO -- add'l headers for t-mobile? // Getting the output stream may flush the headers os = c.openOutputStream(); System.out.println("UTIL -- writing POST data: "+urlPieces[1]); os.write(urlPieces[1].getBytes()); os.flush(); // Optional, getResponseCode will flush // Getting the response code will open the connection, // send the request, and read the HTTP response headers. // The headers are stored until requested. rc = c.getResponseCode(); int len = c.getHeaderFieldInt("Content-Length", 0); //int len = (int)c.getLength(); System.out.println("content-length="+len); dis = c.openDataInputStream(); byte[] data = new byte[len]; if (len == 0) { System.out.println("UTIL -- no length, reading individual characters..."); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); int ch; while( ( ch = dis.read() ) != -1 ) { tmp.write( ch ); } data = tmp.toByteArray(); } else { System.out.println("UTIL -- got a length, reading..."); dis.readFully(data); } respBody=new String(data); } catch (ClassCastException e) { throw new IllegalArgumentException("Not an HTTP URL"); } finally { if (dis != null) dis.close(); if (os != null) os.close(); if (c != null) c.close(); } if (rc != HttpConnection.HTTP_OK) { throw new OAuthServiceProviderException("HTTP response code: " + rc, rc, respBody); } return respBody; }
diff --git a/app/controllers/SearchApiController.java b/app/controllers/SearchApiController.java index ec6e12b1..0c7dc862 100644 --- a/app/controllers/SearchApiController.java +++ b/app/controllers/SearchApiController.java @@ -1,143 +1,143 @@ /* * Copyright 2013 TORCH UG * * This file is part of Graylog2. * * Graylog2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Graylog2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Graylog2. If not, see <http://www.gnu.org/licenses/>. */ package controllers; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.inject.Inject; import lib.APIException; import lib.SearchTools; import lib.timeranges.*; import models.UniversalSearch; import models.api.responses.FieldStatsResponse; import models.api.responses.FieldTermsResponse; import play.mvc.Result; import java.io.IOException; import java.util.Map; /** * @author Lennart Koopmann <[email protected]> */ public class SearchApiController extends AuthenticatedController { @Inject private UniversalSearch.Factory searchFactory; public Result fieldStats(String q, String field, String rangeType, int relative, String from, String to, String keyword, String interval) { if (q == null || q.isEmpty()) { q = "*"; } // Histogram interval. if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) { interval = "hour"; } // Determine timerange type. TimeRange timerange; try { timerange = TimeRange.factory(rangeType, relative, from, to, keyword); } catch(InvalidRangeParametersException e2) { return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request())); } catch(IllegalArgumentException e1) { return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request())); } try { UniversalSearch search = searchFactory.queryWithRange(q, timerange); FieldStatsResponse stats = search.fieldStats(field); Map<String, Object> result = Maps.newHashMap(); result.put("count", stats.count); result.put("sum", stats.sum); result.put("mean", stats.mean); result.put("min", stats.min); result.put("max", stats.max); result.put("variance", stats.variance); result.put("sum_of_squares", stats.sumOfSquares); result.put("std_deviation", stats.stdDeviation); return ok(new Gson().toJson(result)).as("application/json"); } catch (IOException e) { return internalServerError("io exception"); } catch (APIException e) { if (e.getHttpCode() == 400) { // This usually means the field does not have a numeric type. Pass through! return badRequest(); } return internalServerError("api exception " + e); } } public Result fieldTerms(String q, String field, String rangeType, int relative, String from, String to, String keyword, String interval) { if (q == null || q.isEmpty()) { q = "*"; } // Histogram interval. if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) { interval = "hour"; } // Determine timerange type. TimeRange timerange; try { timerange = TimeRange.factory(rangeType, relative, from, to, keyword); } catch(InvalidRangeParametersException e2) { return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request())); } catch(IllegalArgumentException e1) { return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request())); } ////////////// REMOVE ME try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } try { - UniversalSearch search = new UniversalSearch(timerange, q); + UniversalSearch search = searchFactory.queryWithRange(q, timerange);; FieldTermsResponse terms = search.fieldTerms(field); Map<String, Object> result = Maps.newHashMap(); result.put("total", terms.total); result.put("missing", terms.missing); result.put("time", terms.time); result.put("other", terms.other); result.put("terms", terms.terms); return ok(new Gson().toJson(result)).as("application/json"); } catch (IOException e) { return internalServerError("io exception"); } catch (APIException e) { if (e.getHttpCode() == 400) { // This usually means the field does not have a numeric type. Pass through! return badRequest(); } return internalServerError("api exception " + e); } } }
true
true
public Result fieldTerms(String q, String field, String rangeType, int relative, String from, String to, String keyword, String interval) { if (q == null || q.isEmpty()) { q = "*"; } // Histogram interval. if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) { interval = "hour"; } // Determine timerange type. TimeRange timerange; try { timerange = TimeRange.factory(rangeType, relative, from, to, keyword); } catch(InvalidRangeParametersException e2) { return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request())); } catch(IllegalArgumentException e1) { return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request())); } ////////////// REMOVE ME try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } try { UniversalSearch search = new UniversalSearch(timerange, q); FieldTermsResponse terms = search.fieldTerms(field); Map<String, Object> result = Maps.newHashMap(); result.put("total", terms.total); result.put("missing", terms.missing); result.put("time", terms.time); result.put("other", terms.other); result.put("terms", terms.terms); return ok(new Gson().toJson(result)).as("application/json"); } catch (IOException e) { return internalServerError("io exception"); } catch (APIException e) { if (e.getHttpCode() == 400) { // This usually means the field does not have a numeric type. Pass through! return badRequest(); } return internalServerError("api exception " + e); } }
public Result fieldTerms(String q, String field, String rangeType, int relative, String from, String to, String keyword, String interval) { if (q == null || q.isEmpty()) { q = "*"; } // Histogram interval. if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) { interval = "hour"; } // Determine timerange type. TimeRange timerange; try { timerange = TimeRange.factory(rangeType, relative, from, to, keyword); } catch(InvalidRangeParametersException e2) { return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request())); } catch(IllegalArgumentException e1) { return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request())); } ////////////// REMOVE ME try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } try { UniversalSearch search = searchFactory.queryWithRange(q, timerange);; FieldTermsResponse terms = search.fieldTerms(field); Map<String, Object> result = Maps.newHashMap(); result.put("total", terms.total); result.put("missing", terms.missing); result.put("time", terms.time); result.put("other", terms.other); result.put("terms", terms.terms); return ok(new Gson().toJson(result)).as("application/json"); } catch (IOException e) { return internalServerError("io exception"); } catch (APIException e) { if (e.getHttpCode() == 400) { // This usually means the field does not have a numeric type. Pass through! return badRequest(); } return internalServerError("api exception " + e); } }
diff --git a/GAE/src/com/gallatinsystems/image/ImageUtils.java b/GAE/src/com/gallatinsystems/image/ImageUtils.java index 64988b6df..7c96430f7 100644 --- a/GAE/src/com/gallatinsystems/image/ImageUtils.java +++ b/GAE/src/com/gallatinsystems/image/ImageUtils.java @@ -1,44 +1,44 @@ package com.gallatinsystems.image; import java.util.ArrayList; public class ImageUtils { /* * Utility method to return the parts of an image path for S3 * Position 0 = web domain with bucket ends with / * Position 1 = middle path elements ends with / * Position 2 = file name */ - public static ArrayList<String> parseImageParts(String url) { - ArrayList<String> parts = new ArrayList<String>(); + public static String[] parseImageParts(String url) { + String[] parts = new String[3]; url = url.toLowerCase().replace("http://", ""); String[] items = url.split("/"); if (items.length == 3) { // no country in path - parts.add("http://:" + items[0] + "/"); - parts.add(items[1] + "/"); - parts.add(items[2]); + parts[0]=("http://:" + items[0] + "/"); + parts[1]=(items[1] + "/"); + parts[2]=(items[2]); } else if (items.length > 3) { - parts.add("http://:" + items[0] + "/"); + parts[0]=("http://:" + items[0] + "/"); String middlePath = ""; int i = 0; for (i = 1; i < items.length - 1; i++) middlePath += items[i] + "/"; - parts.add(middlePath); - parts.add(items[i]); + parts[1]=(middlePath); + parts[2]=(items[i]); } return parts; } public static void main(String[] args) { String test1 = "http://waterforpeople.s3.amazonaws.com/images/wfpPhoto10062903227521.jpg"; String test2 = "http://waterforpeople.s3.amazonaws.com/images/hn/ch003[1].jpg"; System.out.println(test1); for (String item : parseImageParts(test1)) System.out.println(" " + item); System.out.println(test2); for (String item : parseImageParts(test2)) System.out.println(" " + item); } }
false
true
public static ArrayList<String> parseImageParts(String url) { ArrayList<String> parts = new ArrayList<String>(); url = url.toLowerCase().replace("http://", ""); String[] items = url.split("/"); if (items.length == 3) { // no country in path parts.add("http://:" + items[0] + "/"); parts.add(items[1] + "/"); parts.add(items[2]); } else if (items.length > 3) { parts.add("http://:" + items[0] + "/"); String middlePath = ""; int i = 0; for (i = 1; i < items.length - 1; i++) middlePath += items[i] + "/"; parts.add(middlePath); parts.add(items[i]); } return parts; }
public static String[] parseImageParts(String url) { String[] parts = new String[3]; url = url.toLowerCase().replace("http://", ""); String[] items = url.split("/"); if (items.length == 3) { // no country in path parts[0]=("http://:" + items[0] + "/"); parts[1]=(items[1] + "/"); parts[2]=(items[2]); } else if (items.length > 3) { parts[0]=("http://:" + items[0] + "/"); String middlePath = ""; int i = 0; for (i = 1; i < items.length - 1; i++) middlePath += items[i] + "/"; parts[1]=(middlePath); parts[2]=(items[i]); } return parts; }
diff --git a/src/main/java/br/com/caelum/tubaina/parser/html/CenteredParagraphTag.java b/src/main/java/br/com/caelum/tubaina/parser/html/CenteredParagraphTag.java index d6841da..6968f6c 100644 --- a/src/main/java/br/com/caelum/tubaina/parser/html/CenteredParagraphTag.java +++ b/src/main/java/br/com/caelum/tubaina/parser/html/CenteredParagraphTag.java @@ -1,11 +1,11 @@ package br.com.caelum.tubaina.parser.html; import br.com.caelum.tubaina.parser.Tag; public class CenteredParagraphTag implements Tag { public String parse(String string, String options) { - return "<div style=\"text-align:center\">" + string + "</div>"; + return "<p class=\"center\">" + string + "</p>"; } }
true
true
public String parse(String string, String options) { return "<div style=\"text-align:center\">" + string + "</div>"; }
public String parse(String string, String options) { return "<p class=\"center\">" + string + "</p>"; }
diff --git a/ripple-core/src/main/java/net/fortytwo/ripple/model/RippleList.java b/ripple-core/src/main/java/net/fortytwo/ripple/model/RippleList.java index a186727c..d846b682 100644 --- a/ripple-core/src/main/java/net/fortytwo/ripple/model/RippleList.java +++ b/ripple-core/src/main/java/net/fortytwo/ripple/model/RippleList.java @@ -1,242 +1,242 @@ /* * $URL$ * $Revision$ * $Author$ * * Copyright (C) 2007-2012 Joshua Shinavier */ package net.fortytwo.ripple.model; import net.fortytwo.ripple.ListNode; import net.fortytwo.ripple.RippleException; import net.fortytwo.ripple.io.RipplePrintStream; import java.util.LinkedList; import java.util.List; /** * The head of a linked-list data structure holding <code>RippleValue</code>s. */ public abstract class RippleList extends ListNode<RippleValue> implements RippleValue { // Constants private static boolean initialized = false; protected RippleValue first; protected final RippleList rest; protected RippleList(final RippleValue first, final RippleList rest) { this.first = first; this.rest = rest; } @Override public RippleValue getFirst() { return first; } @Override public RippleList getRest() { return rest; } public abstract void setRDF(final RDFValue id); /** * @return the number of items in this list. * This is purely a convenience method. */ public int length() { int l = 0; ListNode<RippleValue> cur = this; while (!cur.isNil()) { l++; cur = cur.getRest(); } return l; } /** * Gets the item at the specified index in the list. * This is purely a convenience method. * * @param i an index into the list, where the index 0 corresponds to the first item in the list * @return the corresponding list item * @throws RippleException if retrieval from the list fails */ public RippleValue get(final int i) throws RippleException { if (i < 0) { throw new RippleException("list index out of bounds: " + i); } ListNode<RippleValue> cur = this; for (int j = 0; j < i; j++) { if (cur.isNil()) { throw new RippleException("list index out of bounds: " + i); } cur = cur.getRest(); } return cur.getFirst(); } public abstract RippleList push(RippleValue v) throws RippleException; public abstract RippleList invert(); public abstract RippleList concat(final RippleList tail); private static void initialize() throws RippleException { initialized = true; } public String toString() { if (!initialized) { try { initialize(); } catch (RippleException e) { initialized = true; e.logError(); } } StringBuilder sb = new StringBuilder(); ListNode<RippleValue> cur = this; sb.append("("); boolean isFirst = true; while (!cur.isNil()) { RippleValue val = cur.getFirst(); if (isFirst) { isFirst = false; } else { sb.append(" "); } if (Operator.OP == val) { sb.append("op"); } else { sb.append(val); } cur = cur.getRest(); } sb.append(")"); return sb.toString(); } public void printTo(final RipplePrintStream p) throws RippleException { printTo(p, true); } // Note: assumes diagrammatic order public void printTo(final RipplePrintStream p, final boolean includeParentheses) throws RippleException { if (!initialized) { initialize(); } ListNode<RippleValue> cur = this; if (includeParentheses) { - p.print(")"); + p.print("("); } boolean isFirst = true; while (!cur.isNil()) { RippleValue val = cur.getFirst(); if (Operator.OP == val) { p.print("."); } else { if (!isFirst) { p.print(" "); } p.print(val); } if (isFirst) { isFirst = false; } cur = cur.getRest(); } if (includeParentheses) { p.print(")"); } } /** * @return a Java list of the items in this list. This is purely a convenience method. */ public List<RippleValue> toJavaList() { LinkedList<RippleValue> javaList = new LinkedList<RippleValue>(); ListNode<RippleValue> cur = this; while (!cur.isNil()) { javaList.addLast(cur.getFirst()); cur = cur.getRest(); } return javaList; } public boolean equals(final Object other) { if (other instanceof RippleList) { ListNode<RippleValue> cur = this; ListNode<RippleValue> cur2 = (RippleList) other; while (!cur.isNil()) { if (cur2.isNil()) { return false; } if (!cur.getFirst().equals(cur2.getFirst())) { return false; } cur = cur.getRest(); cur2 = cur2.getRest(); } return cur2.isNil(); } else { return false; } } public int hashCode() { int code = 1320672831; int pow = 2; ListNode<RippleValue> cur = this; while (!cur.isNil()) { code += pow * cur.getFirst().hashCode(); pow *= 2; cur = cur.getRest(); } return code; } public Type getType() { return Type.LIST; } }
true
true
public void printTo(final RipplePrintStream p, final boolean includeParentheses) throws RippleException { if (!initialized) { initialize(); } ListNode<RippleValue> cur = this; if (includeParentheses) { p.print(")"); } boolean isFirst = true; while (!cur.isNil()) { RippleValue val = cur.getFirst(); if (Operator.OP == val) { p.print("."); } else { if (!isFirst) { p.print(" "); } p.print(val); } if (isFirst) { isFirst = false; } cur = cur.getRest(); } if (includeParentheses) { p.print(")"); } }
public void printTo(final RipplePrintStream p, final boolean includeParentheses) throws RippleException { if (!initialized) { initialize(); } ListNode<RippleValue> cur = this; if (includeParentheses) { p.print("("); } boolean isFirst = true; while (!cur.isNil()) { RippleValue val = cur.getFirst(); if (Operator.OP == val) { p.print("."); } else { if (!isFirst) { p.print(" "); } p.print(val); } if (isFirst) { isFirst = false; } cur = cur.getRest(); } if (includeParentheses) { p.print(")"); } }
diff --git a/src/tempconverter/TempConverter.java b/src/tempconverter/TempConverter.java index 8375c52..dfd084a 100644 --- a/src/tempconverter/TempConverter.java +++ b/src/tempconverter/TempConverter.java @@ -1,34 +1,34 @@ //Opgave 2.4, bogen side 137 package tempconverter; import java.util.Scanner; /** * * @author Kim Vammen */ public class TempConverter { public static void main(String[] args) { final int BASE = 32; final double CONVERSION_FACTOR = 9.0 / 5.0; double fahrenheitTemp; String celsiusTemp; - System.out.println("Eter the temperature in celsius: "); + System.out.println("Enter the temperature in celsius: "); Scanner scan = new Scanner (System.in); celsiusTemp = scan.nextLine(); int ctemp = Integer.parseInt(celsiusTemp); System.out.println("You entered the following temerature in celsius: " + ctemp); fahrenheitTemp = ctemp * CONVERSION_FACTOR + BASE; System.out.println("Celsius Temperature: " + celsiusTemp); System.out.println("Fahrenheit Equivalent: " + fahrenheitTemp); } }
true
true
public static void main(String[] args) { final int BASE = 32; final double CONVERSION_FACTOR = 9.0 / 5.0; double fahrenheitTemp; String celsiusTemp; System.out.println("Eter the temperature in celsius: "); Scanner scan = new Scanner (System.in); celsiusTemp = scan.nextLine(); int ctemp = Integer.parseInt(celsiusTemp); System.out.println("You entered the following temerature in celsius: " + ctemp); fahrenheitTemp = ctemp * CONVERSION_FACTOR + BASE; System.out.println("Celsius Temperature: " + celsiusTemp); System.out.println("Fahrenheit Equivalent: " + fahrenheitTemp); }
public static void main(String[] args) { final int BASE = 32; final double CONVERSION_FACTOR = 9.0 / 5.0; double fahrenheitTemp; String celsiusTemp; System.out.println("Enter the temperature in celsius: "); Scanner scan = new Scanner (System.in); celsiusTemp = scan.nextLine(); int ctemp = Integer.parseInt(celsiusTemp); System.out.println("You entered the following temerature in celsius: " + ctemp); fahrenheitTemp = ctemp * CONVERSION_FACTOR + BASE; System.out.println("Celsius Temperature: " + celsiusTemp); System.out.println("Fahrenheit Equivalent: " + fahrenheitTemp); }
diff --git a/providers/netty/src/test/java/org/asynchttpclient/providers/netty/NettyAsyncResponseTest.java b/providers/netty/src/test/java/org/asynchttpclient/providers/netty/NettyAsyncResponseTest.java index 5a654d6ab..6d2b7b800 100644 --- a/providers/netty/src/test/java/org/asynchttpclient/providers/netty/NettyAsyncResponseTest.java +++ b/providers/netty/src/test/java/org/asynchttpclient/providers/netty/NettyAsyncResponseTest.java @@ -1,93 +1,93 @@ /* * Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package org.asynchttpclient.providers.netty; import static org.testng.Assert.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; import org.asynchttpclient.FluentCaseInsensitiveStringsMap; import org.asynchttpclient.HttpResponseHeaders; import org.asynchttpclient.cookie.Cookie; import org.asynchttpclient.providers.netty.response.NettyResponse; import org.asynchttpclient.providers.netty.response.ResponseStatus; import org.testng.annotations.Test; /** * @author Benjamin Hanzelmann */ public class NettyAsyncResponseTest { @Test(groups = "standalone") public void testCookieParseExpires() { // e.g. "Sun, 06-Feb-2012 03:45:24 GMT"; SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); - Date date = new Date(System.currentTimeMillis() + 60000); // sdf.parse( dateString ); + Date date = new Date(System.currentTimeMillis() + 60000); final String cookieDef = String.format("efmembercheck=true; expires=%s; path=/; domain=.eclipse.org", sdf.format(date)); - NettyResponse - response = new NettyResponse(new ResponseStatus(null, null, null), new HttpResponseHeaders() { + NettyResponse response = new NettyResponse(new ResponseStatus(null, null, null), new HttpResponseHeaders() { @Override public FluentCaseInsensitiveStringsMap getHeaders() { return new FluentCaseInsensitiveStringsMap().add("Set-Cookie", cookieDef); } }, null, null); List<Cookie> cookies = response.getCookies(); assertEquals(cookies.size(), 1); Cookie cookie = cookies.get(0); - assertTrue(cookie.getMaxAge() > 55 && cookie.getMaxAge() < 61, ""); + long originalDateWith1SecPrecision = date.getTime() / 1000 * 1000; + assertEquals(cookie.getExpires(), originalDateWith1SecPrecision); } @Test(groups = "standalone") public void testCookieParseMaxAge() { final String cookieDef = "efmembercheck=true; max-age=60; path=/; domain=.eclipse.org"; NettyResponse response = new NettyResponse(new ResponseStatus(null, null, null), new HttpResponseHeaders() { @Override public FluentCaseInsensitiveStringsMap getHeaders() { return new FluentCaseInsensitiveStringsMap().add("Set-Cookie", cookieDef); } }, null, null); List<Cookie> cookies = response.getCookies(); assertEquals(cookies.size(), 1); Cookie cookie = cookies.get(0); assertEquals(cookie.getMaxAge(), 60); } @Test(groups = "standalone") public void testCookieParseWeirdExpiresValue() { final String cookieDef = "efmembercheck=true; expires=60; path=/; domain=.eclipse.org"; NettyResponse response = new NettyResponse(new ResponseStatus(null, null, null), new HttpResponseHeaders() { @Override public FluentCaseInsensitiveStringsMap getHeaders() { return new FluentCaseInsensitiveStringsMap().add("Set-Cookie", cookieDef); } }, null, null); List<Cookie> cookies = response.getCookies(); assertEquals(cookies.size(), 1); Cookie cookie = cookies.get(0); assertEquals(cookie.getMaxAge(), -1); } }
false
true
public void testCookieParseExpires() { // e.g. "Sun, 06-Feb-2012 03:45:24 GMT"; SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = new Date(System.currentTimeMillis() + 60000); // sdf.parse( dateString ); final String cookieDef = String.format("efmembercheck=true; expires=%s; path=/; domain=.eclipse.org", sdf.format(date)); NettyResponse response = new NettyResponse(new ResponseStatus(null, null, null), new HttpResponseHeaders() { @Override public FluentCaseInsensitiveStringsMap getHeaders() { return new FluentCaseInsensitiveStringsMap().add("Set-Cookie", cookieDef); } }, null, null); List<Cookie> cookies = response.getCookies(); assertEquals(cookies.size(), 1); Cookie cookie = cookies.get(0); assertTrue(cookie.getMaxAge() > 55 && cookie.getMaxAge() < 61, ""); }
public void testCookieParseExpires() { // e.g. "Sun, 06-Feb-2012 03:45:24 GMT"; SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = new Date(System.currentTimeMillis() + 60000); final String cookieDef = String.format("efmembercheck=true; expires=%s; path=/; domain=.eclipse.org", sdf.format(date)); NettyResponse response = new NettyResponse(new ResponseStatus(null, null, null), new HttpResponseHeaders() { @Override public FluentCaseInsensitiveStringsMap getHeaders() { return new FluentCaseInsensitiveStringsMap().add("Set-Cookie", cookieDef); } }, null, null); List<Cookie> cookies = response.getCookies(); assertEquals(cookies.size(), 1); Cookie cookie = cookies.get(0); long originalDateWith1SecPrecision = date.getTime() / 1000 * 1000; assertEquals(cookie.getExpires(), originalDateWith1SecPrecision); }
diff --git a/src/main/java/org/openmrs/module/mirebalais/smoke/pageobjects/AppDashboard.java b/src/main/java/org/openmrs/module/mirebalais/smoke/pageobjects/AppDashboard.java index 53ffa6d..26ce45f 100644 --- a/src/main/java/org/openmrs/module/mirebalais/smoke/pageobjects/AppDashboard.java +++ b/src/main/java/org/openmrs/module/mirebalais/smoke/pageobjects/AppDashboard.java @@ -1,96 +1,96 @@ /* * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.mirebalais.smoke.pageobjects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.ArrayList; import java.util.List; public class AppDashboard extends AbstractPageObject { public static final String ARCHIVES_ROOM = "emr-archivesRoom-app"; public static final String PATIENT_REGISTRATION_AND_CHECK_IN = "patientregistration-main-app"; public static final String FIND_PATIENT = "emr-findPatient-app"; public static final String SYSTEM_ADMINISTRATION = "emr-systemAdministration-app"; public static final String ACTIVE_VISITS = "emr-activeVisits-app"; public AppDashboard(WebDriver driver) { super(driver); } public void openActiveVisitsApp() { driver.get(properties.getWebAppUrl()); clickAppButton(ACTIVE_VISITS); } public void openArchivesRoomApp() { driver.get(properties.getWebAppUrl()); clickAppButton(ARCHIVES_ROOM); } public void openPatientRegistrationApp() { driver.get(properties.getWebAppUrl()); clickAppButton(PATIENT_REGISTRATION_AND_CHECK_IN); } public void openSysAdminApp() { driver.get(properties.getWebAppUrl()); clickAppButton(SYSTEM_ADMINISTRATION); } public boolean isPatientRegistrationAppPresented() { return isAppButtonPresent(PATIENT_REGISTRATION_AND_CHECK_IN); } public boolean isArchivesRoomAppPresented() { return isAppButtonPresent(ARCHIVES_ROOM); } public boolean isSystemAdministrationAppPresented() { return isAppButtonPresent(SYSTEM_ADMINISTRATION); } public boolean isFindAPatientAppPresented() { return isAppButtonPresent(FIND_PATIENT); } public boolean isActiveVisitsAppPresented() { return isAppButtonPresent(ACTIVE_VISITS); } public List<String> getAppsNames() { List<String> appsNames = new ArrayList<String>(); - List<WebElement> apps = driver.findElements(By.cssSelector(".apps a")); + List<WebElement> apps = driver.findElements(By.xpath("//div[@id='apps']/a")); for(WebElement app: apps) { appsNames.add(app.getText()); } return appsNames; } private void clickAppButton(String appId) { driver.findElement(By.id(appId)).click(); } private boolean isAppButtonPresent(String appId) { try { return driver.findElement(By.id(appId)) != null; } catch (Exception ex) { return false; } } }
true
true
public List<String> getAppsNames() { List<String> appsNames = new ArrayList<String>(); List<WebElement> apps = driver.findElements(By.cssSelector(".apps a")); for(WebElement app: apps) { appsNames.add(app.getText()); } return appsNames; }
public List<String> getAppsNames() { List<String> appsNames = new ArrayList<String>(); List<WebElement> apps = driver.findElements(By.xpath("//div[@id='apps']/a")); for(WebElement app: apps) { appsNames.add(app.getText()); } return appsNames; }
diff --git a/src/main/java/com/example/Main.java b/src/main/java/com/example/Main.java index 8036f00..458e85b 100644 --- a/src/main/java/com/example/Main.java +++ b/src/main/java/com/example/Main.java @@ -1,48 +1,49 @@ package com.example; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.WebAppContext; /** * * This class launches the web application in an embedded Jetty container. * This is the entry point to your application. The Java command that is used for * launching should fire this main method. * */ public class Main { /** * @param args */ public static void main(String[] args) throws Exception{ String webappDirLocation = "src/main/webapp/"; //The port that we should run on can be set into an environment variable //Look for that variable and default to 8080 if it isn't there. String webPort = System.getenv("PORT"); if(webPort == null || webPort.isEmpty()) { webPort = "8080"; } Server server = new Server(Integer.valueOf(webPort)); WebAppContext root = new WebAppContext(); root.setContextPath("/"); + root.setDefaultsDescriptor("etc/webdefault.xml"); root.setDescriptor(webappDirLocation+"/WEB-INF/web.xml"); root.setResourceBase(webappDirLocation); //Parent loader priority is a class loader setting that Jetty accepts. //By default Jetty will behave like most web containers in that it will //allow your application to replace non-server libraries that are part of the //container. Setting parent loader priority to true changes this behavior. //Read more here: http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading root.setParentLoaderPriority(true); server.setHandler(root); server.start(); server.join(); } }
true
true
public static void main(String[] args) throws Exception{ String webappDirLocation = "src/main/webapp/"; //The port that we should run on can be set into an environment variable //Look for that variable and default to 8080 if it isn't there. String webPort = System.getenv("PORT"); if(webPort == null || webPort.isEmpty()) { webPort = "8080"; } Server server = new Server(Integer.valueOf(webPort)); WebAppContext root = new WebAppContext(); root.setContextPath("/"); root.setDescriptor(webappDirLocation+"/WEB-INF/web.xml"); root.setResourceBase(webappDirLocation); //Parent loader priority is a class loader setting that Jetty accepts. //By default Jetty will behave like most web containers in that it will //allow your application to replace non-server libraries that are part of the //container. Setting parent loader priority to true changes this behavior. //Read more here: http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading root.setParentLoaderPriority(true); server.setHandler(root); server.start(); server.join(); }
public static void main(String[] args) throws Exception{ String webappDirLocation = "src/main/webapp/"; //The port that we should run on can be set into an environment variable //Look for that variable and default to 8080 if it isn't there. String webPort = System.getenv("PORT"); if(webPort == null || webPort.isEmpty()) { webPort = "8080"; } Server server = new Server(Integer.valueOf(webPort)); WebAppContext root = new WebAppContext(); root.setContextPath("/"); root.setDefaultsDescriptor("etc/webdefault.xml"); root.setDescriptor(webappDirLocation+"/WEB-INF/web.xml"); root.setResourceBase(webappDirLocation); //Parent loader priority is a class loader setting that Jetty accepts. //By default Jetty will behave like most web containers in that it will //allow your application to replace non-server libraries that are part of the //container. Setting parent loader priority to true changes this behavior. //Read more here: http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading root.setParentLoaderPriority(true); server.setHandler(root); server.start(); server.join(); }
diff --git a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/security/jaas/PropertiesLoginModule.java b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/security/jaas/PropertiesLoginModule.java index 054dd6025..7b103936a 100644 --- a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/security/jaas/PropertiesLoginModule.java +++ b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/security/jaas/PropertiesLoginModule.java @@ -1,168 +1,168 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.core.security.jaas; import org.apache.openejb.util.ConfUtils; import org.apache.openejb.util.LogCategory; import org.apache.openejb.util.Logger; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.FailedLoginException; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; /** * @version $Rev$ $Date$ */ public class PropertiesLoginModule implements LoginModule { private final String USER_FILE = "UsersFile"; private final String GROUP_FILE = "GroupsFile"; private static Logger log = Logger.getInstance(LogCategory.OPENEJB_SECURITY, "org.apache.openejb.util.resources"); private Subject subject; private CallbackHandler callbackHandler; private boolean debug; private Properties users = new Properties(); private Properties groups = new Properties(); private String user; private Set principals = new HashSet(); private URL usersUrl; private URL groupsUrl; public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { this.subject = subject; this.callbackHandler = callbackHandler; debug = "true".equalsIgnoreCase((String) options.get("Debug")); String usersFile = (String) options.get(USER_FILE) + ""; String groupsFile = (String) options.get(GROUP_FILE) + ""; usersUrl = ConfUtils.getConfResource(usersFile); groupsUrl = ConfUtils.getConfResource(groupsFile); if (debug) { log.debug("Initialized debug=" + debug + " usersFile=" + usersFile + " groupsFile=" + groupsFile); } } public boolean login() throws LoginException { try { users.load(usersUrl.openStream()); } catch (IOException ioe) { throw new LoginException("Unable to load user properties file " + usersUrl.getFile()); } try { groups.load(groupsUrl.openStream()); } catch (IOException ioe) { throw new LoginException("Unable to load group properties file " + groupsUrl.getFile()); } Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("Username: "); callbacks[1] = new PasswordCallback("Password: ", false); try { callbackHandler.handle(callbacks); } catch (IOException ioe) { throw new LoginException(ioe.getMessage()); } catch (UnsupportedCallbackException uce) { throw new LoginException(uce.getMessage() + " not available to obtain information from user"); } user = ((NameCallback) callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); if (tmpPassword == null) tmpPassword = new char[0]; String password = users.getProperty(user); - if (password == null) throw new FailedLoginException("User does exist"); + if (password == null) throw new FailedLoginException("User does not exist"); if (!password.equals(new String(tmpPassword))) throw new FailedLoginException("Password does not match"); users.clear(); if (debug) { log.debug("login " + user); } return true; } public boolean commit() throws LoginException { principals.add(new UserPrincipal(user)); for (Enumeration enumeration = groups.keys(); enumeration.hasMoreElements();) { String name = (String) enumeration.nextElement(); String[] userList = ((String) groups.getProperty(name) + "").split(","); for (int i = 0; i < userList.length; i++) { if (user.equals(userList[i])) { principals.add(new GroupPrincipal(name)); break; } } } subject.getPrincipals().addAll(principals); clear(); if (debug) { log.debug("commit"); } return true; } public boolean abort() throws LoginException { clear(); if (debug) { log.debug("abort"); } return true; } public boolean logout() throws LoginException { subject.getPrincipals().removeAll(principals); principals.clear(); if (debug) { log.debug("logout"); } return true; } private void clear() { groups.clear(); user = null; } }
true
true
public boolean login() throws LoginException { try { users.load(usersUrl.openStream()); } catch (IOException ioe) { throw new LoginException("Unable to load user properties file " + usersUrl.getFile()); } try { groups.load(groupsUrl.openStream()); } catch (IOException ioe) { throw new LoginException("Unable to load group properties file " + groupsUrl.getFile()); } Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("Username: "); callbacks[1] = new PasswordCallback("Password: ", false); try { callbackHandler.handle(callbacks); } catch (IOException ioe) { throw new LoginException(ioe.getMessage()); } catch (UnsupportedCallbackException uce) { throw new LoginException(uce.getMessage() + " not available to obtain information from user"); } user = ((NameCallback) callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); if (tmpPassword == null) tmpPassword = new char[0]; String password = users.getProperty(user); if (password == null) throw new FailedLoginException("User does exist"); if (!password.equals(new String(tmpPassword))) throw new FailedLoginException("Password does not match"); users.clear(); if (debug) { log.debug("login " + user); } return true; }
public boolean login() throws LoginException { try { users.load(usersUrl.openStream()); } catch (IOException ioe) { throw new LoginException("Unable to load user properties file " + usersUrl.getFile()); } try { groups.load(groupsUrl.openStream()); } catch (IOException ioe) { throw new LoginException("Unable to load group properties file " + groupsUrl.getFile()); } Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("Username: "); callbacks[1] = new PasswordCallback("Password: ", false); try { callbackHandler.handle(callbacks); } catch (IOException ioe) { throw new LoginException(ioe.getMessage()); } catch (UnsupportedCallbackException uce) { throw new LoginException(uce.getMessage() + " not available to obtain information from user"); } user = ((NameCallback) callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); if (tmpPassword == null) tmpPassword = new char[0]; String password = users.getProperty(user); if (password == null) throw new FailedLoginException("User does not exist"); if (!password.equals(new String(tmpPassword))) throw new FailedLoginException("Password does not match"); users.clear(); if (debug) { log.debug("login " + user); } return true; }
diff --git a/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/general/SeadasFileUtils.java b/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/general/SeadasFileUtils.java index a8b0ebae..7d482e6c 100644 --- a/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/general/SeadasFileUtils.java +++ b/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/general/SeadasFileUtils.java @@ -1,111 +1,111 @@ package gov.nasa.gsfc.seadas.processing.general; import org.esa.beam.util.Debug; import org.esa.beam.visat.VisatApp; import java.io.File; import java.text.SimpleDateFormat; import java.util.Calendar; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 6/20/12 * Time: 2:46 PM * To change this template use File | Settings | File Templates. */ public class SeadasFileUtils { private static boolean debug = false; public static String getCurrentDate(String dateFormat) { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); return sdf.format(cal.getTime()); } public static String getGeoFileNameFromIFile(String ifileName) { String geoFileName = (ifileName.substring(0, ifileName.indexOf("."))).concat(".GEO"); if (new File(geoFileName).exists()) { return geoFileName; } else { VisatApp.getApp().showErrorDialog(ifileName + " requires a GEO file to be extracted. " + geoFileName + " does not exist."); return null; } } public static String getDefaultOFileNameFromIFile(String ifileName, String programName) { debug("Program name is " + programName); Debug.assertNotNull(ifileName); ProcessorTypeInfo.ProcessorID processorID = ProcessorTypeInfo.getProcessorID(programName); String ofileName = ifileName + "_" + programName + ".out"; switch (processorID) { case EXTRACTOR: ofileName = ifileName + ".sub"; break; case MODIS_L1A_PY: //FileUtils.exchangeExtension(ifileName, "GEO") ; break; case MODIS_GEO_PY: ofileName = ifileName.replaceAll("L1A_LAC", "GEO"); break; case L1BGEN: ofileName = ifileName.replaceAll("L1A", "L1B"); break; case MODIS_L1B_PY: ofileName = ifileName.replaceAll("L1A", "L1B"); break; case L1BRSGEN: ofileName = ifileName + ".BRS"; break; case L2BRSGEN: ofileName = ifileName + ".BRS"; break; case L1MAPGEN: ofileName = ifileName + "_" + programName + ".out"; break; case L2MAPGEN: ofileName = ifileName + "_" + programName + ".out"; break; case L2BIN: ofileName = ifileName.replaceAll("L2_.{3,}", "L3b_DAY"); break; case L3BIN: ofileName = ifileName.replaceAll("L2_.{3,}", "L3b_DAY"); ; break; case SMIGEN: - ofileName = ifileName.replaceAll("L3B", "L3M"); - ofileName = ofileName.replaceAll("L3b", "L3M"); + ofileName = ifileName.replaceAll("L3B", "L3m"); + ofileName = ofileName.replaceAll("L3b", "L3m"); ofileName = ofileName.replaceAll(".main", ""); break; case SMITOPPM: ofileName = ifileName.trim().length() > 0 ? ifileName + ".ppm" : ""; break; } return ofileName; } public static void main(String arg[]) { System.out.println(getCurrentDate("dd MMMMM yyyy")); System.out.println(getCurrentDate("yyyyMMdd")); System.out.println(getCurrentDate("dd.MM.yy")); System.out.println(getCurrentDate("MM/dd/yy")); System.out.println(getCurrentDate("yyyy.MM.dd G 'at' hh:mm:ss z")); System.out.println(getCurrentDate("EEE, MMM d, ''yy")); System.out.println(getCurrentDate("h:mm a")); System.out.println(getCurrentDate("H:mm:ss:SSS")); System.out.println(getCurrentDate("K:mm a,z")); System.out.println(getCurrentDate("yyyy.MMMMM.dd GGG hh:mm aaa")); } public static void debug(String message) { if (debug) { System.out.println("Debugging: " + message); } } }
true
true
public static String getDefaultOFileNameFromIFile(String ifileName, String programName) { debug("Program name is " + programName); Debug.assertNotNull(ifileName); ProcessorTypeInfo.ProcessorID processorID = ProcessorTypeInfo.getProcessorID(programName); String ofileName = ifileName + "_" + programName + ".out"; switch (processorID) { case EXTRACTOR: ofileName = ifileName + ".sub"; break; case MODIS_L1A_PY: //FileUtils.exchangeExtension(ifileName, "GEO") ; break; case MODIS_GEO_PY: ofileName = ifileName.replaceAll("L1A_LAC", "GEO"); break; case L1BGEN: ofileName = ifileName.replaceAll("L1A", "L1B"); break; case MODIS_L1B_PY: ofileName = ifileName.replaceAll("L1A", "L1B"); break; case L1BRSGEN: ofileName = ifileName + ".BRS"; break; case L2BRSGEN: ofileName = ifileName + ".BRS"; break; case L1MAPGEN: ofileName = ifileName + "_" + programName + ".out"; break; case L2MAPGEN: ofileName = ifileName + "_" + programName + ".out"; break; case L2BIN: ofileName = ifileName.replaceAll("L2_.{3,}", "L3b_DAY"); break; case L3BIN: ofileName = ifileName.replaceAll("L2_.{3,}", "L3b_DAY"); ; break; case SMIGEN: ofileName = ifileName.replaceAll("L3B", "L3M"); ofileName = ofileName.replaceAll("L3b", "L3M"); ofileName = ofileName.replaceAll(".main", ""); break; case SMITOPPM: ofileName = ifileName.trim().length() > 0 ? ifileName + ".ppm" : ""; break; } return ofileName; }
public static String getDefaultOFileNameFromIFile(String ifileName, String programName) { debug("Program name is " + programName); Debug.assertNotNull(ifileName); ProcessorTypeInfo.ProcessorID processorID = ProcessorTypeInfo.getProcessorID(programName); String ofileName = ifileName + "_" + programName + ".out"; switch (processorID) { case EXTRACTOR: ofileName = ifileName + ".sub"; break; case MODIS_L1A_PY: //FileUtils.exchangeExtension(ifileName, "GEO") ; break; case MODIS_GEO_PY: ofileName = ifileName.replaceAll("L1A_LAC", "GEO"); break; case L1BGEN: ofileName = ifileName.replaceAll("L1A", "L1B"); break; case MODIS_L1B_PY: ofileName = ifileName.replaceAll("L1A", "L1B"); break; case L1BRSGEN: ofileName = ifileName + ".BRS"; break; case L2BRSGEN: ofileName = ifileName + ".BRS"; break; case L1MAPGEN: ofileName = ifileName + "_" + programName + ".out"; break; case L2MAPGEN: ofileName = ifileName + "_" + programName + ".out"; break; case L2BIN: ofileName = ifileName.replaceAll("L2_.{3,}", "L3b_DAY"); break; case L3BIN: ofileName = ifileName.replaceAll("L2_.{3,}", "L3b_DAY"); ; break; case SMIGEN: ofileName = ifileName.replaceAll("L3B", "L3m"); ofileName = ofileName.replaceAll("L3b", "L3m"); ofileName = ofileName.replaceAll(".main", ""); break; case SMITOPPM: ofileName = ifileName.trim().length() > 0 ? ifileName + ".ppm" : ""; break; } return ofileName; }
diff --git a/backend/skynet_backend/src/test/java/toctep/skynet/backend/test/CountryTest.java b/backend/skynet_backend/src/test/java/toctep/skynet/backend/test/CountryTest.java index 2cc5622..036d594 100644 --- a/backend/skynet_backend/src/test/java/toctep/skynet/backend/test/CountryTest.java +++ b/backend/skynet_backend/src/test/java/toctep/skynet/backend/test/CountryTest.java @@ -1,40 +1,40 @@ package toctep.skynet.backend.test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import toctep.skynet.backend.dal.domain.Country; public class CountryTest extends DomainTest{ @Override public void testCreate() { Country country = new Country(); assertNotNull(country); String code = "NL"; country.setCode(code); assertTrue(code.equals(country.getCode())); String text = "Netherlands"; - country.setCode(text); + country.setText(text); assertTrue(text.equals(country.getText())); } @Override public void testDelete() { // TODO Auto-generated method stub } @Override public void testInsert() { // TODO Auto-generated method stub } @Override public void testUpdate() { // TODO Auto-generated method stub } }
true
true
public void testCreate() { Country country = new Country(); assertNotNull(country); String code = "NL"; country.setCode(code); assertTrue(code.equals(country.getCode())); String text = "Netherlands"; country.setCode(text); assertTrue(text.equals(country.getText())); }
public void testCreate() { Country country = new Country(); assertNotNull(country); String code = "NL"; country.setCode(code); assertTrue(code.equals(country.getCode())); String text = "Netherlands"; country.setText(text); assertTrue(text.equals(country.getText())); }
diff --git a/hama/hybrid/onlinecf/src/at/illecker/hama/hybrid/examples/onlinecf/OnlineCFTrainHybridBSP.java b/hama/hybrid/onlinecf/src/at/illecker/hama/hybrid/examples/onlinecf/OnlineCFTrainHybridBSP.java index 2d53deb..cd52f24 100644 --- a/hama/hybrid/onlinecf/src/at/illecker/hama/hybrid/examples/onlinecf/OnlineCFTrainHybridBSP.java +++ b/hama/hybrid/onlinecf/src/at/illecker/hama/hybrid/examples/onlinecf/OnlineCFTrainHybridBSP.java @@ -1,841 +1,841 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.illecker.hama.hybrid.examples.onlinecf; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.SequenceFile.CompressionType; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hama.Constants; import org.apache.hama.HamaConfiguration; import org.apache.hama.bsp.BSPJob; import org.apache.hama.bsp.BSPJobClient; import org.apache.hama.bsp.BSPPeer; import org.apache.hama.bsp.ClusterStatus; import org.apache.hama.bsp.FileOutputFormat; import org.apache.hama.bsp.HashPartitioner; import org.apache.hama.bsp.SequenceFileInputFormat; import org.apache.hama.bsp.SequenceFileOutputFormat; import org.apache.hama.bsp.gpu.HybridBSP; import org.apache.hama.bsp.sync.SyncException; import org.apache.hama.commons.io.PipesVectorWritable; import org.apache.hama.commons.math.DenseDoubleVector; import org.apache.hama.commons.math.DoubleMatrix; import org.apache.hama.commons.math.DoubleVector; import org.apache.hama.ml.recommendation.Preference; import org.apache.hama.ml.recommendation.cf.function.MeanAbsError; import org.apache.hama.ml.recommendation.cf.function.OnlineUpdate; import org.trifort.rootbeer.runtime.Context; import org.trifort.rootbeer.runtime.Rootbeer; import org.trifort.rootbeer.runtime.StatsRow; import org.trifort.rootbeer.runtime.util.Stopwatch; public class OnlineCFTrainHybridBSP extends HybridBSP<IntWritable, PipesVectorWritable, Text, PipesVectorWritable, ItemMessage> { private static final Log LOG = LogFactory .getLog(OnlineCFTrainHybridBSP.class); private static final Path CONF_TMP_DIR = new Path( "output/hama/hybrid/examples/onlinecf/hybrid-" + System.currentTimeMillis()); private static final Path CONF_INPUT_DIR = new Path(CONF_TMP_DIR, "input"); private static final Path CONF_OUTPUT_DIR = new Path(CONF_TMP_DIR, "output"); public static final String CONF_BLOCKSIZE = "onlinecf.hybrid.blockSize"; public static final String CONF_GRIDSIZE = "onlinecf.hybrid.gridSize"; public static final String CONF_DEBUG = "onlinecf.is.debugging"; // gridSize = amount of blocks and multiprocessors public static final int GRID_SIZE = 14; // blockSize = amount of threads public static final int BLOCK_SIZE = 1024; public long m_setupTimeCpu = 0; public long m_setupTimeGpu = 0; public long m_bspTimeCpu = 0; public long m_bspTimeGpu = 0; private Configuration m_conf; private boolean m_isDebuggingEnabled; private FSDataOutputStream m_logger; private int m_gridSize; private int m_blockSize; // OnlineCF members private int m_maxIterations = 0; private int m_matrix_rank = 0; private int m_skip_count = 0; private String m_inputPreferenceDelim = null; private String m_inputUserDelim = null; private String m_inputItemDelim = null; // Input Preferences private ArrayList<Preference<Integer, Long>> m_preferences = new ArrayList<Preference<Integer, Long>>(); private ArrayList<Integer> m_indexes = new ArrayList<Integer>(); // randomly generated depending on matrix rank, // will be computed runtime and represents trained model // userId, factorized value private HashMap<Integer, PipesVectorWritable> m_usersMatrix = new HashMap<Integer, PipesVectorWritable>(); // itemId, factorized value private HashMap<Long, PipesVectorWritable> m_itemsMatrix = new HashMap<Long, PipesVectorWritable>(); // matrixRank, factorized value private DoubleMatrix userFeatureMatrix = null; private DoubleMatrix itemFeatureMatrix = null; // obtained from input data // will not change during execution private HashMap<String, PipesVectorWritable> inpUsersFeatures = null; private HashMap<String, PipesVectorWritable> inpItemsFeatures = null; private OnlineUpdate.Function m_function = null; Random rnd = new Random(); /********************************* CPU *********************************/ @Override public void setup( BSPPeer<IntWritable, PipesVectorWritable, Text, PipesVectorWritable, ItemMessage> peer) throws IOException { long startTime = System.currentTimeMillis(); this.m_conf = peer.getConfiguration(); this.m_isDebuggingEnabled = m_conf.getBoolean(CONF_DEBUG, false); this.m_maxIterations = m_conf.getInt(OnlineCF.CONF_ITERATION_COUNT, OnlineCF.DFLT_ITERATION_COUNT); this.m_matrix_rank = m_conf.getInt(OnlineCF.CONF_MATRIX_RANK, OnlineCF.DFLT_MATRIX_RANK); this.m_skip_count = m_conf.getInt(OnlineCF.CONF_SKIP_COUNT, OnlineCF.DFLT_SKIP_COUNT); this.m_function = new MeanAbsError(); // Init logging if (m_isDebuggingEnabled) { try { FileSystem fs = FileSystem.get(m_conf); m_logger = fs.create(new Path(FileOutputFormat .getOutputPath(new BSPJob((HamaConfiguration) m_conf)) + "/BSP_" + peer.getTaskId() + ".log")); } catch (IOException e) { e.printStackTrace(); } } this.m_setupTimeCpu = System.currentTimeMillis() - startTime; } @Override public void bsp( BSPPeer<IntWritable, PipesVectorWritable, Text, PipesVectorWritable, ItemMessage> peer) throws IOException, SyncException, InterruptedException { int loggingPeer = 0; long startTime = System.currentTimeMillis(); HashSet<Text> requiredUserFeatures = null; HashSet<Text> requiredItemFeatures = null; LOG.info(peer.getPeerName() + ") collecting input data"); collectInput(peer); // TODO // REMOVED broadcast user features and item features LOG.info(peer.getPeerName() + ") collected: " + this.m_usersMatrix.size() + " users, " + this.m_itemsMatrix.size() + " items, " + this.m_preferences.size() + " preferences"); // DEBUG if (peer.getPeerIndex() == loggingPeer) { LOG.info(peer.getPeerName() + ") usersMatrix: length: " + this.m_usersMatrix.size()); for (Map.Entry<Integer, PipesVectorWritable> e : this.m_usersMatrix .entrySet()) { LOG.info(peer.getPeerName() + ") key: '" + e.getKey() + "' value: '" + e.getValue().toString() + "'"); } LOG.info(peer.getPeerName() + ") itemsMatrix: length: " + this.m_itemsMatrix.size()); for (Map.Entry<Long, PipesVectorWritable> e : this.m_itemsMatrix .entrySet()) { LOG.info(peer.getPeerName() + ") key: '" + e.getKey() + "' value: '" + e.getValue().toString() + "'"); } LOG.info(peer.getPeerName() + ") preferences: length: " + this.m_preferences.size()); for (Preference p : this.m_preferences) { LOG.info(peer.getPeerName() + ") userId: '" + p.getUserId() + "' itemId: '" + p.getItemId() + "' value: '" + p.getValue().get() + "'"); } LOG.info("indexes: length: " + this.m_indexes.size() + " indexes: " + Arrays.toString(this.m_indexes.toArray())); } // calculation steps for (int i = 0; i < m_maxIterations; i++) { computeValues(); // DEBUG if (peer.getPeerIndex() == loggingPeer) { LOG.info(peer.getPeerName() + ") usersMatrix: length: " + this.m_usersMatrix.size()); for (Map.Entry<Integer, PipesVectorWritable> e : this.m_usersMatrix .entrySet()) { LOG.info(peer.getPeerName() + ") key: '" + e.getKey() + "' value: '" + e.getValue().toString() + "'"); } LOG.info(peer.getPeerName() + ") itemsMatrix: length: " + this.m_itemsMatrix.size()); for (Map.Entry<Long, PipesVectorWritable> e : this.m_itemsMatrix .entrySet()) { LOG.info(peer.getPeerName() + ") key: '" + e.getKey() + "' value: '" + e.getValue().toString() + "'"); } LOG.info("indexes: length: " + this.m_indexes.size() + " indexes: " + Arrays.toString(this.m_indexes.toArray())); } if ((i + 1) % m_skip_count == 0) { // DEBUG if (peer.getPeerIndex() == loggingPeer) { LOG.info(peer.getPeerName() + ") normalizeWithBroadcastingValues: i: " + i); } normalizeWithBroadcastingValues(peer); } } // DEBUG if (peer.getPeerIndex() == loggingPeer) { LOG.info(peer.getPeerName() + ") usersMatrix: length: " + this.m_usersMatrix.size()); for (Map.Entry<Integer, PipesVectorWritable> e : this.m_usersMatrix .entrySet()) { LOG.info(peer.getPeerName() + ") key: '" + e.getKey() + "' value: '" + e.getValue().toString() + "'"); } LOG.info(peer.getPeerName() + ") itemsMatrix: length: " + this.m_itemsMatrix.size()); for (Map.Entry<Long, PipesVectorWritable> e : this.m_itemsMatrix .entrySet()) { LOG.info(peer.getPeerName() + ") key: '" + e.getKey() + "' value: '" + e.getValue().toString() + "'"); } } saveModel(peer); this.m_bspTimeCpu = System.currentTimeMillis() - startTime; if (m_isDebuggingEnabled) { m_logger.writeChars("OnlineTrainHybridBSP,setupTimeCpu=" + this.m_setupTimeCpu + " ms\n"); m_logger.writeChars("OnlineTrainHybridBSP,setupTimeCpu=" + (this.m_setupTimeCpu / 1000.0) + " seconds\n"); m_logger.writeChars("OnlineTrainHybridBSP,bspTimeCpu=" + this.m_bspTimeCpu + " ms\n"); m_logger.writeChars("OnlineTrainHybridBSP,bspTimeCpu=" + (this.m_bspTimeCpu / 1000.0) + " seconds\n"); m_logger.close(); } } private void collectInput( BSPPeer<IntWritable, PipesVectorWritable, Text, PipesVectorWritable, ItemMessage> peer) throws IOException { IntWritable key = new IntWritable(); PipesVectorWritable value = new PipesVectorWritable(); int counter = 0; while (peer.readNext(key, value)) { int actualId = key.get(); // parse as <k:userId, v:(itemId, score)> long itemId = (long) value.getVector().get(0); double score = value.getVector().get(1); if (m_usersMatrix.containsKey(actualId) == false) { DenseDoubleVector vals = new DenseDoubleVector(m_matrix_rank); for (int i = 0; i < m_matrix_rank; i++) { vals.set(i, rnd.nextDouble()); } m_usersMatrix.put(actualId, new PipesVectorWritable(vals)); } if (m_itemsMatrix.containsKey(itemId) == false) { DenseDoubleVector vals = new DenseDoubleVector(m_matrix_rank); for (int i = 0; i < m_matrix_rank; i++) { vals.set(i, rnd.nextDouble()); } m_itemsMatrix.put(itemId, new PipesVectorWritable(vals)); } m_preferences.add(new Preference<Integer, Long>(actualId, itemId, score)); m_indexes.add(counter); counter++; } } private void computeValues() { // shuffling indexes int idx = 0; int idxValue = 0; int tmp = 0; for (int i = m_indexes.size(); i > 0; i--) { idx = Math.abs(rnd.nextInt()) % i; idxValue = m_indexes.get(idx); tmp = m_indexes.get(i - 1); m_indexes.set(i - 1, idxValue); m_indexes.set(idx, tmp); } // compute values OnlineUpdate.InputStructure inp = new OnlineUpdate.InputStructure(); OnlineUpdate.OutputStructure out = null; Preference<Integer, Long> pref = null; for (Integer prefIdx : m_indexes) { pref = m_preferences.get(prefIdx); PipesVectorWritable userFactorizedValues = m_usersMatrix.get(pref .getUserId()); PipesVectorWritable itemFactorizedValues = m_itemsMatrix.get(pref .getItemId()); PipesVectorWritable userFeatures = (inpUsersFeatures != null) ? inpUsersFeatures .get(pref.getUserId()) : null; PipesVectorWritable itemFeatures = (inpItemsFeatures != null) ? inpItemsFeatures .get(pref.getItemId()) : null; inp.user = userFactorizedValues; inp.item = itemFactorizedValues; inp.expectedScore = pref.getValue(); inp.userFeatures = userFeatures; inp.itemFeatures = itemFeatures; inp.userFeatureFactorized = userFeatureMatrix; inp.itemFeatureFactorized = itemFeatureMatrix; out = m_function.compute(inp); m_usersMatrix.put(pref.getUserId(), new PipesVectorWritable( out.userFactorized)); m_itemsMatrix.put(pref.getItemId(), new PipesVectorWritable( out.itemFactorized)); userFeatureMatrix = out.userFeatureFactorized; itemFeatureMatrix = out.itemFeatureFactorized; } } private void normalizeWithBroadcastingValues( BSPPeer<IntWritable, PipesVectorWritable, Text, PipesVectorWritable, ItemMessage> peer) throws IOException, SyncException, InterruptedException { // normalize item factorized values // normalize user/item feature matrix // Step 1) // send item factorized matrices to selected peers int peerCount = peer.getNumPeers(); // item factorized values should be normalized int peerId = peer.getPeerIndex(); for (Map.Entry<Long, PipesVectorWritable> item : m_itemsMatrix.entrySet()) { peer.send(peer.getPeerName(item.getKey().hashCode() % peerCount), new ItemMessage(peerId, item.getKey().longValue(), item.getValue() .getVector())); } peer.sync(); // Step 2) // receive item factorized matrices if this peer is selected and normalize // them HashMap<Long, LinkedList<Integer>> senderList = new HashMap<Long, LinkedList<Integer>>(); HashMap<Long, DoubleVector> normalizedValues = new HashMap<Long, DoubleVector>(); HashMap<Long, Integer> normalizedValueCount = new HashMap<Long, Integer>(); ItemMessage msg; while ((msg = peer.getCurrentMessage()) != null) { int senderId = msg.getSenderId(); long itemId = msg.getItemId(); DoubleVector vector = msg.getVector(); if (normalizedValues.containsKey(itemId) == false) { normalizedValues.put(itemId, new DenseDoubleVector(m_matrix_rank, 0.0)); normalizedValueCount.put(itemId, 0); senderList.put(itemId, new LinkedList<Integer>()); } normalizedValues.put(itemId, normalizedValues.get(itemId).add(vector)); normalizedValueCount.put(itemId, normalizedValueCount.get(itemId) + 1); senderList.get(itemId).add(senderId); } // normalize for (Map.Entry<Long, DoubleVector> e : normalizedValues.entrySet()) { double count = normalizedValueCount.get(e.getKey()); e.setValue(e.getValue().multiply(1.0 / count)); } // Step 3) // send back normalized values to senders for (Map.Entry<Long, DoubleVector> e : normalizedValues.entrySet()) { msg = new ItemMessage(peerId, e.getKey(), e.getValue()); // send to interested peers Iterator<Integer> iter = senderList.get(e.getKey()).iterator(); while (iter.hasNext()) { peer.send(peer.getPeerName(iter.next()), msg); } } peer.sync(); // Step 4) // receive already normalized and synced data while ((msg = peer.getCurrentMessage()) != null) { m_itemsMatrix.put(msg.getItemId(), new PipesVectorWritable(msg.getVector())); } } private void saveModel( BSPPeer<IntWritable, PipesVectorWritable, Text, PipesVectorWritable, ItemMessage> peer) throws IOException, SyncException, InterruptedException { // save user information LOG.info(peer.getPeerName() + ") saving " + m_usersMatrix.size() + " users"); for (Map.Entry<Integer, PipesVectorWritable> user : m_usersMatrix .entrySet()) { peer.write(new Text("u" + user.getKey()), user.getValue()); } // save item information LOG.info(peer.getPeerName() + ") saving " + m_itemsMatrix.size() + " items"); for (Map.Entry<Long, PipesVectorWritable> item : m_itemsMatrix.entrySet()) { peer.write(new Text("i" + item.getKey()), item.getValue()); } } /********************************* GPU *********************************/ @Override public void setupGpu( BSPPeer<IntWritable, PipesVectorWritable, Text, PipesVectorWritable, ItemMessage> peer) throws IOException, SyncException, InterruptedException { long startTime = System.currentTimeMillis(); this.m_conf = peer.getConfiguration(); this.m_isDebuggingEnabled = m_conf.getBoolean(CONF_DEBUG, false); this.m_maxIterations = m_conf.getInt(OnlineCF.CONF_ITERATION_COUNT, OnlineCF.DFLT_ITERATION_COUNT); this.m_matrix_rank = m_conf.getInt(OnlineCF.CONF_MATRIX_RANK, OnlineCF.DFLT_MATRIX_RANK); this.m_skip_count = m_conf.getInt(OnlineCF.CONF_SKIP_COUNT, OnlineCF.DFLT_SKIP_COUNT); this.m_function = new MeanAbsError(); this.m_blockSize = Integer.parseInt(this.m_conf.get(CONF_BLOCKSIZE)); this.m_gridSize = Integer.parseInt(this.m_conf.get(CONF_GRIDSIZE)); // Init logging if (m_isDebuggingEnabled) { try { FileSystem fs = FileSystem.get(m_conf); m_logger = fs.create(new Path(FileOutputFormat .getOutputPath(new BSPJob((HamaConfiguration) m_conf)) + "/BSP_" + peer.getTaskId() + ".log")); } catch (IOException e) { e.printStackTrace(); } } this.m_setupTimeGpu = System.currentTimeMillis() - startTime; } @Override public void bspGpu( BSPPeer<IntWritable, PipesVectorWritable, Text, PipesVectorWritable, ItemMessage> peer, Rootbeer rootbeer) throws IOException, SyncException, InterruptedException { long startTime = System.currentTimeMillis(); // Logging if (m_isDebuggingEnabled) { m_logger.writeChars("OnlineTrainHybridBSP.bspGpu executed on GPU!\n"); m_logger.writeChars("OnlineTrainHybridBSP.bspGpu blockSize: " + m_blockSize + " gridSize: " + m_gridSize + "\n"); // m_logger.writeChars("KMeansHybrid.bspGpu inputSize: " + inputs.size() + // "\n"); } // TODO // OnlineCFTrainHybridKernel kernel = new // OnlineCFTrainHybridKernel(inputsArr, // m_centers_gpu, m_conf.getInt(CONF_MAX_ITERATIONS, 0), // peer.getAllPeerNames()); // Run GPU Kernels Context context = rootbeer.createDefaultContext(); Stopwatch watch = new Stopwatch(); watch.start(); // rootbeer.run(kernel, new ThreadConfig(m_blockSize, m_gridSize, // m_blockSize * m_gridSize), context); watch.stop(); this.m_bspTimeGpu = System.currentTimeMillis() - startTime; // Logging if (m_isDebuggingEnabled) { m_logger.writeChars("OnlineTrainHybridBSP,setupTimeGpu=" + this.m_setupTimeGpu + " ms\n"); m_logger.writeChars("OnlineTrainHybridBSP,setupTimeGpu=" + (this.m_setupTimeGpu / 1000.0) + " seconds\n"); m_logger.writeChars("OnlineTrainHybridBSP,bspTimeGpu=" + this.m_bspTimeGpu + " ms\n"); m_logger.writeChars("OnlineTrainHybridBSP,bspTimeGpu=" + (this.m_bspTimeGpu / 1000.0) + " seconds\n"); List<StatsRow> stats = context.getStats(); for (StatsRow row : stats) { m_logger.writeChars(" StatsRow:\n"); m_logger.writeChars(" serial time: " + row.getSerializationTime() + "\n"); m_logger.writeChars(" exec time: " + row.getExecutionTime() + "\n"); m_logger.writeChars(" deserial time: " + row.getDeserializationTime() + "\n"); m_logger.writeChars(" num blocks: " + row.getNumBlocks() + "\n"); m_logger.writeChars(" num threads: " + row.getNumThreads() + "\n"); m_logger.writeChars("GPUTime: " + watch.elapsedTimeMillis() + " ms" + "\n"); } m_logger.close(); } } public static BSPJob createOnlineCFTrainHybridBSPConf(Path inPath, Path outPath) throws IOException { return createOnlineCFTrainHybridBSPConf(new HamaConfiguration(), inPath, outPath); } public static BSPJob createOnlineCFTrainHybridBSPConf(Configuration conf, Path inPath, Path outPath) throws IOException { if (conf.getInt(OnlineCF.CONF_MATRIX_RANK, -1) == -1) { conf.setInt(OnlineCF.CONF_MATRIX_RANK, OnlineCF.DFLT_MATRIX_RANK); } if (conf.getInt(OnlineCF.CONF_ITERATION_COUNT, -1) == -1) { conf.setInt(OnlineCF.CONF_ITERATION_COUNT, OnlineCF.DFLT_ITERATION_COUNT); } if (conf.getInt(OnlineCF.CONF_SKIP_COUNT, -1) == -1) { conf.setInt(OnlineCF.CONF_SKIP_COUNT, OnlineCF.DFLT_SKIP_COUNT); } BSPJob job = new BSPJob(new HamaConfiguration(conf), OnlineCFTrainHybridBSP.class); // Set the job name job.setJobName("Online CF train"); // set the BSP class which shall be executed job.setBspClass(OnlineCFTrainHybridBSP.class); // help Hama to locale the jar to be distributed job.setJarByClass(OnlineCFTrainHybridBSP.class); job.setInputPath(inPath); job.setInputFormat(SequenceFileInputFormat.class); job.setInputKeyClass(IntWritable.class); job.setInputValueClass(PipesVectorWritable.class); job.setOutputPath(outPath); job.setOutputFormat(SequenceFileOutputFormat.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(PipesVectorWritable.class); job.setMessageClass(ItemMessage.class); // Enable Partitioning job.setBoolean(Constants.ENABLE_RUNTIME_PARTITIONING, true); job.setPartitioner(HashPartitioner.class); job.set("bsp.child.java.opts", "-Xmx4G"); return job; } public static void main(String[] args) throws Exception { // Defaults - int numBspTask = 1; - int numGpuBspTask = 1; + int numBspTask = 2; // CPU + GPU tasks + int numGpuBspTask = 0; // GPU tasks int blockSize = BLOCK_SIZE; int gridSize = GRID_SIZE; - int maxIteration = 150; + int maxIteration = 3; //150; int matrixRank = 3; int skipCount = 1; - boolean useTestExampleInput = false; - boolean isDebugging = false; + boolean useTestExampleInput = true; + boolean isDebugging = true; Configuration conf = new HamaConfiguration(); FileSystem fs = FileSystem.get(conf); // Set numBspTask to maxTasks - BSPJobClient jobClient = new BSPJobClient(conf); - ClusterStatus cluster = jobClient.getClusterStatus(true); - numBspTask = cluster.getMaxTasks(); + // BSPJobClient jobClient = new BSPJobClient(conf); + // ClusterStatus cluster = jobClient.getClusterStatus(true); + // numBspTask = cluster.getMaxTasks(); if (args.length > 0) { if (args.length == 9) { numBspTask = Integer.parseInt(args[0]); numGpuBspTask = Integer.parseInt(args[1]); blockSize = Integer.parseInt(args[2]); gridSize = Integer.parseInt(args[3]); maxIteration = Integer.parseInt(args[4]); matrixRank = Integer.parseInt(args[5]); skipCount = Integer.parseInt(args[6]); useTestExampleInput = Boolean.parseBoolean(args[7]); isDebugging = Boolean.parseBoolean(args[8]); } else { System.out.println("Wrong argument size!"); System.out.println(" Argument1=numBspTask"); System.out.println(" Argument2=numGpuBspTask"); System.out.println(" Argument3=blockSize"); System.out.println(" Argument4=gridSize"); System.out .println(" Argument5=maxIterations | Number of maximal iterations (" + maxIteration + ")"); System.out.println(" Argument6=matrixRank | matrixRank (" + matrixRank + ")"); System.out.println(" Argument7=skipCount | skipCount (" + skipCount + ")"); System.out .println(" Argument8=testExample | Use testExample input (true|false=default)"); System.out .println(" Argument9=debug | Enable debugging (true|false=default)"); return; } } // Set config variables conf.setBoolean(CONF_DEBUG, isDebugging); - conf.setBoolean("hama.pipes.logging", false); + conf.setBoolean("hama.pipes.logging", isDebugging); // Set CPU tasks conf.setInt("bsp.peers.num", numBspTask); // Set GPU tasks conf.setInt("bsp.peers.gpu.num", numGpuBspTask); // Set GPU blockSize and gridSize conf.set(CONF_BLOCKSIZE, "" + blockSize); conf.set(CONF_GRIDSIZE, "" + gridSize); conf.setInt(OnlineCF.CONF_ITERATION_COUNT, maxIteration); conf.setInt(OnlineCF.CONF_MATRIX_RANK, matrixRank); conf.setInt(OnlineCF.CONF_SKIP_COUNT, skipCount); // Debug output LOG.info("NumBspTask: " + conf.getInt("bsp.peers.num", 0)); LOG.info("NumGpuBspTask: " + conf.getInt("bsp.peers.gpu.num", 0)); LOG.info("bsp.tasks.maximum: " + conf.get("bsp.tasks.maximum")); LOG.info("BlockSize: " + conf.get(CONF_BLOCKSIZE)); LOG.info("GridSize: " + conf.get(CONF_GRIDSIZE)); LOG.info("isDebugging: " + isDebugging); LOG.info("useTestExampleInput: " + useTestExampleInput); LOG.info("inputPath: " + CONF_INPUT_DIR); LOG.info("outputPath: " + CONF_OUTPUT_DIR); LOG.info("maxIteration: " + maxIteration); LOG.info("matrixRank: " + matrixRank); LOG.info("skipCount: " + skipCount); // prepare Input Preference[] testPrefs = null; if (useTestExampleInput) { Path preferencesIn = new Path(CONF_INPUT_DIR, "preferences_in.seq"); testPrefs = prepareInputData(conf, fs, CONF_INPUT_DIR, preferencesIn, new Random(3337L)); } BSPJob job = createOnlineCFTrainHybridBSPConf(conf, CONF_INPUT_DIR, CONF_OUTPUT_DIR); long startTime = System.currentTimeMillis(); if (job.waitForCompletion(true)) { LOG.info("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); if (useTestExampleInput) { OnlineCF recommender = new OnlineCF(); recommender.load(CONF_OUTPUT_DIR.toString(), false); int correct = 0; for (Preference<Integer, Integer> test : testPrefs) { double actual = test.getValue().get(); double estimated = recommender.estimatePreference(test.getUserId(), test.getItemId()); correct += (Math.abs(actual - estimated) < 0.5) ? 1 : 0; } LOG.info("assertEquals(expected: " + (testPrefs.length * 0.75) + " == " + correct + " actual with delta: 1"); } if (isDebugging) { printOutput(conf, fs, ".log", new IntWritable(), new PipesVectorWritable()); } // TODO // printFile(conf, fs, centerOut, new PipesVectorWritable(), // NullWritable.get()); } } /** * prepareInputData * */ public static Preference[] prepareInputData(Configuration conf, FileSystem fs, Path in, Path preferencesIn, Random rand) throws IOException { Preference[] train_prefs = { new Preference<Integer, Integer>(1, 1, 4), new Preference<Integer, Integer>(1, 2, 2.5), new Preference<Integer, Integer>(1, 3, 3.5), new Preference<Integer, Integer>(1, 4, 1), new Preference<Integer, Integer>(1, 5, 3.5), new Preference<Integer, Integer>(2, 1, 4), new Preference<Integer, Integer>(2, 2, 2.5), new Preference<Integer, Integer>(2, 3, 3.5), new Preference<Integer, Integer>(2, 4, 1), new Preference<Integer, Integer>(2, 5, 3.5), new Preference<Integer, Integer>(3, 1, 4), new Preference<Integer, Integer>(3, 2, 2.5), new Preference<Integer, Integer>(3, 3, 3.5) }; Preference[] test_prefs = { new Preference<Integer, Integer>(1, 3, 3.5), new Preference<Integer, Integer>(2, 4, 1), new Preference<Integer, Integer>(3, 4, 1), new Preference<Integer, Integer>(3, 5, 3.5) }; // Delete input files if already exist if (fs.exists(in)) { fs.delete(in, true); } if (fs.exists(preferencesIn)) { fs.delete(preferencesIn, true); } final SequenceFile.Writer prefWriter = SequenceFile.createWriter(fs, conf, preferencesIn, IntWritable.class, PipesVectorWritable.class, CompressionType.NONE); for (Preference<Integer, Integer> taste : train_prefs) { double values[] = new double[2]; values[0] = taste.getItemId(); values[1] = taste.getValue().get(); prefWriter.append(new IntWritable(taste.getUserId()), new PipesVectorWritable(new DenseDoubleVector(values))); } prefWriter.close(); return test_prefs; } static void printOutput(Configuration conf, FileSystem fs, String extensionFilter, Writable key, Writable value) throws IOException { FileStatus[] files = fs.listStatus(CONF_OUTPUT_DIR); for (int i = 0; i < files.length; i++) { if ((files[i].getLen() > 0) && (files[i].getPath().getName().endsWith(extensionFilter))) { printFile(conf, fs, files[i].getPath(), key, value); } } // fs.delete(FileOutputFormat.getOutputPath(job), true); } static void printFile(Configuration conf, FileSystem fs, Path file, Writable key, Writable value) throws IOException { System.out.println("File " + file.toString()); SequenceFile.Reader reader = null; try { reader = new SequenceFile.Reader(fs, file, conf); while (reader.next(key, value)) { System.out.println("key: '" + key.toString() + "' value: '" + value.toString() + "'\n"); } } catch (IOException e) { FSDataInputStream in = fs.open(file); IOUtils.copyBytes(in, System.out, conf, false); in.close(); } catch (NullPointerException e) { LOG.error(e); } finally { if (reader != null) { reader.close(); } } } }
false
true
public static void main(String[] args) throws Exception { // Defaults int numBspTask = 1; int numGpuBspTask = 1; int blockSize = BLOCK_SIZE; int gridSize = GRID_SIZE; int maxIteration = 150; int matrixRank = 3; int skipCount = 1; boolean useTestExampleInput = false; boolean isDebugging = false; Configuration conf = new HamaConfiguration(); FileSystem fs = FileSystem.get(conf); // Set numBspTask to maxTasks BSPJobClient jobClient = new BSPJobClient(conf); ClusterStatus cluster = jobClient.getClusterStatus(true); numBspTask = cluster.getMaxTasks(); if (args.length > 0) { if (args.length == 9) { numBspTask = Integer.parseInt(args[0]); numGpuBspTask = Integer.parseInt(args[1]); blockSize = Integer.parseInt(args[2]); gridSize = Integer.parseInt(args[3]); maxIteration = Integer.parseInt(args[4]); matrixRank = Integer.parseInt(args[5]); skipCount = Integer.parseInt(args[6]); useTestExampleInput = Boolean.parseBoolean(args[7]); isDebugging = Boolean.parseBoolean(args[8]); } else { System.out.println("Wrong argument size!"); System.out.println(" Argument1=numBspTask"); System.out.println(" Argument2=numGpuBspTask"); System.out.println(" Argument3=blockSize"); System.out.println(" Argument4=gridSize"); System.out .println(" Argument5=maxIterations | Number of maximal iterations (" + maxIteration + ")"); System.out.println(" Argument6=matrixRank | matrixRank (" + matrixRank + ")"); System.out.println(" Argument7=skipCount | skipCount (" + skipCount + ")"); System.out .println(" Argument8=testExample | Use testExample input (true|false=default)"); System.out .println(" Argument9=debug | Enable debugging (true|false=default)"); return; } } // Set config variables conf.setBoolean(CONF_DEBUG, isDebugging); conf.setBoolean("hama.pipes.logging", false); // Set CPU tasks conf.setInt("bsp.peers.num", numBspTask); // Set GPU tasks conf.setInt("bsp.peers.gpu.num", numGpuBspTask); // Set GPU blockSize and gridSize conf.set(CONF_BLOCKSIZE, "" + blockSize); conf.set(CONF_GRIDSIZE, "" + gridSize); conf.setInt(OnlineCF.CONF_ITERATION_COUNT, maxIteration); conf.setInt(OnlineCF.CONF_MATRIX_RANK, matrixRank); conf.setInt(OnlineCF.CONF_SKIP_COUNT, skipCount); // Debug output LOG.info("NumBspTask: " + conf.getInt("bsp.peers.num", 0)); LOG.info("NumGpuBspTask: " + conf.getInt("bsp.peers.gpu.num", 0)); LOG.info("bsp.tasks.maximum: " + conf.get("bsp.tasks.maximum")); LOG.info("BlockSize: " + conf.get(CONF_BLOCKSIZE)); LOG.info("GridSize: " + conf.get(CONF_GRIDSIZE)); LOG.info("isDebugging: " + isDebugging); LOG.info("useTestExampleInput: " + useTestExampleInput); LOG.info("inputPath: " + CONF_INPUT_DIR); LOG.info("outputPath: " + CONF_OUTPUT_DIR); LOG.info("maxIteration: " + maxIteration); LOG.info("matrixRank: " + matrixRank); LOG.info("skipCount: " + skipCount); // prepare Input Preference[] testPrefs = null; if (useTestExampleInput) { Path preferencesIn = new Path(CONF_INPUT_DIR, "preferences_in.seq"); testPrefs = prepareInputData(conf, fs, CONF_INPUT_DIR, preferencesIn, new Random(3337L)); } BSPJob job = createOnlineCFTrainHybridBSPConf(conf, CONF_INPUT_DIR, CONF_OUTPUT_DIR); long startTime = System.currentTimeMillis(); if (job.waitForCompletion(true)) { LOG.info("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); if (useTestExampleInput) { OnlineCF recommender = new OnlineCF(); recommender.load(CONF_OUTPUT_DIR.toString(), false); int correct = 0; for (Preference<Integer, Integer> test : testPrefs) { double actual = test.getValue().get(); double estimated = recommender.estimatePreference(test.getUserId(), test.getItemId()); correct += (Math.abs(actual - estimated) < 0.5) ? 1 : 0; } LOG.info("assertEquals(expected: " + (testPrefs.length * 0.75) + " == " + correct + " actual with delta: 1"); } if (isDebugging) { printOutput(conf, fs, ".log", new IntWritable(), new PipesVectorWritable()); } // TODO // printFile(conf, fs, centerOut, new PipesVectorWritable(), // NullWritable.get()); } }
public static void main(String[] args) throws Exception { // Defaults int numBspTask = 2; // CPU + GPU tasks int numGpuBspTask = 0; // GPU tasks int blockSize = BLOCK_SIZE; int gridSize = GRID_SIZE; int maxIteration = 3; //150; int matrixRank = 3; int skipCount = 1; boolean useTestExampleInput = true; boolean isDebugging = true; Configuration conf = new HamaConfiguration(); FileSystem fs = FileSystem.get(conf); // Set numBspTask to maxTasks // BSPJobClient jobClient = new BSPJobClient(conf); // ClusterStatus cluster = jobClient.getClusterStatus(true); // numBspTask = cluster.getMaxTasks(); if (args.length > 0) { if (args.length == 9) { numBspTask = Integer.parseInt(args[0]); numGpuBspTask = Integer.parseInt(args[1]); blockSize = Integer.parseInt(args[2]); gridSize = Integer.parseInt(args[3]); maxIteration = Integer.parseInt(args[4]); matrixRank = Integer.parseInt(args[5]); skipCount = Integer.parseInt(args[6]); useTestExampleInput = Boolean.parseBoolean(args[7]); isDebugging = Boolean.parseBoolean(args[8]); } else { System.out.println("Wrong argument size!"); System.out.println(" Argument1=numBspTask"); System.out.println(" Argument2=numGpuBspTask"); System.out.println(" Argument3=blockSize"); System.out.println(" Argument4=gridSize"); System.out .println(" Argument5=maxIterations | Number of maximal iterations (" + maxIteration + ")"); System.out.println(" Argument6=matrixRank | matrixRank (" + matrixRank + ")"); System.out.println(" Argument7=skipCount | skipCount (" + skipCount + ")"); System.out .println(" Argument8=testExample | Use testExample input (true|false=default)"); System.out .println(" Argument9=debug | Enable debugging (true|false=default)"); return; } } // Set config variables conf.setBoolean(CONF_DEBUG, isDebugging); conf.setBoolean("hama.pipes.logging", isDebugging); // Set CPU tasks conf.setInt("bsp.peers.num", numBspTask); // Set GPU tasks conf.setInt("bsp.peers.gpu.num", numGpuBspTask); // Set GPU blockSize and gridSize conf.set(CONF_BLOCKSIZE, "" + blockSize); conf.set(CONF_GRIDSIZE, "" + gridSize); conf.setInt(OnlineCF.CONF_ITERATION_COUNT, maxIteration); conf.setInt(OnlineCF.CONF_MATRIX_RANK, matrixRank); conf.setInt(OnlineCF.CONF_SKIP_COUNT, skipCount); // Debug output LOG.info("NumBspTask: " + conf.getInt("bsp.peers.num", 0)); LOG.info("NumGpuBspTask: " + conf.getInt("bsp.peers.gpu.num", 0)); LOG.info("bsp.tasks.maximum: " + conf.get("bsp.tasks.maximum")); LOG.info("BlockSize: " + conf.get(CONF_BLOCKSIZE)); LOG.info("GridSize: " + conf.get(CONF_GRIDSIZE)); LOG.info("isDebugging: " + isDebugging); LOG.info("useTestExampleInput: " + useTestExampleInput); LOG.info("inputPath: " + CONF_INPUT_DIR); LOG.info("outputPath: " + CONF_OUTPUT_DIR); LOG.info("maxIteration: " + maxIteration); LOG.info("matrixRank: " + matrixRank); LOG.info("skipCount: " + skipCount); // prepare Input Preference[] testPrefs = null; if (useTestExampleInput) { Path preferencesIn = new Path(CONF_INPUT_DIR, "preferences_in.seq"); testPrefs = prepareInputData(conf, fs, CONF_INPUT_DIR, preferencesIn, new Random(3337L)); } BSPJob job = createOnlineCFTrainHybridBSPConf(conf, CONF_INPUT_DIR, CONF_OUTPUT_DIR); long startTime = System.currentTimeMillis(); if (job.waitForCompletion(true)) { LOG.info("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); if (useTestExampleInput) { OnlineCF recommender = new OnlineCF(); recommender.load(CONF_OUTPUT_DIR.toString(), false); int correct = 0; for (Preference<Integer, Integer> test : testPrefs) { double actual = test.getValue().get(); double estimated = recommender.estimatePreference(test.getUserId(), test.getItemId()); correct += (Math.abs(actual - estimated) < 0.5) ? 1 : 0; } LOG.info("assertEquals(expected: " + (testPrefs.length * 0.75) + " == " + correct + " actual with delta: 1"); } if (isDebugging) { printOutput(conf, fs, ".log", new IntWritable(), new PipesVectorWritable()); } // TODO // printFile(conf, fs, centerOut, new PipesVectorWritable(), // NullWritable.get()); } }
diff --git a/gcs/base/src/pt/com/gcs/messaging/GcsRemoteProtocolHandler.java b/gcs/base/src/pt/com/gcs/messaging/GcsRemoteProtocolHandler.java index ccada592..5a55cb7c 100755 --- a/gcs/base/src/pt/com/gcs/messaging/GcsRemoteProtocolHandler.java +++ b/gcs/base/src/pt/com/gcs/messaging/GcsRemoteProtocolHandler.java @@ -1,135 +1,136 @@ package pt.com.gcs.messaging; import java.net.SocketAddress; import java.util.Set; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.caudexorigo.ErrorAnalyser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pt.com.gcs.conf.AgentInfo; import pt.com.gcs.net.IoSessionHelper; class GcsRemoteProtocolHandler extends IoHandlerAdapter { private static Logger log = LoggerFactory.getLogger(GcsRemoteProtocolHandler.class); @Override public void exceptionCaught(IoSession iosession, Throwable cause) throws Exception { Throwable rootCause = ErrorAnalyser.findRootCause(cause); log.error("Exception Caught:{}, {}", IoSessionHelper.getRemoteAddress(iosession), rootCause.getMessage()); if (iosession.isConnected() && !iosession.isClosing()) { log.error("STACKTRACE", rootCause); } } @Override public void messageReceived(final IoSession iosession, Object omessage) throws Exception { final Message msg = (Message) omessage; if (log.isDebugEnabled()) { log.debug("Message Received from: '{}', Type: '{}'", IoSessionHelper.getRemoteAddress(iosession), msg.getType()); } if (msg.getType() == (MessageType.COM_TOPIC)) { LocalTopicConsumers.notify(msg); } else if (msg.getType() == (MessageType.COM_QUEUE)) { ReceivedMessagesBuffer receivedMessages = ReceivedMessagesBufferList.get(msg.getDestination()); if (!receivedMessages.isDuplicate(msg.getMessageId())) { QueueProcessorList.get(msg.getDestination()).store(msg, true); LocalQueueConsumers.acknowledgeMessage(msg, iosession); + receivedMessages.put(msg.getMessageId()); } } else { log.warn("Unkwown message type. Don't know how to handle message"); } } @Override public void messageSent(IoSession iosession, Object message) throws Exception { if (log.isDebugEnabled()) { log.debug("Message Sent: '{}', '{}'", IoSessionHelper.getRemoteAddress(iosession), message.toString()); } } @Override public void sessionClosed(final IoSession iosession) throws Exception { log.info("Session Closed: '{}'", IoSessionHelper.getRemoteAddress(iosession)); Gcs.connect((SocketAddress) IoSessionHelper.getRemoteInetAddress(iosession)); } @Override public void sessionCreated(IoSession iosession) throws Exception { IoSessionHelper.tagWithRemoteAddress(iosession); if (log.isDebugEnabled()) { log.debug("Session Created: '{}'", IoSessionHelper.getRemoteAddress(iosession)); } } @Override public void sessionIdle(IoSession iosession, IdleStatus status) throws Exception { if (log.isDebugEnabled()) { log.debug("Session Idle:'{}'", IoSessionHelper.getRemoteAddress(iosession)); } } @Override public void sessionOpened(IoSession iosession) throws Exception { log.info("Session Opened: '{}'", IoSessionHelper.getRemoteAddress(iosession)); sayHello(iosession); } public void sayHello(IoSession iosession) { if (log.isDebugEnabled()) { log.debug("Say Hello: '{}'", IoSessionHelper.getRemoteAddress(iosession)); } Message m = new Message(); String agentId = AgentInfo.getAgentName() + "@" + AgentInfo.getAgentHost() + ":" + AgentInfo.getAgentPort(); m.setType((MessageType.HELLO)); m.setDestination("HELLO"); m.setContent(agentId); log.info("Send agentId: '{}'", agentId); // iosession.write(m).awaitUninterruptibly(); iosession.write(m); Set<String> topicNameSet = LocalTopicConsumers.getBroadcastableTopics(); for (String topicName : topicNameSet) { LocalTopicConsumers.broadCastTopicInfo(topicName, "CREATE", iosession); } Set<String> queueNameSet = LocalQueueConsumers.getBroadcastableQueues(); for (String queueName : queueNameSet) { LocalQueueConsumers.broadCastQueueInfo(queueName, "CREATE", iosession); } } }
true
true
public void messageReceived(final IoSession iosession, Object omessage) throws Exception { final Message msg = (Message) omessage; if (log.isDebugEnabled()) { log.debug("Message Received from: '{}', Type: '{}'", IoSessionHelper.getRemoteAddress(iosession), msg.getType()); } if (msg.getType() == (MessageType.COM_TOPIC)) { LocalTopicConsumers.notify(msg); } else if (msg.getType() == (MessageType.COM_QUEUE)) { ReceivedMessagesBuffer receivedMessages = ReceivedMessagesBufferList.get(msg.getDestination()); if (!receivedMessages.isDuplicate(msg.getMessageId())) { QueueProcessorList.get(msg.getDestination()).store(msg, true); LocalQueueConsumers.acknowledgeMessage(msg, iosession); } } else { log.warn("Unkwown message type. Don't know how to handle message"); } }
public void messageReceived(final IoSession iosession, Object omessage) throws Exception { final Message msg = (Message) omessage; if (log.isDebugEnabled()) { log.debug("Message Received from: '{}', Type: '{}'", IoSessionHelper.getRemoteAddress(iosession), msg.getType()); } if (msg.getType() == (MessageType.COM_TOPIC)) { LocalTopicConsumers.notify(msg); } else if (msg.getType() == (MessageType.COM_QUEUE)) { ReceivedMessagesBuffer receivedMessages = ReceivedMessagesBufferList.get(msg.getDestination()); if (!receivedMessages.isDuplicate(msg.getMessageId())) { QueueProcessorList.get(msg.getDestination()).store(msg, true); LocalQueueConsumers.acknowledgeMessage(msg, iosession); receivedMessages.put(msg.getMessageId()); } } else { log.warn("Unkwown message type. Don't know how to handle message"); } }
diff --git a/src/main/java/org/got5/tapestry5/jquery/jqgrid/services/javascript/JQGridJavaScriptStack.java b/src/main/java/org/got5/tapestry5/jquery/jqgrid/services/javascript/JQGridJavaScriptStack.java index 2ea42c1..1a99c63 100755 --- a/src/main/java/org/got5/tapestry5/jquery/jqgrid/services/javascript/JQGridJavaScriptStack.java +++ b/src/main/java/org/got5/tapestry5/jquery/jqgrid/services/javascript/JQGridJavaScriptStack.java @@ -1,192 +1,192 @@ // // Copyright 2010 GOT5 (GO Tapestry 5) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.got5.tapestry5.jquery.jqgrid.services.javascript; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import org.apache.tapestry5.Asset; import org.apache.tapestry5.SymbolConstants; import org.apache.tapestry5.func.F; import org.apache.tapestry5.func.Mapper; import org.apache.tapestry5.ioc.annotations.Symbol; import org.apache.tapestry5.ioc.services.ThreadLocale; import org.apache.tapestry5.json.JSONArray; import org.apache.tapestry5.json.JSONObject; import org.apache.tapestry5.services.AssetSource; import org.apache.tapestry5.services.javascript.JavaScriptStack; import org.apache.tapestry5.services.javascript.StylesheetLink; import org.got5.tapestry5.jquery.jqgrid.JQGridSymbolConstants; public class JQGridJavaScriptStack implements JavaScriptStack { public static final String STACK_ID = "jqGridStack"; private final ThreadLocale threadLocale; private final AssetSource assetSource; private final boolean compactJSON; private final boolean addJqueryStack; private final List<Asset> javaScriptStack; private final List<Asset> jqueryStack; private final List<StylesheetLink> stylesheetStack; public JQGridJavaScriptStack(final ThreadLocale threadLocale, @Symbol(SymbolConstants.COMPACT_JSON) final boolean compactJSON, @Symbol(SymbolConstants.PRODUCTION_MODE) final boolean productionMode, @Symbol(JQGridSymbolConstants.ADD_JQUERY_IN_JQGRIDSTACK) final boolean addJqueryStack, final AssetSource assetSource) { this.threadLocale = threadLocale; this.assetSource = assetSource; this.compactJSON = compactJSON; this.addJqueryStack = addJqueryStack; final Mapper<String, Asset> pathToAsset = new Mapper<String, Asset>() { @Override public Asset map(String path) { return assetSource.getExpandedAsset(path); } }; final Mapper<Asset, StylesheetLink> assetToStylesheetLink = new Mapper<Asset, StylesheetLink>() { @Override public StylesheetLink map(Asset input) { return new StylesheetLink(input); }; }; final Mapper<String, StylesheetLink> pathToStylesheetLink = pathToAsset.combine(assetToStylesheetLink); jqueryStack = F.flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.min.js", "${jquery.jqgrid.core.path}/jquery.noconflict.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery-ui-custom.min.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.contextmenu.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.layout.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.tablednd.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/ui.multiselect.js" ).map(pathToAsset).toList(); if (productionMode) { stylesheetStack = F.flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/css/ui.jqgrid.css") .map(pathToStylesheetLink).toList(); javaScriptStack = F .flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.jqgrid.min.js", "${jquery.jqgrid.core.path}/jqgrid.js") .map(pathToAsset).toList(); } else { stylesheetStack = F.flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/css/ui.jqgrid.css") .map(pathToStylesheetLink).toList(); javaScriptStack = F .flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.base.js", // jqGrid base "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.common.js", // jqGrid common for editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.formedit.js", // jqGrid Form editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.inlinedit.js", // jqGrid inline editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.celledit.js", // jqGrid cell editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.subgrid.js", //jqGrid subgrid "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.treegrid.js", //jqGrid treegrid "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.grouping.js", //jqGrid grouping "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.custom.js", //jqGrid custom "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.tbltogrid.js", //jqGrid table to grid "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.import.js", //jqGrid import "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jquery.fmatter.js", //jqGrid formater "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/JsonXml.js", //xmljson utils "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.jqueryui.js", //jQuery UI utils "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.loader.js", //jqGrid loader "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.postext.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.setcolumns.js", - "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jqDnr.js", + "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jqDnR.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jqModal.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/ui.multiselect.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jquery.searchFilter.js", "${jquery.jqgrid.core.path}/jqgrid.js") .map(pathToAsset).toList(); } } public String getInitialization() { Locale locale = threadLocale.getLocale(); JSONObject spec = new JSONObject(); // set language spec.put("language", locale.getLanguage()); return null; //return String.format("Tapestry.JQGrid.initLocalization(%s);", spec.toString(compactJSON)); } public List<Asset> getJavaScriptLibraries() { Locale locale = threadLocale.getLocale(); String pathToJQGridI18nRess = "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/i18n/grid.locale-"+locale.getLanguage()+".js"; Asset jqGridI18nAsset = this.assetSource.getExpandedAsset(pathToJQGridI18nRess); if (jqGridI18nAsset.getResource().exists()) { List<Asset> ret = new ArrayList<Asset>(); if(addJqueryStack) ret.addAll(jqueryStack); //locale asset should be declare after file // or you get this eror in firebug (b.jgrid.getAccessor is not a function Line 53) ret.add(jqGridI18nAsset); ret.addAll(javaScriptStack); return ret; } return javaScriptStack; } public List<StylesheetLink> getStylesheets() { return stylesheetStack; } public List<String> getStacks() { return Collections.emptyList(); } }
true
true
public JQGridJavaScriptStack(final ThreadLocale threadLocale, @Symbol(SymbolConstants.COMPACT_JSON) final boolean compactJSON, @Symbol(SymbolConstants.PRODUCTION_MODE) final boolean productionMode, @Symbol(JQGridSymbolConstants.ADD_JQUERY_IN_JQGRIDSTACK) final boolean addJqueryStack, final AssetSource assetSource) { this.threadLocale = threadLocale; this.assetSource = assetSource; this.compactJSON = compactJSON; this.addJqueryStack = addJqueryStack; final Mapper<String, Asset> pathToAsset = new Mapper<String, Asset>() { @Override public Asset map(String path) { return assetSource.getExpandedAsset(path); } }; final Mapper<Asset, StylesheetLink> assetToStylesheetLink = new Mapper<Asset, StylesheetLink>() { @Override public StylesheetLink map(Asset input) { return new StylesheetLink(input); }; }; final Mapper<String, StylesheetLink> pathToStylesheetLink = pathToAsset.combine(assetToStylesheetLink); jqueryStack = F.flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.min.js", "${jquery.jqgrid.core.path}/jquery.noconflict.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery-ui-custom.min.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.contextmenu.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.layout.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.tablednd.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/ui.multiselect.js" ).map(pathToAsset).toList(); if (productionMode) { stylesheetStack = F.flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/css/ui.jqgrid.css") .map(pathToStylesheetLink).toList(); javaScriptStack = F .flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.jqgrid.min.js", "${jquery.jqgrid.core.path}/jqgrid.js") .map(pathToAsset).toList(); } else { stylesheetStack = F.flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/css/ui.jqgrid.css") .map(pathToStylesheetLink).toList(); javaScriptStack = F .flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.base.js", // jqGrid base "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.common.js", // jqGrid common for editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.formedit.js", // jqGrid Form editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.inlinedit.js", // jqGrid inline editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.celledit.js", // jqGrid cell editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.subgrid.js", //jqGrid subgrid "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.treegrid.js", //jqGrid treegrid "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.grouping.js", //jqGrid grouping "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.custom.js", //jqGrid custom "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.tbltogrid.js", //jqGrid table to grid "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.import.js", //jqGrid import "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jquery.fmatter.js", //jqGrid formater "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/JsonXml.js", //xmljson utils "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.jqueryui.js", //jQuery UI utils "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.loader.js", //jqGrid loader "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.postext.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.setcolumns.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jqDnr.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jqModal.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/ui.multiselect.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jquery.searchFilter.js", "${jquery.jqgrid.core.path}/jqgrid.js") .map(pathToAsset).toList(); } }
public JQGridJavaScriptStack(final ThreadLocale threadLocale, @Symbol(SymbolConstants.COMPACT_JSON) final boolean compactJSON, @Symbol(SymbolConstants.PRODUCTION_MODE) final boolean productionMode, @Symbol(JQGridSymbolConstants.ADD_JQUERY_IN_JQGRIDSTACK) final boolean addJqueryStack, final AssetSource assetSource) { this.threadLocale = threadLocale; this.assetSource = assetSource; this.compactJSON = compactJSON; this.addJqueryStack = addJqueryStack; final Mapper<String, Asset> pathToAsset = new Mapper<String, Asset>() { @Override public Asset map(String path) { return assetSource.getExpandedAsset(path); } }; final Mapper<Asset, StylesheetLink> assetToStylesheetLink = new Mapper<Asset, StylesheetLink>() { @Override public StylesheetLink map(Asset input) { return new StylesheetLink(input); }; }; final Mapper<String, StylesheetLink> pathToStylesheetLink = pathToAsset.combine(assetToStylesheetLink); jqueryStack = F.flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.min.js", "${jquery.jqgrid.core.path}/jquery.noconflict.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery-ui-custom.min.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.contextmenu.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.layout.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.tablednd.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/ui.multiselect.js" ).map(pathToAsset).toList(); if (productionMode) { stylesheetStack = F.flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/css/ui.jqgrid.css") .map(pathToStylesheetLink).toList(); javaScriptStack = F .flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/js/jquery.jqgrid.min.js", "${jquery.jqgrid.core.path}/jqgrid.js") .map(pathToAsset).toList(); } else { stylesheetStack = F.flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/css/ui.jqgrid.css") .map(pathToStylesheetLink).toList(); javaScriptStack = F .flow("${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.base.js", // jqGrid base "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.common.js", // jqGrid common for editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.formedit.js", // jqGrid Form editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.inlinedit.js", // jqGrid inline editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.celledit.js", // jqGrid cell editing "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.subgrid.js", //jqGrid subgrid "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.treegrid.js", //jqGrid treegrid "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.grouping.js", //jqGrid grouping "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.custom.js", //jqGrid custom "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.tbltogrid.js", //jqGrid table to grid "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.import.js", //jqGrid import "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jquery.fmatter.js", //jqGrid formater "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/JsonXml.js", //xmljson utils "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.jqueryui.js", //jQuery UI utils "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.loader.js", //jqGrid loader "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.postext.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/grid.setcolumns.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jqDnR.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jqModal.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/ui.multiselect.js", "${jquery.jqgrid.core.path}/${jquery.jqgrid.version}/src/jquery.searchFilter.js", "${jquery.jqgrid.core.path}/jqgrid.js") .map(pathToAsset).toList(); } }
diff --git a/source/util/src/main/java/org/marketcetera/util/file/FileType.java b/source/util/src/main/java/org/marketcetera/util/file/FileType.java index ca7832cfc..6868a1f10 100644 --- a/source/util/src/main/java/org/marketcetera/util/file/FileType.java +++ b/source/util/src/main/java/org/marketcetera/util/file/FileType.java @@ -1,135 +1,135 @@ package org.marketcetera.util.file; import java.io.File; import java.io.IOException; import org.marketcetera.core.ClassVersion; /** * A file type. Files on NTFS are limited to the following types: * {@link #NONEXISTENT}, {@link #FILE}, {@link #DIR} (folder), and * {@link #UNKNOWN} (the file may or may not exist, and, if it does, * its type cannot be determined). On Unix systems, unresolvable * (dangling or recursive) links are {@link #NONEXISTENT}. * * @author tlerios * @version $Id$ */ /* $License$ */ @ClassVersion("$Id$") public enum FileType { NONEXISTENT, LINK_FILE, FILE, LINK_DIR, DIR, UNKNOWN; // CLASS METHODS. /** * Returns the enumerated constant representing the type of the * given file. * * @param file The file. It may be null, in which case * {@link #UNKNOWN} is returned. * * @return The enumerated constant. */ public static final FileType get (File file) { if (file==null) { return UNKNOWN; } try { if (!file.exists()) { return NONEXISTENT; } if (file.getCanonicalFile().equals(file.getAbsoluteFile())) { if (file.isDirectory()) { return DIR; } if (file.isFile()) { return FILE; } } else { if (file.isDirectory()) { return LINK_DIR; } if (file.isFile()) { return LINK_FILE; } } } catch (IOException ex) { - Messages.LOGGER.error + Messages.LOGGER.warn (FileType.class,ex,Messages.CANNOT_GET_TYPE, file.getAbsolutePath()); } return UNKNOWN; } /** * Returns the enumerated constant representing the type of the * file with the given name. * * @param name The file name. It may be null, in which case {@link * #UNKNOWN} is returned. * * @return The enumerated constant. */ public static final FileType get (String name) { if (name==null) { return UNKNOWN; } return get(new File(name)); } // INSTANCE METHODS. /** * Returns true if the receiver represents a symbolic link. * * @return True if so. */ public boolean isSymbolicLink() { return ((this==LINK_FILE) || (this==LINK_DIR)); } /** * Returns true if the receiver represents a directory (possibly * via a symbolic link). * * @return True if so. */ public boolean isDirectory() { return ((this==LINK_DIR) || (this==DIR)); } /** * Returns true if the receiver represents a plain file (possibly * via a symbolic link). * * @return True if so. */ public boolean isFile() { return ((this==LINK_FILE) || (this==FILE)); } }
true
true
public static final FileType get (File file) { if (file==null) { return UNKNOWN; } try { if (!file.exists()) { return NONEXISTENT; } if (file.getCanonicalFile().equals(file.getAbsoluteFile())) { if (file.isDirectory()) { return DIR; } if (file.isFile()) { return FILE; } } else { if (file.isDirectory()) { return LINK_DIR; } if (file.isFile()) { return LINK_FILE; } } } catch (IOException ex) { Messages.LOGGER.error (FileType.class,ex,Messages.CANNOT_GET_TYPE, file.getAbsolutePath()); } return UNKNOWN; }
public static final FileType get (File file) { if (file==null) { return UNKNOWN; } try { if (!file.exists()) { return NONEXISTENT; } if (file.getCanonicalFile().equals(file.getAbsoluteFile())) { if (file.isDirectory()) { return DIR; } if (file.isFile()) { return FILE; } } else { if (file.isDirectory()) { return LINK_DIR; } if (file.isFile()) { return LINK_FILE; } } } catch (IOException ex) { Messages.LOGGER.warn (FileType.class,ex,Messages.CANNOT_GET_TYPE, file.getAbsolutePath()); } return UNKNOWN; }
diff --git a/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelServerImpl.java b/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelServerImpl.java index e247b7330..95ebe199f 100644 --- a/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelServerImpl.java +++ b/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelServerImpl.java @@ -1,758 +1,759 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ode.bpel.engine; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.xml.namespace.QName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ode.bom.wsdl.Definition4BPEL; import org.apache.ode.bpel.dao.BpelDAOConnection; import org.apache.ode.bpel.dao.BpelDAOConnectionFactory; import org.apache.ode.bpel.dao.ProcessDAO; import org.apache.ode.bpel.dd.*; import org.apache.ode.bpel.deploy.DeploymentServiceImpl; import org.apache.ode.bpel.deploy.DeploymentUnitImpl; import org.apache.ode.bpel.evt.BpelEvent; import org.apache.ode.bpel.explang.ConfigurationException; import org.apache.ode.bpel.iapi.BindingContext; import org.apache.ode.bpel.iapi.BpelEngine; import org.apache.ode.bpel.iapi.BpelEngineException; import org.apache.ode.bpel.iapi.BpelEventListener; import org.apache.ode.bpel.iapi.BpelServer; import org.apache.ode.bpel.iapi.DeploymentService; import org.apache.ode.bpel.iapi.DeploymentUnit; import org.apache.ode.bpel.iapi.Endpoint; import org.apache.ode.bpel.iapi.EndpointReferenceContext; import org.apache.ode.bpel.iapi.MessageExchangeContext; import org.apache.ode.bpel.iapi.Scheduler; import org.apache.ode.bpel.intercept.MessageExchangeInterceptor; import org.apache.ode.bpel.o.OExpressionLanguage; import org.apache.ode.bpel.o.OPartnerLink; import org.apache.ode.bpel.o.OProcess; import org.apache.ode.bpel.o.Serializer; import org.apache.ode.bpel.pmapi.BpelManagementFacade; import org.apache.ode.bpel.runtime.ExpressionLanguageRuntimeRegistry; import org.apache.ode.utils.msg.MessageBundle; /** * The BPEL server implementation. */ public class BpelServerImpl implements BpelServer { private static final Log __log = LogFactory.getLog(BpelServer.class); private static final Messages __msgs = MessageBundle.getMessages(Messages.class); private ReadWriteLock _mngmtLock = new ReentrantReadWriteLock(); private Contexts _contexts = new Contexts(); BpelEngineImpl _engine; private boolean _started; private boolean _initialized; private BpelDatabase _db; /** Should processes marked "active" in the DB be activated on server start? */ private boolean _autoActivate = false; private List<BpelEventListener> _listeners = new CopyOnWriteArrayList<BpelEventListener>(); private Map<QName, DeploymentUnitImpl> _deploymentUnits = new HashMap<QName,DeploymentUnitImpl>(); public BpelServerImpl() { } public void start() { _mngmtLock.writeLock().lock(); try { if (!_initialized) { String err = "start() called before init()!"; __log.fatal(err); throw new IllegalStateException(err); } if (_started) { if (__log.isDebugEnabled()) __log.debug("start() ignored -- already started"); return; } if (__log.isDebugEnabled()) { __log.debug("BPEL SERVER starting."); } _engine = new BpelEngineImpl(_contexts); if (_autoActivate) { List<QName> pids = findActive(); for (QName pid : pids) try { doActivateProcess(pid); } catch (Exception ex) { String msg = __msgs.msgProcessActivationError(pid); __log.error(msg, ex); } } //readState(); _contexts.scheduler.start(); _started = true; __log.info(__msgs.msgServerStarted()); } finally { _mngmtLock.writeLock().unlock(); } } public boolean undeploy(File file) { DeploymentUnit du = null; for (DeploymentUnitImpl deploymentUnit : new HashSet<DeploymentUnitImpl>(_deploymentUnits.values())) { if (deploymentUnit.getDeployDir().getName().equals(file.getName())) du = deploymentUnit; } if (du == null) { __log.warn("Couldn't deploy " + file.getName() + ", package was not found."); return false; } boolean success = true; for (QName pName : du.getProcessNames()) { success = success && undeploy(pName); } rm(du.getDeployDir()); for (QName pname : du.getProcessNames()) { _deploymentUnits.remove(pname); } return success; } private void rm(File f) { if (f.isDirectory()) { for (File child : f.listFiles()) rm(child); f.delete(); } else { f.delete(); } } public void registerBpelEventListener(BpelEventListener listener) { _listeners.add(listener); } public void unregisterBpelEventListener(BpelEventListener listener) { _listeners.remove(listener); } void fireEvent(BpelEvent event) { for (BpelEventListener l : _listeners) { l.onEvent(event); } } /** * Find the active processes in the database. * @return list of process qnames */ private List<QName> findActive() { try { return _db.exec(new BpelDatabase.Callable<List<QName>>() { public List<QName> run(BpelDAOConnection conn) throws Exception { Collection<ProcessDAO> proc = conn.processQuery(null); ArrayList<QName> list = new ArrayList<QName>(); for (ProcessDAO p : proc) if (p.isActive()) list.add(p.getProcessId()); return list; } }); } catch (Exception ex) { String msg = __msgs.msgDbError(); __log.error(msg, ex); throw new BpelEngineException(msg, ex); } } public void stop() { _mngmtLock.writeLock().lock(); try { if (!_started) { if (__log.isDebugEnabled()) __log.debug("stop() ignored -- already stopped"); return; } if (__log.isDebugEnabled()) { __log.debug("BPEL SERVER STOPPING"); } //writeState(); _contexts.scheduler.stop(); _engine = null; _started = false; __log.info(__msgs.msgServerStopped()); } finally { _mngmtLock.writeLock().unlock(); } } public boolean undeploy(final QName process) { _mngmtLock.writeLock().lock(); try { if (!_initialized) { String err = "Server must be initialized!"; __log.error(err); throw new IllegalStateException(err, null); } if (_engine != null) _engine.unregisterProcess(process); // Delete it from the database. boolean found = _db.exec(new BpelDatabase.Callable<Boolean>() { public Boolean run(BpelDAOConnection conn) throws Exception { ProcessDAO proc = conn.getProcess(process); if (proc != null) { proc.delete(); return true; } return false; } }); if (found) { __log.info(__msgs.msgProcessUndeployed(process)); return true; } return false; } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { __log.error(__msgs.msgProcessUndeployFailed(process), ex); throw new BpelEngineException(ex); } finally { _mngmtLock.writeLock().unlock(); } } /** * Load the parsed and compiled BPEL process definition from the database. * * @param processId * process identifier * @return process information from configuration database */ private OProcess loadProcess(final QName processId) { if (__log.isTraceEnabled()) { __log.trace("loadProcess: " + processId); } assert _initialized : "loadProcess() called before init()!"; byte[] bits; try { bits = _db.exec(new BpelDatabase.Callable<byte[]>() { public byte[] run(BpelDAOConnection daoc) throws Exception { ProcessDAO procdao = daoc.getProcess(processId); return procdao.getCompiledProcess(); } }); } catch (Exception e) { throw new BpelEngineException("", e); } InputStream is = new ByteArrayInputStream(bits); OProcess compiledProcess; try { Serializer ofh = new Serializer(is); compiledProcess = ofh.readOProcess(); } catch (Exception e) { String errmsg = __msgs.msgProcessLoadError(processId); __log.error(errmsg, e); throw new BpelEngineException(errmsg, e); } return compiledProcess; } public BpelManagementFacade getBpelManagementFacade() { return new BpelManagementFacadeImpl(_db, _engine, this); } public DeploymentService getDeploymentService() { return new DeploymentServiceImpl(this); } public void setMessageExchangeContext(MessageExchangeContext mexContext) throws BpelEngineException { _contexts.mexContext = mexContext; } public void setScheduler(Scheduler scheduler) throws BpelEngineException { _contexts.scheduler = scheduler; } public void setEndpointReferenceContext(EndpointReferenceContext eprContext) throws BpelEngineException { _contexts.eprContext = eprContext; } public void setDaoConnectionFactory(BpelDAOConnectionFactory daoCF) throws BpelEngineException { _contexts.dao = daoCF; } public void setBindingContext(BindingContext bc) { _contexts.bindingContext = bc; } public void init() throws BpelEngineException { _mngmtLock.writeLock().lock(); try { if (_initialized) throw new IllegalStateException("init() called twice."); if (__log.isDebugEnabled()) { __log.debug("BPEL SERVER initializing "); } _db = new BpelDatabase(_contexts.dao, _contexts.scheduler); _initialized = true; } finally { _mngmtLock.writeLock().unlock(); } } public void shutdown() throws BpelEngineException { } public BpelEngine getEngine() { acquireWorkLockForTx(); if (!_started) { __log.debug("call on getEngine() on server that has not been started!"); throw new IllegalStateException("Server must be started!"); } return _engine; } public void activate(final QName pid, boolean sticky) { if (__log.isTraceEnabled()) __log.trace("activate: " + pid); try { _mngmtLock.writeLock().lockInterruptibly(); } catch (InterruptedException ie) { __log.debug("activate() interrupted.", ie); throw new BpelEngineException(__msgs.msgOperationInterrupted()); } try { if (sticky) dbSetProcessActive(pid, true); doActivateProcess(pid); } finally { _mngmtLock.writeLock().unlock(); } } public void deactivate(QName pid, boolean sticky) throws BpelEngineException { if (__log.isTraceEnabled()) __log.trace("deactivate " + pid); try { _mngmtLock.writeLock().lockInterruptibly(); } catch (InterruptedException ie) { __log.debug("deactivate() interrupted.", ie); throw new BpelEngineException(__msgs.msgOperationInterrupted()); } try { if (sticky) dbSetProcessActive(pid, false); doActivateProcess(pid); } finally { _mngmtLock.writeLock().unlock(); } } /** * Activate the process in the engine. * * @param pid */ private void doActivateProcess(final QName pid) { _mngmtLock.writeLock().lock(); try { // If the process is already active, do nothing. if (_engine.isProcessRegistered(pid)) { __log.debug("skipping doActivateProcess(" + pid + ") -- process is already active"); return; } if (__log.isDebugEnabled()) __log.debug("Process " + pid + " is not active, creating new entry."); // Figure out where on the local file system we can find the // deployment directory for this process DeploymentUnitImpl du = _deploymentUnits.get(pid); if (du == null) { // Indicates process not deployed. String errmsg = "Process " + pid + " is not deployed, it cannot be activated"; __log.error(errmsg); throw new BpelEngineException(errmsg); } // Load the compiled process from the database, note we do not want // to recompile / or read from the file system as // the user could have changed it, thereby corrupting all the // previously instantiated processes OProcess compiledProcess = loadProcess(pid); TDeployment.Process deployInfo = du.getProcessDeployInfo(pid); if (deployInfo == null) { String errmsg = " <process> element not found in deployment descriptor for " + pid; __log.error(errmsg); throw new BpelEngineException(errmsg); } // Create an expression language registry for this process ExpressionLanguageRuntimeRegistry elangRegistry = new ExpressionLanguageRuntimeRegistry(); for (OExpressionLanguage elang : compiledProcess.expressionLanguages) { try { elangRegistry.registerRuntime(elang); } catch (ConfigurationException e) { String msg = "Expression language registration error."; __log.error(msg, e); throw new BpelEngineException(msg, e); } } // Create local message-exchange interceptors. List<MessageExchangeInterceptor> localMexInterceptors = new LinkedList<MessageExchangeInterceptor>(); - for (TMexInterceptor mexi : deployInfo.getMexInterceptors().getMexInterceptorList()) { - try { - Class cls = Class.forName(mexi.getClassName()); - localMexInterceptors.add((MessageExchangeInterceptor) cls.newInstance()); - } catch (Throwable t) { - String errmsg = "Error instantiating message-exchange interceptor " + mexi.getClassName(); - __log.error(errmsg,t); + if (deployInfo.getMexInterceptors() != null) + for (TMexInterceptor mexi : deployInfo.getMexInterceptors().getMexInterceptorList()) { + try { + Class cls = Class.forName(mexi.getClassName()); + localMexInterceptors.add((MessageExchangeInterceptor) cls.newInstance()); + } catch (Throwable t) { + String errmsg = "Error instantiating message-exchange interceptor " + mexi.getClassName(); + __log.error(errmsg,t); + } } - } // Create myRole endpoint name mapping (from deployment descriptor) HashMap<OPartnerLink, Endpoint> myRoleEndpoints = new HashMap<OPartnerLink, Endpoint>(); for (TProvide provide : deployInfo.getProvideList()) { String plinkName = provide.getPartnerLink(); TService service = provide.getService(); if (service == null) { // TODO: proper error message. String errmsg = "Error in <provide> element for process " + pid + "; partnerlink " + plinkName + "did not identify an endpoint"; __log.error(errmsg); throw new BpelEngineException(errmsg); } __log.debug("Processing <provide> element for process " + pid + ": partnerlink " + plinkName + " --> " + service.getName() + " : " + service.getPort()); OPartnerLink plink = compiledProcess.getPartnerLink(plinkName); if (plink == null) { String errmsg = "Error in deployment descriptor for process " + pid + "; reference to unknown partner link " + plinkName; __log.error(errmsg); throw new BpelEngineException(errmsg); } myRoleEndpoints.put(plink,new Endpoint(service.getName(), service.getPort())); } // Create partnerRole initial value mapping HashMap<OPartnerLink, Endpoint> partnerRoleIntialValues = new HashMap<OPartnerLink, Endpoint>(); for (TInvoke invoke : deployInfo.getInvokeList()) { String plinkName = invoke.getPartnerLink(); OPartnerLink plink = compiledProcess.getPartnerLink(plinkName); if (plink == null) { String errmsg = "Error in deployment descriptor for process " + pid + "; reference to unknown partner link " + plinkName; __log.error(errmsg); throw new BpelEngineException(errmsg); } TService service = invoke.getService(); // NOTE: service can be null for partner links if (service == null) continue; __log.debug("Processing <invoke> element for process " + pid + ": partnerlink " + plinkName + " --> " + service); partnerRoleIntialValues.put(plink, new Endpoint(service.getName(), service.getPort())); } BpelProcess process = new BpelProcess(pid, du, compiledProcess, myRoleEndpoints, partnerRoleIntialValues, null, elangRegistry, localMexInterceptors); _engine.registerProcess(process); __log.info(__msgs.msgProcessActivated(pid)); } finally { _mngmtLock.writeLock().unlock(); } } public DeploymentUnit getDeploymentUnit(QName pid) { return _deploymentUnits.get(pid); } public Collection<DeploymentUnit> getDeploymentUnits() { ArrayList<DeploymentUnit> dus = new ArrayList<DeploymentUnit>(_deploymentUnits.size()); for (DeploymentUnitImpl du : _deploymentUnits.values()) { dus.add(du); } return dus; } private void dbSetProcessActive(final QName pid, final boolean val) { if (__log.isTraceEnabled()) __log.trace("dbSetProcessActive:" + pid + " = " + val); try { if (_db.exec(new BpelDatabase.Callable<ProcessDAO>() { public ProcessDAO run(BpelDAOConnection conn) throws Exception { // Hack, but at least for now we need to ensure that we are // the only // process with this process id. ProcessDAO pdao = conn.getProcess(pid); if (pdao == null) return null; pdao.setActive(val); return pdao; } }) == null) { String errmsg = __msgs.msgProcessNotFound(pid); __log.error(errmsg); throw new BpelEngineException(errmsg, null); } } catch (BpelEngineException bpe) { throw bpe; } catch (Exception ex) { String errmsg = __msgs.msgDbError(); __log.error(errmsg); throw new BpelEngineException(ex); } } /** * Deploys a process. */ public Collection<QName> deploy(File deploymentUnitDirectory) { __log.info(__msgs.msgDeployStarting(deploymentUnitDirectory)); DeploymentUnitImpl du = new DeploymentUnitImpl(deploymentUnitDirectory); ArrayList<QName> deployed = new ArrayList<QName> (); BpelEngineException failed = null; // Going trough each process declared in the dd for (TDeployment.Process processDD : du.getDeploymentDescriptor().getDeploy().getProcessList()) { // If a type is not specified, assume the process id is also the type. QName type = processDD.getType() != null ? processDD.getType() : processDD.getName(); OProcess oprocess = du.getProcesses().get(type); if (oprocess == null) throw new BpelEngineException("Could not find the compiled process definition for BPEL" + "type " + type + " when deploying process " + processDD.getName() + " in " + deploymentUnitDirectory); try { deploy(processDD.getName(), du, oprocess, du.getDocRegistry() .getDefinitions(), processDD); deployed.add(processDD.getName()); } catch (Throwable e) { String errmsg = __msgs.msgDeployFailed(processDD.getName(), deploymentUnitDirectory); __log.error(errmsg, e); failed = new BpelEngineException(errmsg,e); break; } } // Roll back succesfull deployments if we failed. if (failed != null) { if (!deployed.isEmpty()) { __log.error(__msgs.msgDeployRollback(deploymentUnitDirectory)); for (QName pid : deployed) { try { undeploy(pid); } catch (Throwable t) { __log.fatal("Unexpect error undeploying process " + pid, t); } } } throw failed; } else return du.getProcesses().keySet(); } private void deploy(final QName processId, final DeploymentUnitImpl du, final OProcess oprocess, final Definition4BPEL[] defs, TDeployment.Process processDD) { // First, make sure we are undeployed. undeploy(processId); Serializer serializer = new Serializer(oprocess.compileDate.getTime(), 1); final byte[] bits; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); serializer.write(bos); serializer.writeOProcess(oprocess, bos); bos.close(); bits = bos.toByteArray(); } catch (Exception ex) { String errmsg = "Error re-serializing CBP"; __log.fatal(errmsg, ex); throw new BpelEngineException(errmsg, ex); } final ProcessDDInitializer pi = new ProcessDDInitializer(oprocess, processDD); try { _db.exec(new BpelDatabase.Callable<ProcessDAO>() { public ProcessDAO run(BpelDAOConnection conn) throws Exception { // Hack, but at least for now we need to ensure that we are // the only process with this process id. ProcessDAO old = conn.getProcess(processId); if (old != null) { String errmsg = __msgs.msgProcessDeployErrAlreadyDeployed(processId); __log.error(errmsg); throw new BpelEngineException(errmsg); } ProcessDAO newDao = conn.createProcess(processId, oprocess.getQName()); newDao.setCompiledProcess(bits); pi.init(newDao); pi.update(newDao); return newDao; } }); __log.info(__msgs.msgProcessDeployed(processId)); } catch (BpelEngineException ex) { throw ex; } catch (Exception dce) { __log.error("", dce); throw new BpelEngineException("", dce); } _deploymentUnits.put(processDD.getName(), du); doActivateProcess(processId); } /** * Acquire a work lock for the current transaction, releasing the lock once * the transaction completes. */ private void acquireWorkLockForTx() { // TODO We need to have support for a TransactionContext in order to // do this. } /** * Get the flag that determines whether processes marked as active are * automatically activated at startup. * * @return */ public boolean isAutoActivate() { return _autoActivate; } /** * Set the flag the determines whether processes marked as active are * automatically activated at startup. * * @param autoActivate */ public void setAutoActivate(boolean autoActivate) { _autoActivate = autoActivate; } /** * Register a global message exchange interceptor. * @param interceptor message-exchange interceptor */ public void registerMessageExchangeInterceptor(MessageExchangeInterceptor interceptor) { // We don't really care all that much about concurrency here, we just want to // avoid ConcurrentModificationEx, so use an array instead of a collection. synchronized(_contexts) { MessageExchangeInterceptor[] r = new MessageExchangeInterceptor[1+_contexts.globalIntereceptors.length]; System.arraycopy(_contexts.globalIntereceptors,0,r,0,_contexts.globalIntereceptors.length); r[r.length-1] = interceptor; _contexts.globalIntereceptors = r; } } }
false
true
private void doActivateProcess(final QName pid) { _mngmtLock.writeLock().lock(); try { // If the process is already active, do nothing. if (_engine.isProcessRegistered(pid)) { __log.debug("skipping doActivateProcess(" + pid + ") -- process is already active"); return; } if (__log.isDebugEnabled()) __log.debug("Process " + pid + " is not active, creating new entry."); // Figure out where on the local file system we can find the // deployment directory for this process DeploymentUnitImpl du = _deploymentUnits.get(pid); if (du == null) { // Indicates process not deployed. String errmsg = "Process " + pid + " is not deployed, it cannot be activated"; __log.error(errmsg); throw new BpelEngineException(errmsg); } // Load the compiled process from the database, note we do not want // to recompile / or read from the file system as // the user could have changed it, thereby corrupting all the // previously instantiated processes OProcess compiledProcess = loadProcess(pid); TDeployment.Process deployInfo = du.getProcessDeployInfo(pid); if (deployInfo == null) { String errmsg = " <process> element not found in deployment descriptor for " + pid; __log.error(errmsg); throw new BpelEngineException(errmsg); } // Create an expression language registry for this process ExpressionLanguageRuntimeRegistry elangRegistry = new ExpressionLanguageRuntimeRegistry(); for (OExpressionLanguage elang : compiledProcess.expressionLanguages) { try { elangRegistry.registerRuntime(elang); } catch (ConfigurationException e) { String msg = "Expression language registration error."; __log.error(msg, e); throw new BpelEngineException(msg, e); } } // Create local message-exchange interceptors. List<MessageExchangeInterceptor> localMexInterceptors = new LinkedList<MessageExchangeInterceptor>(); for (TMexInterceptor mexi : deployInfo.getMexInterceptors().getMexInterceptorList()) { try { Class cls = Class.forName(mexi.getClassName()); localMexInterceptors.add((MessageExchangeInterceptor) cls.newInstance()); } catch (Throwable t) { String errmsg = "Error instantiating message-exchange interceptor " + mexi.getClassName(); __log.error(errmsg,t); } } // Create myRole endpoint name mapping (from deployment descriptor) HashMap<OPartnerLink, Endpoint> myRoleEndpoints = new HashMap<OPartnerLink, Endpoint>(); for (TProvide provide : deployInfo.getProvideList()) { String plinkName = provide.getPartnerLink(); TService service = provide.getService(); if (service == null) { // TODO: proper error message. String errmsg = "Error in <provide> element for process " + pid + "; partnerlink " + plinkName + "did not identify an endpoint"; __log.error(errmsg); throw new BpelEngineException(errmsg); } __log.debug("Processing <provide> element for process " + pid + ": partnerlink " + plinkName + " --> " + service.getName() + " : " + service.getPort()); OPartnerLink plink = compiledProcess.getPartnerLink(plinkName); if (plink == null) { String errmsg = "Error in deployment descriptor for process " + pid + "; reference to unknown partner link " + plinkName; __log.error(errmsg); throw new BpelEngineException(errmsg); } myRoleEndpoints.put(plink,new Endpoint(service.getName(), service.getPort())); } // Create partnerRole initial value mapping HashMap<OPartnerLink, Endpoint> partnerRoleIntialValues = new HashMap<OPartnerLink, Endpoint>(); for (TInvoke invoke : deployInfo.getInvokeList()) { String plinkName = invoke.getPartnerLink(); OPartnerLink plink = compiledProcess.getPartnerLink(plinkName); if (plink == null) { String errmsg = "Error in deployment descriptor for process " + pid + "; reference to unknown partner link " + plinkName; __log.error(errmsg); throw new BpelEngineException(errmsg); } TService service = invoke.getService(); // NOTE: service can be null for partner links if (service == null) continue; __log.debug("Processing <invoke> element for process " + pid + ": partnerlink " + plinkName + " --> " + service); partnerRoleIntialValues.put(plink, new Endpoint(service.getName(), service.getPort())); } BpelProcess process = new BpelProcess(pid, du, compiledProcess, myRoleEndpoints, partnerRoleIntialValues, null, elangRegistry, localMexInterceptors); _engine.registerProcess(process); __log.info(__msgs.msgProcessActivated(pid)); } finally { _mngmtLock.writeLock().unlock(); } }
private void doActivateProcess(final QName pid) { _mngmtLock.writeLock().lock(); try { // If the process is already active, do nothing. if (_engine.isProcessRegistered(pid)) { __log.debug("skipping doActivateProcess(" + pid + ") -- process is already active"); return; } if (__log.isDebugEnabled()) __log.debug("Process " + pid + " is not active, creating new entry."); // Figure out where on the local file system we can find the // deployment directory for this process DeploymentUnitImpl du = _deploymentUnits.get(pid); if (du == null) { // Indicates process not deployed. String errmsg = "Process " + pid + " is not deployed, it cannot be activated"; __log.error(errmsg); throw new BpelEngineException(errmsg); } // Load the compiled process from the database, note we do not want // to recompile / or read from the file system as // the user could have changed it, thereby corrupting all the // previously instantiated processes OProcess compiledProcess = loadProcess(pid); TDeployment.Process deployInfo = du.getProcessDeployInfo(pid); if (deployInfo == null) { String errmsg = " <process> element not found in deployment descriptor for " + pid; __log.error(errmsg); throw new BpelEngineException(errmsg); } // Create an expression language registry for this process ExpressionLanguageRuntimeRegistry elangRegistry = new ExpressionLanguageRuntimeRegistry(); for (OExpressionLanguage elang : compiledProcess.expressionLanguages) { try { elangRegistry.registerRuntime(elang); } catch (ConfigurationException e) { String msg = "Expression language registration error."; __log.error(msg, e); throw new BpelEngineException(msg, e); } } // Create local message-exchange interceptors. List<MessageExchangeInterceptor> localMexInterceptors = new LinkedList<MessageExchangeInterceptor>(); if (deployInfo.getMexInterceptors() != null) for (TMexInterceptor mexi : deployInfo.getMexInterceptors().getMexInterceptorList()) { try { Class cls = Class.forName(mexi.getClassName()); localMexInterceptors.add((MessageExchangeInterceptor) cls.newInstance()); } catch (Throwable t) { String errmsg = "Error instantiating message-exchange interceptor " + mexi.getClassName(); __log.error(errmsg,t); } } // Create myRole endpoint name mapping (from deployment descriptor) HashMap<OPartnerLink, Endpoint> myRoleEndpoints = new HashMap<OPartnerLink, Endpoint>(); for (TProvide provide : deployInfo.getProvideList()) { String plinkName = provide.getPartnerLink(); TService service = provide.getService(); if (service == null) { // TODO: proper error message. String errmsg = "Error in <provide> element for process " + pid + "; partnerlink " + plinkName + "did not identify an endpoint"; __log.error(errmsg); throw new BpelEngineException(errmsg); } __log.debug("Processing <provide> element for process " + pid + ": partnerlink " + plinkName + " --> " + service.getName() + " : " + service.getPort()); OPartnerLink plink = compiledProcess.getPartnerLink(plinkName); if (plink == null) { String errmsg = "Error in deployment descriptor for process " + pid + "; reference to unknown partner link " + plinkName; __log.error(errmsg); throw new BpelEngineException(errmsg); } myRoleEndpoints.put(plink,new Endpoint(service.getName(), service.getPort())); } // Create partnerRole initial value mapping HashMap<OPartnerLink, Endpoint> partnerRoleIntialValues = new HashMap<OPartnerLink, Endpoint>(); for (TInvoke invoke : deployInfo.getInvokeList()) { String plinkName = invoke.getPartnerLink(); OPartnerLink plink = compiledProcess.getPartnerLink(plinkName); if (plink == null) { String errmsg = "Error in deployment descriptor for process " + pid + "; reference to unknown partner link " + plinkName; __log.error(errmsg); throw new BpelEngineException(errmsg); } TService service = invoke.getService(); // NOTE: service can be null for partner links if (service == null) continue; __log.debug("Processing <invoke> element for process " + pid + ": partnerlink " + plinkName + " --> " + service); partnerRoleIntialValues.put(plink, new Endpoint(service.getName(), service.getPort())); } BpelProcess process = new BpelProcess(pid, du, compiledProcess, myRoleEndpoints, partnerRoleIntialValues, null, elangRegistry, localMexInterceptors); _engine.registerProcess(process); __log.info(__msgs.msgProcessActivated(pid)); } finally { _mngmtLock.writeLock().unlock(); } }
diff --git a/src/webapp/src/java/org/wyona/yanel/servlet/YanelServlet.java b/src/webapp/src/java/org/wyona/yanel/servlet/YanelServlet.java index 34b47bd66..02d397b63 100644 --- a/src/webapp/src/java/org/wyona/yanel/servlet/YanelServlet.java +++ b/src/webapp/src/java/org/wyona/yanel/servlet/YanelServlet.java @@ -1,2302 +1,2302 @@ package org.wyona.yanel.servlet; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.BufferedReader; import java.io.InputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.net.URL; import java.util.Calendar; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import java.util.Vector; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamSource; import org.wyona.yanel.core.StateOfView; import org.wyona.yanel.core.Environment; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeIdentifier; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.Yanel; import org.wyona.yanel.core.api.attributes.IntrospectableV1; import org.wyona.yanel.core.api.attributes.ModifiableV1; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.TranslatableV1; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.api.attributes.WorkflowableV1; import org.wyona.yanel.core.api.security.WebAuthenticator; import org.wyona.yanel.core.attributes.versionable.RevisionInformation; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.navigation.Node; import org.wyona.yanel.core.navigation.Sitetree; import org.wyona.yanel.core.serialization.SerializerFactory; import org.wyona.yanel.core.source.SourceResolver; import org.wyona.yanel.core.transformation.I18nTransformer2; import org.wyona.yanel.core.util.DateUtil; import org.wyona.yanel.core.workflow.WorkflowException; import org.wyona.yanel.core.workflow.WorkflowHelper; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.wyona.yanel.servlet.IdentityMap; import org.wyona.yanel.servlet.communication.HttpRequest; import org.wyona.yanel.servlet.communication.HttpResponse; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.IdentityManager; import org.wyona.security.core.api.Policy; import org.wyona.security.core.api.PolicyManager; import org.wyona.security.core.api.Role; import org.wyona.security.core.api.Usecase; import org.wyona.security.core.api.User; import org.apache.log4j.Category; import org.apache.xalan.transformer.TransformerIdentityImpl; import org.apache.xml.resolver.tools.CatalogResolver; import org.apache.xml.serializer.Serializer; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; import org.apache.commons.io.FilenameUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * */ public class YanelServlet extends HttpServlet { private static Category log = Category.getInstance(YanelServlet.class); private ServletConfig config; ResourceTypeRegistry rtr; //PolicyManager pm; //IdentityManager im; Map map; Yanel yanel; Sitetree sitetree; File xsltInfoAndException; String xsltLoginScreenDefault; public static String IDENTITY_MAP_KEY = "identity-map"; private static String TOOLBAR_KEY = "toolbar"; private static String TOOLBAR_USECASE = "toolbar"; public static String NAMESPACE = "http://www.wyona.org/yanel/1.0"; private static final String METHOD_PROPFIND = "PROPFIND"; private static final String METHOD_OPTIONS = "OPTIONS"; private static final String METHOD_GET = "GET"; private static final String METHOD_POST = "POST"; private static final String METHOD_PUT = "PUT"; private static final String METHOD_DELETE = "DELETE"; private static final int INSIDE_TAG = 0; private static final int OUTSIDE_TAG = 1; private String sslPort = null; private String toolbarMasterSwitch = "off"; private String reservedPrefix; private String servletContextRealPath; private int cacheExpires = 0; public static final String DEFAULT_ENCODING = "UTF-8"; public static final String VIEW_ID_PARAM_NAME = "yanel.resource.viewid"; /** * */ public void init(ServletConfig config) throws ServletException { this.config = config; servletContextRealPath = config.getServletContext().getRealPath("/"); xsltInfoAndException = org.wyona.commons.io.FileUtil.file(servletContextRealPath, config.getInitParameter("exception-and-info-screen-xslt")); xsltLoginScreenDefault = config.getInitParameter("login-screen-xslt"); try { yanel = Yanel.getInstance(); yanel.init(); rtr = yanel.getResourceTypeRegistry(); map = (Map) yanel.getBeanFactory().getBean("map"); sitetree = (Sitetree) yanel.getBeanFactory().getBean("repo-navigation"); sslPort = config.getInitParameter("ssl-port"); toolbarMasterSwitch = config.getInitParameter("toolbar-master-switch"); reservedPrefix = yanel.getReservedPrefix(); String expires = config.getInitParameter("static-content-cache-expires"); if (expires != null) { this.cacheExpires = Integer.parseInt(expires); } } catch (Exception e) { log.error(e); throw new ServletException(e.getMessage(), e); } } /** * Dispatch requests */ public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); String httpAcceptLanguage = request.getHeader("Accept-Language"); String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("logout")) { // Logout from Yanel if(doLogout(request, response) != null) return; } else if(yanelUsecase != null && yanelUsecase.equals("create")) { // Create a new resource if(doCreate(request, response) != null) return; } // Check authorization and if authorization failed, then try to authenticate if(doAccessControl(request, response) != null) { // Either redirect (after successful authentication) or access denied (and response will send the login screen) return; } else { if (log.isDebugEnabled()) log.debug("Access granted: " + request.getServletPath()); } // Check for requests re policies String policyRequestPara = request.getParameter("yanel.policy"); if (policyRequestPara != null) { doAccessPolicyRequest(request, response, policyRequestPara); return; } // Check for requests for global data Resource resource = getResource(request, response); String path = resource.getPath(); if (path.indexOf("/" + reservedPrefix + "/") == 0) { getGlobalData(request, response); return; } String value = request.getParameter("yanel.resource.usecase"); // Delete node if (value != null && value.equals("delete")) { handleDeleteUsecase(request, response); return; } // Delegate ... String method = request.getMethod(); if (method.equals(METHOD_PROPFIND)) { doPropfind(request, response); } else if (method.equals(METHOD_GET)) { doGet(request, response); } else if (method.equals(METHOD_POST)) { doPost(request, response); } else if (method.equals(METHOD_PUT)) { doPut(request, response); } else if (method.equals(METHOD_DELETE)) { doDelete(request, response); } else if (method.equals(METHOD_OPTIONS)) { doOptions(request, response); } else { log.error("No such method implemented: " + method); response.sendError(response.SC_NOT_IMPLEMENTED); } } /** * */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); Resource resource = getResource(request, response); // Enable or disable toolbar switchToolbar(request); // Check for requests refered by WebDAV String yanelWebDAV = request.getParameter("yanel.webdav"); if(yanelWebDAV != null && yanelWebDAV.equals("propfind1")) { log.error("DEBUG: WebDAV client (" + request.getHeader("User-Agent") + ") requests to \"edit\" a resource: " + resource.getRealm() + ", " + resource.getPath()); //return; } String value = request.getParameter("yanel.resource.usecase"); try { if (value != null && value.equals("release-lock")) { log.debug("Release lock ..."); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { VersionableV2 versionable = (VersionableV2)resource; try { versionable.cancelCheckout(); } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException("Releasing of lock failed because of: " + resource.getPath() + " " + e.getMessage(), e); } } return; } else { getContent(request, response); return; } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } /** * Checks if the yanel.toolbar request parameter is set and stores * the value of the parameter in the session. * @param request */ private void switchToolbar(HttpServletRequest request) { // Check for toolbar ... String yanelToolbar = request.getParameter("yanel.toolbar"); if(yanelToolbar != null) { HttpSession session = request.getSession(false); if (yanelToolbar.equals("on")) { log.info("Turn on toolbar!"); enableToolbar(request); } else if (yanelToolbar.equals("off")) { log.info("Turn off toolbar!"); disableToolbar(request); } else { log.warn("No such toolbar value: " + yanelToolbar); } } } /** * Returns the mime-type according to the given file extension. * Default is application/octet-stream. * @param extension * @return */ private String guessMimeType(String extension) { String ext = extension.toLowerCase(); if (ext.equals("html") || ext.equals("htm")) return "text/html"; if (ext.equals("css")) return "text/css"; if (ext.equals("txt")) return "text/plain"; if (ext.equals("js")) return "application/x-javascript"; if (ext.equals("jpg") || ext.equals("jpg")) return "image/jpeg"; if (ext.equals("gif")) return "image/gif"; if (ext.equals("pdf")) return "application/pdf"; if (ext.equals("zip")) return "application/zip"; if (ext.equals("htc")) return "text/x-component"; // TODO: add more mime types // TODO: and move to MimeTypeUtil return "application/octet-stream"; // default } /** * Get view of resource */ private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { View view = null; org.w3c.dom.Document doc = null; try { doc = getDocument(NAMESPACE, "yanel"); } catch(Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } Element rootElement = doc.getDocumentElement(); rootElement.setAttribute("servlet-context-real-path", servletContextRealPath); Element requestElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "request")); requestElement.setAttributeNS(NAMESPACE, "uri", request.getRequestURI()); requestElement.setAttributeNS(NAMESPACE, "servlet-path", request.getServletPath()); HttpSession session = request.getSession(true); Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session")); sessionElement.setAttribute("id", session.getId()); Enumeration attrNames = session.getAttributeNames(); if (!attrNames.hasMoreElements()) { Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes")); } while (attrNames.hasMoreElements()) { String name = (String)attrNames.nextElement(); String value = session.getAttribute(name).toString(); Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute")); sessionAttributeElement.setAttribute("name", name); sessionAttributeElement.appendChild(doc.createTextNode(value)); } String usecase = request.getParameter("yanel.resource.usecase"); Resource res = null; long lastModified = -1; long size = -1; try { Environment environment = getEnvironment(request, response); res = getResource(request, response); if (res != null) { Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource")); ResourceConfiguration resConfig = res.getConfiguration(); if (resConfig != null) { Element resConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "config")); resConfigElement.setAttributeNS(NAMESPACE, "rti-name", resConfig.getName()); resConfigElement.setAttributeNS(NAMESPACE, "rti-namespace", resConfig.getNamespace()); } else { Element noResConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "no-config")); } Element realmElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "realm")); realmElement.setAttributeNS(NAMESPACE, "name", res.getRealm().getName()); realmElement.setAttributeNS(NAMESPACE, "rid", res.getRealm().getID()); realmElement.setAttributeNS(NAMESPACE, "prefix", res.getRealm().getMountPoint()); Element identityManagerElement = (Element) realmElement.appendChild(doc.createElementNS(NAMESPACE, "identity-manager")); Element userManagerElement = (Element) identityManagerElement.appendChild(doc.createElementNS(NAMESPACE, "user-manager")); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { if (log.isDebugEnabled()) log.debug("Resource is viewable V1"); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.setAttributeNS(NAMESPACE, "version", "1"); // TODO: The same as for ViewableV2 ... ViewDescriptor[] vd = ((ViewableV1) res).getViewDescriptors(); if (vd != null) { for (int i = 0; i < vd.length; i++) { Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor")); if (vd[i].getMimeType() != null) { descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType())); } descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId()); } } else { viewElement.appendChild(doc.createTextNode("No View Descriptors!")); } String viewId = request.getParameter(VIEW_ID_PARAM_NAME); try { view = ((ViewableV1) res).getView(request, viewId); } catch(org.wyona.yarep.core.NoSuchNodeException e) { do404(request, response, doc, e.getMessage()); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "500"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) { if (log.isDebugEnabled()) log.debug("Resource is viewable V2"); if (!((ViewableV2) res).exists()) { //log.warn("No such ViewableV2 resource: " + res.getPath()); //log.warn("TODO: It seems like many ViewableV2 resources are not implementing exists() properly!"); //do404(request, response, doc, res.getPath()); //return; } String viewId = request.getParameter(VIEW_ID_PARAM_NAME); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.setAttributeNS(NAMESPACE, "version", "2"); ViewDescriptor[] vd = ((ViewableV2) res).getViewDescriptors(); if (vd != null) { for (int i = 0; i < vd.length; i++) { Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor")); if (vd[i].getMimeType() != null) { descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType())); } descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId()); } } else { viewElement.appendChild(doc.createTextNode("No View Descriptors!")); } size = ((ViewableV2) res).getSize(); Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size")); sizeElement.appendChild(doc.createTextNode(String.valueOf(size))); try { String revisionName = request.getParameter("yanel.resource.revision"); if (revisionName != null && ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { view = ((VersionableV2) res).getView(viewId, revisionName); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1") && environment.getStateOfView().equals(StateOfView.LIVE)) { WorkflowableV1 workflowable = (WorkflowableV1)res; if (workflowable.isLive()) { view = workflowable.getLiveView(viewId); } else { - String message = "The resource '" + res.getPath() + "' is WorkflowableV1, but has not been published yet. Instead a live version, the most recent version will be displayed!"; + String message = "The resource '" + res.getPath() + "' is WorkflowableV1, but has not been published yet. Instead the live version, the most recent version will be displayed!"; log.warn(message); view = ((ViewableV2) res).getView(viewId); // TODO: Maybe sending a 404 instead the most recent version should be configurable! /* do404(request, response, doc, message); return; */ } } else { view = ((ViewableV2) res).getView(viewId); } } catch(org.wyona.yarep.core.NoSuchNodeException e) { String message = "" + e; log.warn(message); do404(request, response, doc, message); return; } catch(org.wyona.yanel.core.ResourceNotFoundException e) { String message = "" + e; log.warn(message); do404(request, response, doc, message); return; } } else { Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("not-viewable")); String message = res.getClass().getName() + " is not viewable! (" + res.getPath() + ", " + res.getRealm() + ")"; noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!")); log.error(message); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "501"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED); setYanelOutput(request, response, doc); return; } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { lastModified = ((ModifiableV2) res).getLastModified(); Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified")); lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString())); } else { Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // retrieve the revisions, but only in the meta usecase (for performance reasons): if (request.getParameter("yanel.resource.meta") != null) { RevisionInformation[] revisions = ((VersionableV2)res).getRevisions(); Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement("revisions")); if (revisions != null && revisions.length > 0) { for (int i = revisions.length - 1; i >= 0; i--) { Element revisionElement = (Element) revisionsElement.appendChild(doc.createElement("revision")); Element revisionNameElement = (Element) revisionElement.appendChild(doc.createElement("name")); revisionNameElement.appendChild(doc.createTextNode(revisions[i].getName())); Element revisionDateElement = (Element) revisionElement.appendChild(doc.createElement("date")); revisionDateElement.appendChild(doc.createTextNode(DateUtil.format(revisions[i].getDate()))); Element revisionUserElement = (Element) revisionElement.appendChild(doc.createElement("user")); revisionUserElement.appendChild(doc.createTextNode(revisions[i].getUser())); Element revisionCommentElement = (Element) revisionElement.appendChild(doc.createElement("comment")); revisionCommentElement.appendChild(doc.createTextNode(revisions[i].getComment())); } } else { Element noRevisionsYetElement = (Element) resourceElement.appendChild(doc.createElement("no-revisions-yet")); } } } else { Element notVersionableElement = (Element) resourceElement.appendChild(doc.createElement("not-versionable")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Translatable", "1")) { TranslatableV1 translatable = ((TranslatableV1) res); Element translationsElement = (Element) resourceElement.appendChild(doc.createElement("translations")); String[] languages = translatable.getLanguages(); for (int i=0; i<languages.length; i++) { Element translationElement = (Element) translationsElement.appendChild(doc.createElement("translation")); translationElement.setAttribute("language", languages[i]); String path = translatable.getTranslation(languages[i]).getPath(); translationElement.setAttribute("path", path); } } if (usecase != null && usecase.equals("checkout")) { if(log.isDebugEnabled()) log.debug("Checkout data ..."); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // note: this will throw an exception if the document is checked out already // by another user. String userID = environment.getIdentity().getUsername(); VersionableV2 versionable = (VersionableV2)res; if (versionable.isCheckedOut()) { String checkoutUserID = versionable.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { log.warn("Resource " + res.getPath() + " is already checked out by this user: " + checkoutUserID); } else { throw new Exception("Resource is already checked out by another user: " + checkoutUserID); } } else { versionable.checkout(userID); } } else { log.warn("Acquire lock has not been implemented yet ...!"); // acquireLock(); } } } else { Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null")); } } catch(org.wyona.yarep.core.NoSuchNodeException e) { String message = "" + e; log.warn(e, e); do404(request, response, doc, message); return; } catch(org.wyona.yanel.core.ResourceNotFoundException e) { String message = "" + e; log.warn(e, e); do404(request, response, doc, message); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString() + "\n\n" + getStackTrace(e); //String message = e.toString(); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } // TODO: Move this introspection generation somewhere else ... try { if (usecase != null && usecase.equals("introspection")) { if (ResourceAttributeHelper.hasAttributeImplemented(res, "Introspectable", "1")) { String introspection = ((IntrospectableV1)res).getIntrospection(); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.getWriter().print(introspection); } else { String message = "Resource is not introspectable."; Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); } return; } } catch(Exception e) { log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(e.getMessage())); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } String meta = request.getParameter("yanel.resource.meta"); if (meta != null) { if (meta.length() > 0) { log.warn("TODO: meta: " + meta); } else { log.debug("Show all meta"); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); setYanelOutput(request, response, doc); return; } if (view != null) { if (generateResponse(view, res, request, response, doc, size, lastModified) != null) return; } else { String message = "View is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } /** * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String transition = request.getParameter("yanel.resource.workflow.transition"); if (transition != null) { Resource resource = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Workflowable", "1")) { WorkflowableV1 workflowable = (WorkflowableV1)resource; try { String revision = request.getParameter("yanel.resource.revision"); workflowable.doTransition(transition, revision); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append(workflowable.getWorkflowIntrospection()); PrintWriter w = response.getWriter(); w.print(sb); return; } catch (WorkflowException e) { // TODO: Implement response if transition has failed ... log.error(e, e); throw new ServletException(e.getMessage(), e); } } else { log.warn("Resource not workflowable: " + resource.getPath()); } } String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response, false); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response, true); log.warn("Release lock has not been implemented yet ..."); // releaseLock(); return; } else { log.info("No parameter yanel.resource.usecase!"); String contentType = request.getContentType(); // TODO: Check for type (see section 9.2 of APP spec (e.g. draft 16) if (contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); // Create new Atom entry try { String atomEntryUniversalName = "<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>"; Realm realm = yanel.getMap().getRealm(request.getServletPath()); String newEntryPath = yanel.getMap().getPath(realm, request.getServletPath() + "/" + new java.util.Date().getTime() + ".xml"); log.error("DEBUG: Realm and Path of new Atom entry: " + realm + " " + newEntryPath); Resource atomEntryResource = yanel.getResourceManager().getResource(getEnvironment(request, response), realm, newEntryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new ResourceTypeIdentifier(atomEntryUniversalName, null)); ((ModifiableV2)atomEntryResource).write(in); byte buffer[] = new byte[8192]; int bytesRead; InputStream resourceIn = ((ModifiableV2)atomEntryResource).getInputStream(); OutputStream responseOut = response.getOutputStream(); while ((bytesRead = resourceIn.read(buffer)) != -1) { responseOut.write(buffer, 0, bytesRead); } // TODO: Fix Location ... response.setHeader("Location", "http://ulysses.wyona.org" + newEntryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED); return; } catch (Exception e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage()); } } // Enable or disable toolbar switchToolbar(request); getContent(request, response); } } /** * HTTP PUT implementation */ public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO: Reuse code doPost resp. share code with doPut String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response, false); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response, true); log.warn("Release lock has not been implemented yet ...!"); // releaseLock(); return; } else { log.warn("No parameter yanel.resource.usecase!"); String contentType = request.getContentType(); if (contentType != null && contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); // Overwrite existing atom entry try { String atomEntryUniversalName = "<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>"; Realm realm = yanel.getMap().getRealm(request.getServletPath()); String entryPath = yanel.getMap().getPath(realm, request.getServletPath()); log.error("DEBUG: Realm and Path of new Atom entry: " + realm + " " + entryPath); Resource atomEntryResource = yanel.getResourceManager().getResource(getEnvironment(request, response), realm, entryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new ResourceTypeIdentifier(atomEntryUniversalName, null)); // TODO: There seems to be a problem ... ((ModifiableV2)atomEntryResource).write(in); // NOTE: This method does not update updated date /* OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath); byte buffer[] = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } */ log.info("Atom entry has been saved: " + entryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); return; } catch (Exception e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage()); } } else { Resource resource = getResource(request, response); log.error("DEBUG: Client (" + request.getHeader("User-Agent") + ") requests to save a resource: " + resource.getRealm() + ", " + resource.getPath()); save(request, response, false); return; } } } /** * HTTP DELETE implementation */ public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { if (((ModifiableV2) res).delete()) { // TODO: Also delete resource config! What about access policies?! log.debug("Resource has been deleted: " + res); response.setStatus(HttpServletResponse.SC_OK); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(res.getPath()); StringBuffer sb = new StringBuffer("<html><body>Page has been deleted! <a href=\"\">Check</a> or return to <a href=\"" + backToRealm + "\">Homepage</a>.</body></html>"); PrintWriter w = response.getWriter(); w.print(sb); return; } else { log.warn("Resource could not be deleted: " + res); response.setStatus(response.SC_FORBIDDEN); return; } } else { log.error("Resource '" + res + "' has interface ModifiableV2 not implemented." ); response.sendError(response.SC_NOT_IMPLEMENTED); return; } } catch (Exception e) { log.error("Could not delete resource with URL " + request.getRequestURL() + " " + e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } /** * */ private Resource getResource(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { Realm realm = map.getRealm(request.getServletPath()); String path = map.getPath(realm, request.getServletPath()); HttpRequest httpRequest = (HttpRequest)request; HttpResponse httpResponse = new HttpResponse(response); Resource res = yanel.getResourceManager().getResource(getEnvironment(httpRequest, httpResponse), realm, path); return res; } catch(Exception e) { String errorMsg = "Could not get resource for request: " + request.getServletPath() + ": " + e.getMessage(); log.error(errorMsg, e); throw new ServletException(errorMsg, e); } } /** * */ private Environment getEnvironment(HttpServletRequest request, HttpServletResponse response) throws ServletException { Identity identity; try { identity = getIdentity(request); Realm realm = map.getRealm(request.getServletPath()); String stateOfView = StateOfView.AUTHORING; if (isToolbarEnabled(request)) { stateOfView = StateOfView.AUTHORING; } else { stateOfView = StateOfView.LIVE; } //log.debug("State of view: " + stateOfView); Environment environment = new Environment(request, response, identity, stateOfView, null); return environment; } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } /** * Save data */ private void save(HttpServletRequest request, HttpServletResponse response, boolean doCheckin) throws ServletException, IOException { log.debug("Save data ..."); Resource resource = getResource(request, response); /* -> commented because the current default repo implementation does not support versioning yet. if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { try { // check the resource state: Identity identity = getIdentity(request); String userID = identity.getUser().getID(); VersionableV2 versionable = (VersionableV2)resource; if (versionable.isCheckedOut()) { String checkoutUserID = versionable.getCheckoutUserID(); if (!checkoutUserID.equals(userID)) { throw new Exception("Resource is checked out by another user: " + checkoutUserID); } } else { throw new Exception("Resource is not checked out."); } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } */ InputStream in = request.getInputStream(); // TODO: Should be delegated to resource type, e.g. <{http://...}xml/>! // Check on well-formedness ... String contentType = request.getContentType(); log.debug("Content-Type: " + contentType); if (contentType != null && (contentType.indexOf("application/xml") >= 0 || contentType.indexOf("application/xhtml+xml") >= 0)) { log.info("Check well-formedness ..."); javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); // TODO: Get log messages into log4j ... //parser.setErrorHandler(...); java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) // http://www-128.ibm.com/developerworks/java/library/j-io1/ byte[] memBuffer = baos.toByteArray(); // NOTE: DOCTYPE is being resolved/retrieved (e.g. xhtml schema from w3.org) also // if isValidating is set to false. // Hence, for performance and network reasons we use a local catalog ... // Also see http://www.xml.com/pub/a/2004/03/03/catalogs.html // resp. http://xml.apache.org/commons/components/resolver/ // TODO: What about a resolver factory? parser.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver()); parser.parse(new ByteArrayInputStream(memBuffer)); in = new ByteArrayInputStream(memBuffer); //org.w3c.dom.Document document = parser.parse(new ByteArrayInputStream(memBuffer)); } catch (org.xml.sax.SAXException e) { log.warn("Data is not well-formed: "+e.getMessage()); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"data-not-well-formed\">"); sb.append("<message>Data is not well-formed: "+e.getMessage()+"</message>"); sb.append("</exception>"); response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } catch (Exception e) { log.error(e.getMessage(), e); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"neutron\">"); //sb.append("<message>" + e.getStackTrace() + "</message>"); //sb.append("<message>" + e.getMessage() + "</message>"); sb.append("<message>" + e + "</message>"); sb.append("</exception>"); response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } log.info("Data seems to be well-formed :-)"); } else { log.info("No well-formedness check required for content type: " + contentType); } // IMPORTANT TODO: Use ModifiableV2.write(InputStream in) such that resource can modify data during saving resp. check if getOutputStream is equals null and then use write .... OutputStream out = null; Resource res = getResource(request, response); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath())); write(in, out, request, response); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { try { out = ((ModifiableV2) res).getOutputStream(); if (out != null) { write(in, out, request, response); } else { ((ModifiableV2) res).write(in); } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } else { String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!"; log.warn(message); StringBuffer sb = new StringBuffer(); // TODO: Differentiate between Neutron based and other clients ... sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"neutron\">"); sb.append("<message>" + message + "</message>"); sb.append("</exception>"); response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); } if (doCheckin) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) { VersionableV2 versionable = (VersionableV2)resource; try { versionable.checkin("updated"); } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException("Could not check in resource: " + resource.getPath() + " " + e.getMessage(), e); } } } } /** * Check authorization and if not authorized then authenticate. Return null if authorization granted, otherwise return 401 and appropriate response such that client can provide credentials for authentication */ private HttpServletResponse doAccessControl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get usecase Usecase usecase = getUsecase(request); // Get identity, realm, path Identity identity; Realm realm; String path; try { identity = getIdentity(request); realm = map.getRealm(request.getServletPath()); path = map.getPath(realm, request.getServletPath()); } catch (Exception e) { log.error(e, e); throw new ServletException(e.getMessage()); } // Check Authorization boolean authorized = false; try { if (log.isDebugEnabled()) log.debug("Check authorization: realm: " + realm + ", path: " + path + ", identity: " + identity + ", Usecase: " + usecase.getName()); authorized = realm.getPolicyManager().authorize(path, identity, usecase); if (log.isDebugEnabled()) log.debug("Check authorization result: " + authorized); } catch (Exception e) { log.error(e, e); throw new ServletException(e.getMessage(), e); } if(!authorized) { // TODO: Implement HTTP BASIC/DIGEST response (see above) log.warn("Access denied: " + getRequestURLQS(request, null, false)); if(!request.isSecure()) { if(sslPort != null) { log.info("Redirect to SSL ..."); try { URL url = new URL(getRequestURLQS(request, null, false).toString()); url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); if (realm.isProxySet()) { if (realm.getProxySSLPort() >= 0) { log.debug("Use configured port: " + realm.getProxySSLPort()); url = new URL(url.getProtocol(), url.getHost(), new Integer(realm.getProxySSLPort()).intValue(), url.getFile()); } else { log.debug("Use default port: " + url.getDefaultPort()); // NOTE: getDefaultPort depends on the Protocol (e.g. https is 443) url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } } log.info("Redirect to SSL: " + url); response.setHeader("Location", url.toString()); // TODO: Yulup has a bug re TEMPORARY_REDIRECT //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); return response; } catch (Exception e) { log.error(e); } } else { log.warn("SSL does not seem to be configured!"); } } if(doAuthenticate(request, response) != null) { log.warn("Return response of web authenticator."); /* NOTE: Such a response can have different reasons: - Either no credentials provided yet and web authenticator is generating a response to fetch credentials - Or authentication failed and web authenticator is resending response to fetch again credentials"); - Or authentication was successful and web authenticator sends a redirect */ return response; } else { try { log.warn("Authentication was successful for user: " + getIdentity(request).getUsername()); } catch (Exception e) { log.error(e, e); } URL url = new URL(getRequestURLQS(request, null, false).toString()); if (sslPort != null) { url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile()); } log.warn("Redirect to original request: " + url); //response.sendRedirect(url.toString()); // 302 // TODO: Yulup has a bug re TEMPORARY_REDIRECT (or is the problem that the load balancer is rewritting 302 reponses?!) response.setHeader("Location", url.toString()); response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY); // 301 //response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT); // 302 return response; } } else { log.info("Access granted: " + getRequestURLQS(request, null, false)); return null; } } /** * Patch request with proxy settings re realm configuration */ private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) { try { Realm realm = map.getRealm(request.getServletPath()); // TODO: Handle this exception more gracefully! if (realm == null) log.error("No realm found for path " +request.getServletPath()); String proxyHostName = realm.getProxyHostName(); int proxyPort = realm.getProxyPort(); String proxyPrefix = realm.getProxyPrefix(); URL url = null; url = new URL(request.getRequestURL().toString()); //if(proxyHostName != null || proxyPort >= null || proxyPrefix != null) { if(realm.isProxySet()) { if (proxyHostName != null) { url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile()); } if (proxyPort >= 0) { url = new URL(url.getProtocol(), url.getHost(), proxyPort, url.getFile()); } else { url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } if (proxyPrefix != null) { url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length())); } //log.debug("Proxy enabled for this realm resp. request: " + realm + ", " + url); } else { //log.debug("No proxy set for this realm resp. request: " + realm + ", " + url); } String urlQS = url.toString(); if (request.getQueryString() != null) { urlQS = urlQS + "?" + request.getQueryString(); if (addQS != null) urlQS = urlQS + "&" + addQS; } else { if (addQS != null) urlQS = urlQS + "?" + addQS; } if (xml) urlQS = urlQS.replaceAll("&", "&amp;"); if(log.isDebugEnabled()) log.debug("Request: " + urlQS); return urlQS; } catch (Exception e) { log.error(e); return null; } } /** * Also see https://svn.apache.org/repos/asf/tomcat/container/branches/tc5.0.x/catalina/src/share/org/apache/catalina/servlets/WebdavServlet.java * Also maybe interesting http://sourceforge.net/projects/openharmonise */ public void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Resource resource = getResource(request, response); //Node node = resource.getRealm().getSitetree().getNode(resource.getPath()); Node node = sitetree.getNode(resource.getRealm(),resource.getPath()); String depth = request.getHeader("Depth"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<multistatus xmlns=\"DAV:\">"); if (depth.equals("0")) { if (node.isCollection()) { sb.append(" <response>"); sb.append(" <href>"+request.getRequestURI()+"</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype><collection/></resourcetype>"); sb.append(" <getcontenttype>httpd/unix-directory</getcontenttype>"); sb.append(" </prop>"); sb.append(" <status>HTTP/1.1 200 OK</status>"); sb.append(" </propstat>"); sb.append(" </response>"); } else if (node.isResource()) { sb.append(" <response>"); sb.append(" <href>"+request.getRequestURI()+"</href>"); sb.append(" <propstat>"); sb.append(" <prop>"); sb.append(" <resourcetype/>"); // TODO: Set mime type of node! sb.append(" <getcontenttype>application/octet-stream</getcontenttype>"); // TODO: Set content length and last modified! sb.append(" <getcontentlength>0</getcontentlength>"); sb.append(" <getlastmodified>1969.02.16</getlastmodified>"); // See http://www.webdav.org/specs/rfc2518.html#PROPERTY_source, http://wiki.zope.org/HiperDom/RoundtripEditingDiscussion sb.append(" <source>\n"); sb.append(" <link>\n"); sb.append(" <src>" + request.getRequestURI() + "</src>\n"); sb.append(" <dst>" + request.getRequestURI() + "?yanel.resource.modifiable.source</dst>\n"); sb.append(" </link>\n"); sb.append(" </source>\n"); sb.append(" </prop>"); sb.append(" <status>HTTP/1.1 200 OK</status>"); sb.append(" </propstat>"); sb.append(" </response>"); } else { log.error("Neither collection nor resource!"); } } else if (depth.equals("1")) { // TODO: Shouldn't one check with isCollection() first?! Node[] children = node.getChildren(); if (children != null) { for (int i = 0; i < children.length; i++) { if (children[i].isCollection()) { sb.append(" <response>\n"); sb.append(" <href>" + request.getRequestURI() + "/" + children[i].getName() + "/</href>\n"); sb.append(" <propstat>\n"); sb.append(" <prop>\n"); sb.append(" <displayname>" + children[i].getName() + "</displayname>\n"); sb.append(" <resourcetype><collection/></resourcetype>\n"); sb.append(" <getcontenttype>httpd/unix-directory</getcontenttype>\n"); sb.append(" </prop>\n"); sb.append(" <status>HTTP/1.1 200 OK</status>\n"); sb.append(" </propstat>\n"); sb.append(" </response>\n"); } else if(children[i].isResource()) { sb.append(" <response>\n"); sb.append(" <href>" + request.getRequestURI() + "/" + children[i].getName() + "?yanel.webdav=propfind1</href>\n"); sb.append(" <propstat>\n"); sb.append(" <prop>\n"); sb.append(" <displayname>" + children[i].getName() + "</displayname>\n"); sb.append(" <resourcetype/>\n"); // TODO: Set mime type of node! sb.append(" <getcontenttype>application/octet-stream</getcontenttype>\n"); // TODO: Set content length and last modified! sb.append(" <getcontentlength>0</getcontentlength>"); sb.append(" <getlastmodified>1969.02.16</getlastmodified>"); // See http://www.webdav.org/specs/rfc2518.html#PROPERTY_source, http://wiki.zope.org/HiperDom/RoundtripEditingDiscussion sb.append(" <source>\n"); sb.append(" <link>\n"); sb.append(" <src>" + request.getRequestURI() + "/" + children[i].getName() + "</src>\n"); sb.append(" <dst>" + request.getRequestURI() + "/" + children[i].getName() + "?yanel.resource.modifiable.source</dst>\n"); sb.append(" </link>\n"); sb.append(" </source>\n"); sb.append(" </prop>\n"); sb.append(" <status>HTTP/1.1 200 OK</status>\n"); sb.append(" </propstat>\n"); sb.append(" </response>\n"); } else { log.error("Neither collection nor resource: " + children[i].getPath()); } } } else { log.warn("No children!"); } } else if (depth.equals("infinity")) { log.warn("TODO: List children and their children and their children ..."); } else { log.error("No such depth: " + depth); } sb.append("</multistatus>"); //response.setStatus(javax.servlet.http.HttpServletResponse.SC_MULTI_STATUS); response.setStatus(207, "Multi-Status"); PrintWriter w = response.getWriter(); w.print(sb); } /** * */ public void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("DAV", "1"); // TODO: Is there anything else to do?! } /** * Authentication * @return null when authentication successful or has already been authenticated, otherwise return response generated by web authenticator */ public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // TODO/TBD: In the case of HTTP-BASIC/DIGEST one needs to check authentication with every request // TODO: enhance API with flag, e.g. session-based="true/false" // WARNING: One needs to separate doAuthenticate from the login screen generation! //if (getIdentity(request) != null) return null; WebAuthenticator wa = map.getRealm(request.getServletPath()).getWebAuthenticator(); return wa.doAuthenticate(request, response, map, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort); } catch (Exception e) { log.error(e.getMessage(), e); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return response; } } /** * Escapes all reserved xml characters (&amp; &lt; &gt; &apos; &quot;) in a string. * @param s input string * @return string with escaped characters */ public static String encodeXML(String s) { s = s.replaceAll("&", "&amp;"); s = s.replaceAll("<", "&lt;"); s = s.replaceAll(">", "&gt;"); s = s.replaceAll("'", "&apos;"); s = s.replaceAll("\"", "&quot;"); return s; } /** * Do logout * @return null for a regular logout and a Neutron response if auth scheme is Neutron */ public HttpServletResponse doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if (isToolbarEnabled(request)) { // TODO: Check if WORLD has access to the toolbar //if (getRealm().getPolicyManager().authorize(path, new Identity(), new Usecase(TOOLBAR_USECASE))) { disableToolbar(request); //} } HttpSession session = request.getSession(true); // TODO: should we logout only from the current realm, or from all realms? // -> logout only from the current realm Realm realm = map.getRealm(request.getServletPath()); IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY); if (identityMap != null && identityMap.containsKey(realm.getID())) { log.info("Logout from realm: " + realm.getID()); identityMap.remove(realm.getID()); } String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { // TODO: send some XML content, e.g. <logout-successful/> response.setContentType("text/plain; charset=" + DEFAULT_ENCODING); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print("Neutron Logout Successful!"); return response; } if (log.isDebugEnabled()) log.debug("Regular Logout Successful!"); return null; } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } /** * Do create a new resource */ public HttpServletResponse doCreate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.error("Not implemented yet!"); return null; } /** * Patches the mimetype of the Content-Type response field because * Microsoft Internet Explorer does not understand application/xhtml+xml * See http://en.wikipedia.org/wiki/Criticisms_of_Internet_Explorer#XHTML */ static public String patchMimeType(String mimeType, HttpServletRequest request) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); if (mimeType != null && mimeType.equals("application/xhtml+xml") && httpAcceptMediaTypes != null && httpAcceptMediaTypes.indexOf("application/xhtml+xml") < 0) { log.info("Patch contentType with text/html because client (" + request.getHeader("User-Agent") + ") does not seem to understand application/xhtml+xml"); return "text/html"; } return mimeType; } /** * Intercept InputStream and log content ... */ public InputStream intercept(InputStream in) throws IOException { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) // http://www-128.ibm.com/developerworks/java/library/j-io1/ byte[] memBuffer = baos.toByteArray(); log.error("DEBUG: InputStream: " + baos); return new java.io.ByteArrayInputStream(memBuffer); } /** * Generate a "Yanel" response (page information, 404, internal server error, ...) */ private void setYanelOutput(HttpServletRequest request, HttpServletResponse response, Document doc) throws ServletException { String path = getResource(request, response).getPath(); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(path); try { String yanelFormat = request.getParameter("yanel.format"); if(yanelFormat != null && yanelFormat.equals("xml")) { response.setContentType("application/xml; charset=" + DEFAULT_ENCODING); OutputStream out = response.getOutputStream(); javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); out.close(); } else { String mimeType = patchMimeType("application/xhtml+xml", request); response.setContentType(mimeType + "; charset=" + DEFAULT_ENCODING); // create identity transformer which serves as a dom-to-sax transformer TransformerIdentityImpl transformer = new TransformerIdentityImpl(); // create xslt transformer: SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler xsltTransformer = saxTransformerFactory.newTransformerHandler(new StreamSource(xsltInfoAndException)); xsltTransformer.getTransformer().setParameter("yanel.back2realm", backToRealm); xsltTransformer.getTransformer().setParameter("yanel.reservedPrefix", reservedPrefix); // create i18n transformer: I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getLanguage(request),yanel.getMap().getRealm(request.getServletPath()).getDefaultLanguage()); CatalogResolver catalogResolver = new CatalogResolver(); i18nTransformer.setEntityResolver(new CatalogResolver()); // create serializer: Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); // chain everything together (create a pipeline): xsltTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(response.getOutputStream()); // execute pipeline: transformer.transform(new DOMSource(doc), new SAXResult(xsltTransformer)); } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } } /** * Get language with the following priorization: 1) yanel.meta.language query string parameter, 2) Accept-Language header, 3) Default en */ private String getLanguage(HttpServletRequest request) throws Exception { // TODO: Shouldn't this be replaced by Resource.getRequestedLanguage() or Resource.getContentLanguage() ?! String language = request.getParameter("yanel.meta.language"); if (language == null) { language = request.getHeader("Accept-Language"); if (language != null) { int commaIndex = language.indexOf(","); if (commaIndex > 0) { language = language.substring(0, commaIndex); } int dashIndex = language.indexOf("-"); if (dashIndex > 0) { language = language.substring(0, dashIndex); } } } if(language != null && language.length() > 0) return language; return yanel.getMap().getRealm(request.getServletPath()).getDefaultLanguage(); } /** * Write to output stream of modifiable resource */ private void write(InputStream in, OutputStream out, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (out != null) { log.debug("Content-Type: " + request.getContentType()); // TODO: Compare mime-type from response with mime-type of resource //if (contentType.equals("text/xml")) { ... } byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); out.close(); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Data has been saved ...</p>"); sb.append("</body>"); sb.append("</html>"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("application/xhtml+xml; charset=" + DEFAULT_ENCODING); PrintWriter w = response.getWriter(); w.print(sb); log.info("Data has been saved ..."); return; } else { log.error("OutputStream is null!"); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Exception: OutputStream is null!</p>"); sb.append("</body>"); sb.append("</html>"); PrintWriter w = response.getWriter(); w.print(sb); response.setContentType("application/xhtml+xml; charset=" + DEFAULT_ENCODING); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } /** * Get toolbar menus */ private String getToolbarMenus(Resource resource, HttpServletRequest request) throws ServletException, IOException, Exception { org.wyona.yanel.servlet.menu.Menu menu = null; String menuRealmClass = resource.getRealm().getMenuClass(); if (menuRealmClass != null) { menu = (org.wyona.yanel.servlet.menu.Menu) Class.forName(menuRealmClass).newInstance(); // TODO: Check resource configuration ... //} else if (RESOURCE) { } else { menu = new org.wyona.yanel.servlet.menu.impl.DefaultMenu(); } return menu.getAllMenus(resource, request, map, reservedPrefix); } /** * Gets the part of the toolbar which has to be inserted into the html header. * @param resource * @param request * @return * @throws Exception */ private String getToolbarHeader(Resource resource, HttpServletRequest request) throws Exception { String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuffer sb= new StringBuffer(); sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbar.css\" rel=\"stylesheet\"/>"); sb.append(System.getProperty("line.separator")); sb.append("<style type=\"text/css\" media=\"screen\">"); sb.append(System.getProperty("line.separator")); sb.append("#yaneltoolbar_menu li li.haschild{ background: lightgrey url(" + backToRealm + reservedPrefix + "/yanel-img/submenu.gif) no-repeat 98% 50%;}"); sb.append(System.getProperty("line.separator")); sb.append("#yaneltoolbar_menu li li.haschild:hover{ background: lightsteelblue url(" + backToRealm + reservedPrefix + "/yanel-img/submenu.gif) no-repeat 98% 50%;}"); sb.append("</style>"); sb.append(System.getProperty("line.separator")); // If browser is Mozilla (gecko engine rv:1.7) if (request.getHeader("User-Agent").indexOf("rv:1.7") >= 0) { sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarMozilla.css\" rel=\"stylesheet\"/>"); sb.append(System.getProperty("line.separator")); } // If browser is IE if (request.getHeader("User-Agent").indexOf("compatible; MSIE") >= 0 && request.getHeader("User-Agent").indexOf("Windows") >= 0 ) { sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE.css\" rel=\"stylesheet\"/>"); sb.append(System.getProperty("line.separator")); sb.append("<style type=\"text/css\" media=\"screen\">"); sb.append(" body{behavior:url(" + backToRealm + reservedPrefix + "/csshover.htc);font-size:100%;}"); sb.append("</style>"); } // If browser is IE6 if (request.getHeader("User-Agent").indexOf("compatible; MSIE 6") >= 0 && request.getHeader("User-Agent").indexOf("Windows") >= 0 ) { sb.append("<link type=\"text/css\" href=\"" + backToRealm + reservedPrefix + "/toolbarIE6.css\" rel=\"stylesheet\"/>"); sb.append(System.getProperty("line.separator")); } return sb.toString(); } /** * Gets the part of the toolbar which has to be inserted into the html body * right after the opening body tag. * @param resource * @param request * @return * @throws Exception */ private String getToolbarBodyStart(Resource resource, HttpServletRequest request) throws Exception { String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath()); StringBuffer buf = new StringBuffer(); buf.append("<div id=\"yaneltoolbar_headerwrap\">"); buf.append("<div id=\"yaneltoolbar_menu\">"); buf.append(getToolbarMenus(resource, request)); buf.append("</div>"); buf.append("<span id=\"yaneltoolbar_info\">"); //buf.append("Version: " + yanel.getVersion() + "-r" + yanel.getRevision() + "&#160;&#160;"); buf.append("Realm: <b>" + resource.getRealm().getName() + "</b>&#160;&#160;"); Identity identity = getIdentity(request); if (identity != null && !identity.isWorld()) { buf.append("User: <b>" + identity.getUsername() + "</b>"); } else { buf.append("User: <b>Not signed in!</b>"); } buf.append("</span>"); buf.append("<span id=\"yaneltoolbar_logo\">"); buf.append("<img src=\"" + backToRealm + reservedPrefix + "/yanel_toolbar_logo.png\"/>"); buf.append("</span>"); buf.append("</div>"); buf.append("<div id=\"yaneltoolbar_middlewrap\">"); return buf.toString(); } /** * Gets the part of the toolbar which has to be inserted into the html body * right before the closing body tag. * @param resource * @param request * @return * @throws Exception */ private String getToolbarBodyEnd(Resource resource, HttpServletRequest request) throws Exception { return "</div>"; } /** * Merges the toolbar and the page content. This will parse the html stream and add * the toolbar. * @param request * @param response * @param resource * @param view * @throws Exception */ private void mergeToolbarWithContent(HttpServletRequest request, HttpServletResponse response, Resource resource, View view) throws Exception { String encoding = view.getEncoding(); if (encoding == null) { encoding = "UTF-8"; } InputStreamReader reader = new InputStreamReader(view.getInputStream(), encoding); OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), encoding); int c; int state = OUTSIDE_TAG; StringBuffer tagBuf = null; int headcount = 0; int bodycount = 0; while ((c = reader.read()) != -1) { switch (state) { case OUTSIDE_TAG: if (c == '<') { tagBuf = new StringBuffer("<"); state = INSIDE_TAG; } else { writer.write(c); } break; case INSIDE_TAG: //writer.write(c); if (c == '>') { state = OUTSIDE_TAG; tagBuf.append((char)c); String tag = tagBuf.toString(); if (tag.startsWith("<head")) { if (headcount == 0) { writer.write(tag, 0, tag.length()); String toolbarString = getToolbarHeader(resource, request); writer.write(toolbarString, 0, toolbarString.length()); } else { writer.write(tag, 0, tag.length()); } headcount++; } else if (tag.startsWith("<body")) { if (bodycount == 0) { writer.write(tag, 0, tag.length()); String toolbarString = getToolbarBodyStart(resource, request); writer.write(toolbarString, 0, toolbarString.length()); } else { writer.write(tag, 0, tag.length()); } bodycount++; } else if (tag.equals("</body>")) { bodycount--; if (bodycount == 0) { String toolbarString = getToolbarBodyEnd(resource, request); writer.write(toolbarString, 0, toolbarString.length()); writer.write(tag, 0, tag.length()); } else { writer.write(tag, 0, tag.length()); } } else { writer.write(tag, 0, tag.length()); } } else { tagBuf.append((char)c); } break; } } writer.flush(); writer.close(); } /** * Gets the identity from the session associated with the given request. * @param request * @return identity or null if there is no identity in the session for the current realm or if there is no session at all */ private Identity getIdentity(HttpServletRequest request) throws Exception { Realm realm = map.getRealm(request.getServletPath()); HttpSession session = request.getSession(false); if (session != null) { IdentityMap identityMap = (IdentityMap)session.getAttribute(IDENTITY_MAP_KEY); if (identityMap != null) { Identity identity = (Identity)identityMap.get(realm.getID()); if (identity != null) { return identity; } } } // HTTP BASIC Authentication (For clients such as for instance Sunbird, OpenOffice or cadaver) // IMPORT NOTE: BASIC Authentication needs to be checked on every request, because clients often do not support session handling String authorizationHeader = request.getHeader("Authorization"); if (log.isDebugEnabled()) log.debug("Checking for Authorization Header: " + authorizationHeader); if (authorizationHeader != null) { if (authorizationHeader.toUpperCase().startsWith("BASIC")) { log.warn("Using BASIC authorization ..."); // Get encoded user and password, comes after "BASIC " String userpassEncoded = authorizationHeader.substring(6); // Decode it, using any base 64 decoder sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); log.debug("Username and Password Decoded: " + userpassDecoded); String[] up = userpassDecoded.split(":"); String username = up[0]; String password = up[1]; log.debug("username: " + username + ", password: " + password); try { User user = realm.getIdentityManager().getUserManager().getUser(username); if (user != null && user.authenticate(password)) { return new Identity(user); } else { log.warn("HTTP BASIC Authentication failed for " + username + "!"); /* response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\""); response.sendError(response.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.print("BASIC Authentication Failed!"); return response; */ } } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } } else if (authorizationHeader.toUpperCase().startsWith("DIGEST")) { log.error("DIGEST is not implemented"); /* authorized = false; response.sendError(response.SC_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "DIGEST realm=\"" + realm.getName() + "\""); PrintWriter writer = response.getWriter(); writer.print("DIGEST is not implemented!"); */ } else { log.warn("No such authorization type implemented: " + authorizationHeader); } } if(log.isDebugEnabled()) log.debug("No identity yet (Neither session nor header based! Identity is set to WORLD!)"); // TBD: Should add world identity to the session? return new Identity(); } /** * Create a DOM Document */ static public Document getDocument(String namespace, String localname) throws Exception { javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation(); org.w3c.dom.DocumentType doctype = null; Document doc = impl.createDocument(namespace, localname, doctype); if (namespace != null) { doc.getDocumentElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", namespace); } return doc; } /** * Get global data located below reserved prefix */ public void getGlobalData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Resource resource = getResource(request, response); String path = resource.getPath(); String viewId = request.getParameter(VIEW_ID_PARAM_NAME); if (path.startsWith("/" + reservedPrefix + "/users/")) { String userName = path.substring(reservedPrefix.length() + 8); userName = userName.split("[.]")[0]; try { java.util.Map properties = new HashMap(); properties.put("user", userName); ResourceConfiguration rc = new ResourceConfiguration("yanel-user", "http://www.wyona.org/yanel/resource/1.0", properties); Realm realm = yanel.getMap().getRealm(request.getServletPath()); Resource yanelUserResource = yanel.getResourceManager().getResource(getEnvironment(request, response), realm, path, rc); View view = ((ViewableV2) yanelUserResource).getView(viewId); if (view != null) { if (generateResponse(view, yanelUserResource, request, response, getDocument(NAMESPACE, "yanel"), -1, -1) != null) return; } } catch (Exception e) { throw new ServletException(e); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); return; } else if (path.indexOf("user-mgmt/list-users.html") >= 0) { log.warn("TODO: Implementation not finished yet!"); } else if (path.indexOf("about.html") >= 0) { response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); StringBuffer sb = new StringBuffer("<html>"); sb.append("<head><title>About Yanel</title></head>"); sb.append("<body><h1>About Yanel</h1><p>Version " + yanel.getVersion() + "-r" + yanel.getRevision() + "</p><p>Copyright &#169; 2007 Wyona. All rights reserved.</p></body>"); sb.append("</html>"); PrintWriter w = response.getWriter(); w.print(sb); return; } else if (path.indexOf("data-repository-sitetree.html") >= 0) { try { Realm realm = yanel.getMap().getRealm(request.getServletPath()); File drsResConfigFile = getGlobalResourceConfiguration("data-repo-sitetree_yanel-rc.xml", realm); ResourceConfiguration rc = new ResourceConfiguration(new java.io.FileInputStream(drsResConfigFile)); Resource sitetreeResource = yanel.getResourceManager().getResource(getEnvironment(request, response), realm, path, rc); View view = ((ViewableV2) sitetreeResource).getView(viewId); if (view != null) { if (generateResponse(view, sitetreeResource, request, response, getDocument(NAMESPACE, "yanel"), -1, -1) != null) return; } } catch (Exception e) { throw new ServletException(e); } } else if (path.indexOf("resource-types") >=0 ) { String[] pathPart1 = path.split("/resource-types/"); String[] pathPart2 = pathPart1[1].split("::"); String[] pathPart3 = pathPart2[1].split("/"); String name = pathPart3[0]; String namespace = pathPart2[0].replaceAll("http:/", "http://"); try { java.util.Map properties = new HashMap(); Realm realm = yanel.getMap().getRealm(request.getServletPath()); ResourceConfiguration rc = new ResourceConfiguration(name, namespace, properties); Resource resourceOfPrefix = yanel.getResourceManager().getResource(getEnvironment(request, response), realm, path, rc); String htdocsPath; if (pathPart2[1].indexOf("/" + reservedPrefix + "/") >= 0) { htdocsPath = "rtyanelhtdocs:" + path.split("::" + name)[1].split("/" + reservedPrefix)[1].replace('/', File.separatorChar); } else { htdocsPath = "rthtdocs:" + path.split("::" + name)[1].replace('/', File.separatorChar); } SourceResolver resolver = new SourceResolver(resourceOfPrefix); Source source = resolver.resolve(htdocsPath, null); InputStream htodoc = ((StreamSource) source).getInputStream(); if (htodoc != null) { log.debug("Resource-Type specific data: " + htdocsPath); // TODO: Set HTTP header (mime-type, size, etc.) String mimeType = guessMimeType(FilenameUtils.getExtension(FilenameUtils.getName(htdocsPath))); response.setHeader("Content-Type", mimeType); byte buffer[] = new byte[8192]; int bytesRead; InputStream in = htodoc; OutputStream out = response.getOutputStream(); while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } // allow client-side caching: if (cacheExpires != 0) { setExpiresHeader(response, cacheExpires); } return; } else { log.error("No such file or directory: " + htdocsPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); return; } } catch (Exception e) { throw new ServletException(e); } } else { File globalFile = org.wyona.commons.io.FileUtil.file(servletContextRealPath, "htdocs" + File.separator + path.substring(reservedPrefix.length() + 2)); if (globalFile.exists()) { log.debug("Global data: " + globalFile); // TODO: Set HTTP header (mime-type, size, etc.) String mimeType = guessMimeType(FilenameUtils.getExtension(globalFile.getName())); response.setHeader("Content-Type", mimeType); byte buffer[] = new byte[8192]; int bytesRead; InputStream in = new java.io.FileInputStream(globalFile); OutputStream out = response.getOutputStream(); while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } // allow client-side caching: if (cacheExpires != 0) { setExpiresHeader(response, cacheExpires); } return; } else { log.error("No such file or directory: " + globalFile); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); return; } } } private void setExpiresHeader(HttpServletResponse response, int hours) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR_OF_DAY, hours); String expires = DateUtil.formatRFC822GMT(calendar.getTime()); response.setHeader("Expires", expires); } /** * Generate response from a resource view */ private HttpServletResponse generateResponse(View view, Resource res, HttpServletRequest request, HttpServletResponse response, Document doc, long size, long lastModified) throws ServletException, IOException { // Check if the view contains the response, otherwise assume that the resource wrote the response, and just return. // TODO: There seem like no header fields are being set (e.g. Content-Length, ...). Please see below ... // Check if viewable resource has already created a response if (!view.isResponse()) return response; // Set encoding if (view.getEncoding() != null) { response.setContentType(patchMimeType(view.getMimeType(), request) + "; charset=" + view.getEncoding()); } else if (res.getConfiguration() != null && res.getConfiguration().getEncoding() != null) { response.setContentType(patchMimeType(view.getMimeType(), request) + "; charset=" + res.getConfiguration().getEncoding()); } else { // try to guess if we have to set the default encoding String mimeType = view.getMimeType(); if (mimeType != null && mimeType.startsWith("text") || mimeType.equals("application/xml") || mimeType.equals("application/xhtml+xml") || mimeType.equals("application/atom+xml") || mimeType.equals("application/x-javascript")) { response.setContentType(patchMimeType(mimeType, request) + "; charset=" + DEFAULT_ENCODING); } else { // probably binary mime-type, don't set encoding response.setContentType(patchMimeType(mimeType, request)); } } // Set HTTP headers: HashMap headers = view.getHttpHeaders(); Iterator iter = headers.keySet().iterator(); while (iter.hasNext()) { String name = (String)iter.next(); String value = (String)headers.get(name); if (log.isDebugEnabled()) { log.debug("set http header: " + name + ": " + value); } response.setHeader(name, value); } // Possibly embed toolbar: // TODO: Check if user is authorized to actually see toolbar (Current flaw: Enabled Toolbar, Login, Toolbar is enabled, Logout, Toolbar is still visible!) if (isToolbarEnabled(request)) { String mimeType = view.getMimeType(); if (mimeType != null && mimeType.indexOf("html") > 0) { // TODO: What about other query strings or frames or TinyMCE? if (request.getParameter("yanel.resource.usecase") == null) { if (toolbarMasterSwitch.equals("on")) { OutputStream os = response.getOutputStream(); try { mergeToolbarWithContent(request, response, res, view); } catch (Exception e) { log.error(e, e); String message = "Error merging toolbar into content: " + e.toString(); Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return response; } return response; } else { log.info("Toolbar has been disabled. Please check web.xml!"); } } else { log.error("DEBUG: Exception to the rule: " + request.getParameter("yanel.resource.usecase")); } } else { log.debug("No HTML related mime type: " + mimeType); } } else { log.debug("Toolbar is turned off."); } // Set actual content byte buffer[] = new byte[8192]; int bytesRead; InputStream is = view.getInputStream(); if (is != null) { bytesRead = is.read(buffer); // Check if InputStream is empty if (bytesRead == -1) { String message = "InputStream of view does not seem to contain any data!"; Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return response; } // TODO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag String ifModifiedSince = request.getHeader("If-Modified-Since"); if (ifModifiedSince != null) { if (log.isDebugEnabled()) log.debug("TODO: Implement 304 ..."); } if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified); if(size > 0) { if (log.isDebugEnabled()) log.debug("Size of " + request.getRequestURI() + ": " + size); response.setContentLength((int) size); } else { if (log.isDebugEnabled()) log.debug("No size for " + request.getRequestURI() + ": " + size); } java.io.OutputStream os = response.getOutputStream(); os.write(buffer, 0, bytesRead); while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } return response; } else { String message = "InputStream of view is null!"; Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return response; } } /** * */ public void destroy() { super.destroy(); yanel.destroy(); log.warn("Yanel webapp has been shut down."); } /** * */ private Usecase getUsecase(HttpServletRequest request) { Usecase usecase = null; // TODO: Replace hardcoded roles by mapping between roles amd query strings ... String value = request.getParameter("yanel.resource.usecase"); String yanelUsecaseValue = request.getParameter("yanel.usecase"); String workflowTransitionValue = request.getParameter("yanel.resource.workflow.transition"); String contentType = request.getContentType(); String method = request.getMethod(); if (value != null && value.equals("save")) { log.debug("Save data ..."); usecase = new Usecase("write"); } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); usecase = new Usecase("write"); } else if (yanelUsecaseValue != null && yanelUsecaseValue.equals("create")) { log.debug("Create new resource ..."); usecase = new Usecase("resource.create"); } else if (value != null && value.equals("introspection")) { if(log.isDebugEnabled()) log.debug("Dynamically generated introspection ..."); usecase = new Usecase("introspection"); } else if (value != null && value.equals("checkout")) { log.debug("Checkout data ..."); usecase = new Usecase("open"); } else if (contentType != null && contentType.indexOf("application/atom+xml") >= 0 && (method.equals(METHOD_PUT) || method.equals(METHOD_POST))) { // TODO: Is posting atom entries different from a general post (see below)?! log.error("DEBUG: Write/Checkin Atom entry ..."); usecase = new Usecase("write"); // TODO: METHOD_POST is not generally protected, but save, checkin, application/atom+xml are being protected. See doPost(.... } else if (method.equals(METHOD_PUT)) { log.error("DEBUG: Upload data ..."); usecase = new Usecase("write"); } else if (method.equals(METHOD_DELETE)) { log.error("DEBUG: Delete resource (HTTP method delete)"); usecase = new Usecase("delete"); } else if (value != null && value.equals("delete")) { log.info("Delete resource (yanel resource usecase delete)"); usecase = new Usecase("delete"); } else if (workflowTransitionValue != null) { // TODO: How shall we protect workflow transitions?! log.error("DEBUG: Workflow transition ..."); usecase = new Usecase("view"); } else { usecase = new Usecase("view"); } value = request.getParameter("yanel.toolbar"); if (value != null && value.equals("on")) { log.debug("Turn on toolbar ..."); usecase = new Usecase(TOOLBAR_USECASE); } value = request.getParameter("yanel.policy"); if (value != null) { if (value.equals("create")) { usecase = new Usecase("policy.create"); } else if (value.equals("read")) { usecase = new Usecase("policy.read"); } else if (value.equals("update")) { usecase = new Usecase("policy.update"); } else if (value.equals("delete")) { usecase = new Usecase("policy.delete"); } else { log.warn("No such policy usecase: " + value); } } return usecase; } /** * Handle access policy requests (CRUD, whereas delete is not implemented yet!) */ private void doAccessPolicyRequest(HttpServletRequest request, HttpServletResponse response, String usecase) throws ServletException, IOException { try { String viewId = request.getParameter(VIEW_ID_PARAM_NAME); Realm realm = map.getRealm(request.getServletPath()); String path = map.getPath(realm, request.getServletPath()); File pmrcGlobalFile = getGlobalResourceConfiguration("policy-manager_yanel-rc.xml", realm); Resource policyManagerResource = yanel.getResourceManager().getResource(getEnvironment(request, response), realm, path, new ResourceConfiguration(new java.io.FileInputStream(pmrcGlobalFile))); View view = ((ViewableV2) policyManagerResource).getView(viewId); if (view != null) { if (generateResponse(view, policyManagerResource, request, response, getDocument(NAMESPACE, "yanel"), -1, -1) != null) return; } log.error("Something went terribly wrong!"); response.getWriter().print("Something went terribly wrong!"); return; } catch(Exception e) { log.error(e, e); throw new ServletException(e.getMessage()); } } /** * */ private void enableToolbar(HttpServletRequest request) { request.getSession(true).setAttribute(TOOLBAR_KEY, "on"); } /** * */ private void disableToolbar(HttpServletRequest request) { request.getSession(true).setAttribute(TOOLBAR_KEY, "off"); } /** * */ private boolean isToolbarEnabled(HttpServletRequest request) { String toolbarStatus = (String) request.getSession(true).getAttribute(TOOLBAR_KEY); if (toolbarStatus != null && toolbarStatus.equals("on")) { String yanelToolbar = request.getParameter("yanel.toolbar"); if(yanelToolbar != null && request.getParameter("yanel.toolbar").equals("suppress")) { return false; } else { return true; } } return false; } /** * Handle delete usecase */ private void handleDeleteUsecase(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String confirmed = request.getParameter("confirmed"); if (confirmed != null) { String path = getResource(request, response).getPath(); log.warn("Really delete " + path); doDelete(request, response); return; } else { log.warn("Delete has not been confirmed by client yet!"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); StringBuffer sb = new StringBuffer("<html><body>Do you really want to delete this page? <a href=\"?yanel.resource.usecase=delete&confirmed\">YES</a>, <a href=\"\">no</a></body></html>"); PrintWriter w = response.getWriter(); w.print(sb); return; } } /** * */ private File getGlobalResourceConfiguration(String resConfigName, Realm realm) { // TODO: Introduce a repository for the Yanel webapp File realmDir = new File(realm.getConfigFile().getParent()); File globalResConfigFile = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + "global-resource-configs/" + resConfigName); if (!globalResConfigFile.isFile()) { // Fallback to global configuration globalResConfigFile = org.wyona.commons.io.FileUtil.file(servletContextRealPath, "global-resource-configs/" + resConfigName); } return globalResConfigFile; } /** * */ private String getStackTrace(Exception e) { java.io.StringWriter sw = new java.io.StringWriter(); e.printStackTrace(new java.io.PrintWriter(sw)); return sw.toString(); } /** * */ private void do404(HttpServletRequest request, HttpServletResponse response, Document doc, String exceptionMessage) throws ServletException { // TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ... String message = "No such node/resource exception: " + exceptionMessage; log.warn(message); /* Element exceptionElement = (Element) doc.getDocumentElement().appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "404"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); setYanelOutput(request, response, doc); return; */ // TODO: Finish the XML (as it used to be before)! response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); try { Realm realm = yanel.getMap().getRealm(request.getServletPath()); File pnfResConfigFile = getGlobalResourceConfiguration("404_yanel-rc.xml", realm); ResourceConfiguration rc = new ResourceConfiguration(new java.io.FileInputStream(pnfResConfigFile)); String path = getResource(request, response).getPath(); Resource pageNotFoundResource = yanel.getResourceManager().getResource(getEnvironment(request, response), realm, path, rc); String viewId = request.getParameter(VIEW_ID_PARAM_NAME); if (request.getParameter("yanel.format") != null) { // backwards compatible viewId = request.getParameter("yanel.format"); } View view = ((ViewableV2) pageNotFoundResource).getView(viewId); if (view != null) { if (generateResponse(view, pageNotFoundResource, request, response, getDocument(NAMESPACE, "yanel"), -1, -1) != null) return; } log.error("404 seems to be broken!"); return; } catch (Exception e) { log.error(e, e); return; } } }
true
true
private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { View view = null; org.w3c.dom.Document doc = null; try { doc = getDocument(NAMESPACE, "yanel"); } catch(Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } Element rootElement = doc.getDocumentElement(); rootElement.setAttribute("servlet-context-real-path", servletContextRealPath); Element requestElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "request")); requestElement.setAttributeNS(NAMESPACE, "uri", request.getRequestURI()); requestElement.setAttributeNS(NAMESPACE, "servlet-path", request.getServletPath()); HttpSession session = request.getSession(true); Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session")); sessionElement.setAttribute("id", session.getId()); Enumeration attrNames = session.getAttributeNames(); if (!attrNames.hasMoreElements()) { Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes")); } while (attrNames.hasMoreElements()) { String name = (String)attrNames.nextElement(); String value = session.getAttribute(name).toString(); Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute")); sessionAttributeElement.setAttribute("name", name); sessionAttributeElement.appendChild(doc.createTextNode(value)); } String usecase = request.getParameter("yanel.resource.usecase"); Resource res = null; long lastModified = -1; long size = -1; try { Environment environment = getEnvironment(request, response); res = getResource(request, response); if (res != null) { Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource")); ResourceConfiguration resConfig = res.getConfiguration(); if (resConfig != null) { Element resConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "config")); resConfigElement.setAttributeNS(NAMESPACE, "rti-name", resConfig.getName()); resConfigElement.setAttributeNS(NAMESPACE, "rti-namespace", resConfig.getNamespace()); } else { Element noResConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "no-config")); } Element realmElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "realm")); realmElement.setAttributeNS(NAMESPACE, "name", res.getRealm().getName()); realmElement.setAttributeNS(NAMESPACE, "rid", res.getRealm().getID()); realmElement.setAttributeNS(NAMESPACE, "prefix", res.getRealm().getMountPoint()); Element identityManagerElement = (Element) realmElement.appendChild(doc.createElementNS(NAMESPACE, "identity-manager")); Element userManagerElement = (Element) identityManagerElement.appendChild(doc.createElementNS(NAMESPACE, "user-manager")); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { if (log.isDebugEnabled()) log.debug("Resource is viewable V1"); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.setAttributeNS(NAMESPACE, "version", "1"); // TODO: The same as for ViewableV2 ... ViewDescriptor[] vd = ((ViewableV1) res).getViewDescriptors(); if (vd != null) { for (int i = 0; i < vd.length; i++) { Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor")); if (vd[i].getMimeType() != null) { descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType())); } descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId()); } } else { viewElement.appendChild(doc.createTextNode("No View Descriptors!")); } String viewId = request.getParameter(VIEW_ID_PARAM_NAME); try { view = ((ViewableV1) res).getView(request, viewId); } catch(org.wyona.yarep.core.NoSuchNodeException e) { do404(request, response, doc, e.getMessage()); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "500"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) { if (log.isDebugEnabled()) log.debug("Resource is viewable V2"); if (!((ViewableV2) res).exists()) { //log.warn("No such ViewableV2 resource: " + res.getPath()); //log.warn("TODO: It seems like many ViewableV2 resources are not implementing exists() properly!"); //do404(request, response, doc, res.getPath()); //return; } String viewId = request.getParameter(VIEW_ID_PARAM_NAME); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.setAttributeNS(NAMESPACE, "version", "2"); ViewDescriptor[] vd = ((ViewableV2) res).getViewDescriptors(); if (vd != null) { for (int i = 0; i < vd.length; i++) { Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor")); if (vd[i].getMimeType() != null) { descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType())); } descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId()); } } else { viewElement.appendChild(doc.createTextNode("No View Descriptors!")); } size = ((ViewableV2) res).getSize(); Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size")); sizeElement.appendChild(doc.createTextNode(String.valueOf(size))); try { String revisionName = request.getParameter("yanel.resource.revision"); if (revisionName != null && ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { view = ((VersionableV2) res).getView(viewId, revisionName); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1") && environment.getStateOfView().equals(StateOfView.LIVE)) { WorkflowableV1 workflowable = (WorkflowableV1)res; if (workflowable.isLive()) { view = workflowable.getLiveView(viewId); } else { String message = "The resource '" + res.getPath() + "' is WorkflowableV1, but has not been published yet. Instead a live version, the most recent version will be displayed!"; log.warn(message); view = ((ViewableV2) res).getView(viewId); // TODO: Maybe sending a 404 instead the most recent version should be configurable! /* do404(request, response, doc, message); return; */ } } else { view = ((ViewableV2) res).getView(viewId); } } catch(org.wyona.yarep.core.NoSuchNodeException e) { String message = "" + e; log.warn(message); do404(request, response, doc, message); return; } catch(org.wyona.yanel.core.ResourceNotFoundException e) { String message = "" + e; log.warn(message); do404(request, response, doc, message); return; } } else { Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("not-viewable")); String message = res.getClass().getName() + " is not viewable! (" + res.getPath() + ", " + res.getRealm() + ")"; noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!")); log.error(message); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "501"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED); setYanelOutput(request, response, doc); return; } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { lastModified = ((ModifiableV2) res).getLastModified(); Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified")); lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString())); } else { Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // retrieve the revisions, but only in the meta usecase (for performance reasons): if (request.getParameter("yanel.resource.meta") != null) { RevisionInformation[] revisions = ((VersionableV2)res).getRevisions(); Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement("revisions")); if (revisions != null && revisions.length > 0) { for (int i = revisions.length - 1; i >= 0; i--) { Element revisionElement = (Element) revisionsElement.appendChild(doc.createElement("revision")); Element revisionNameElement = (Element) revisionElement.appendChild(doc.createElement("name")); revisionNameElement.appendChild(doc.createTextNode(revisions[i].getName())); Element revisionDateElement = (Element) revisionElement.appendChild(doc.createElement("date")); revisionDateElement.appendChild(doc.createTextNode(DateUtil.format(revisions[i].getDate()))); Element revisionUserElement = (Element) revisionElement.appendChild(doc.createElement("user")); revisionUserElement.appendChild(doc.createTextNode(revisions[i].getUser())); Element revisionCommentElement = (Element) revisionElement.appendChild(doc.createElement("comment")); revisionCommentElement.appendChild(doc.createTextNode(revisions[i].getComment())); } } else { Element noRevisionsYetElement = (Element) resourceElement.appendChild(doc.createElement("no-revisions-yet")); } } } else { Element notVersionableElement = (Element) resourceElement.appendChild(doc.createElement("not-versionable")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Translatable", "1")) { TranslatableV1 translatable = ((TranslatableV1) res); Element translationsElement = (Element) resourceElement.appendChild(doc.createElement("translations")); String[] languages = translatable.getLanguages(); for (int i=0; i<languages.length; i++) { Element translationElement = (Element) translationsElement.appendChild(doc.createElement("translation")); translationElement.setAttribute("language", languages[i]); String path = translatable.getTranslation(languages[i]).getPath(); translationElement.setAttribute("path", path); } } if (usecase != null && usecase.equals("checkout")) { if(log.isDebugEnabled()) log.debug("Checkout data ..."); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // note: this will throw an exception if the document is checked out already // by another user. String userID = environment.getIdentity().getUsername(); VersionableV2 versionable = (VersionableV2)res; if (versionable.isCheckedOut()) { String checkoutUserID = versionable.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { log.warn("Resource " + res.getPath() + " is already checked out by this user: " + checkoutUserID); } else { throw new Exception("Resource is already checked out by another user: " + checkoutUserID); } } else { versionable.checkout(userID); } } else { log.warn("Acquire lock has not been implemented yet ...!"); // acquireLock(); } } } else { Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null")); } } catch(org.wyona.yarep.core.NoSuchNodeException e) { String message = "" + e; log.warn(e, e); do404(request, response, doc, message); return; } catch(org.wyona.yanel.core.ResourceNotFoundException e) { String message = "" + e; log.warn(e, e); do404(request, response, doc, message); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString() + "\n\n" + getStackTrace(e); //String message = e.toString(); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } // TODO: Move this introspection generation somewhere else ... try { if (usecase != null && usecase.equals("introspection")) { if (ResourceAttributeHelper.hasAttributeImplemented(res, "Introspectable", "1")) { String introspection = ((IntrospectableV1)res).getIntrospection(); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.getWriter().print(introspection); } else { String message = "Resource is not introspectable."; Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); } return; } } catch(Exception e) { log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(e.getMessage())); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } String meta = request.getParameter("yanel.resource.meta"); if (meta != null) { if (meta.length() > 0) { log.warn("TODO: meta: " + meta); } else { log.debug("Show all meta"); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); setYanelOutput(request, response, doc); return; } if (view != null) { if (generateResponse(view, res, request, response, doc, size, lastModified) != null) return; } else { String message = "View is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; }
private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { View view = null; org.w3c.dom.Document doc = null; try { doc = getDocument(NAMESPACE, "yanel"); } catch(Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } Element rootElement = doc.getDocumentElement(); rootElement.setAttribute("servlet-context-real-path", servletContextRealPath); Element requestElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "request")); requestElement.setAttributeNS(NAMESPACE, "uri", request.getRequestURI()); requestElement.setAttributeNS(NAMESPACE, "servlet-path", request.getServletPath()); HttpSession session = request.getSession(true); Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session")); sessionElement.setAttribute("id", session.getId()); Enumeration attrNames = session.getAttributeNames(); if (!attrNames.hasMoreElements()) { Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes")); } while (attrNames.hasMoreElements()) { String name = (String)attrNames.nextElement(); String value = session.getAttribute(name).toString(); Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute")); sessionAttributeElement.setAttribute("name", name); sessionAttributeElement.appendChild(doc.createTextNode(value)); } String usecase = request.getParameter("yanel.resource.usecase"); Resource res = null; long lastModified = -1; long size = -1; try { Environment environment = getEnvironment(request, response); res = getResource(request, response); if (res != null) { Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource")); ResourceConfiguration resConfig = res.getConfiguration(); if (resConfig != null) { Element resConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "config")); resConfigElement.setAttributeNS(NAMESPACE, "rti-name", resConfig.getName()); resConfigElement.setAttributeNS(NAMESPACE, "rti-namespace", resConfig.getNamespace()); } else { Element noResConfigElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "no-config")); } Element realmElement = (Element) resourceElement.appendChild(doc.createElementNS(NAMESPACE, "realm")); realmElement.setAttributeNS(NAMESPACE, "name", res.getRealm().getName()); realmElement.setAttributeNS(NAMESPACE, "rid", res.getRealm().getID()); realmElement.setAttributeNS(NAMESPACE, "prefix", res.getRealm().getMountPoint()); Element identityManagerElement = (Element) realmElement.appendChild(doc.createElementNS(NAMESPACE, "identity-manager")); Element userManagerElement = (Element) identityManagerElement.appendChild(doc.createElementNS(NAMESPACE, "user-manager")); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { if (log.isDebugEnabled()) log.debug("Resource is viewable V1"); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.setAttributeNS(NAMESPACE, "version", "1"); // TODO: The same as for ViewableV2 ... ViewDescriptor[] vd = ((ViewableV1) res).getViewDescriptors(); if (vd != null) { for (int i = 0; i < vd.length; i++) { Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor")); if (vd[i].getMimeType() != null) { descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType())); } descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId()); } } else { viewElement.appendChild(doc.createTextNode("No View Descriptors!")); } String viewId = request.getParameter(VIEW_ID_PARAM_NAME); try { view = ((ViewableV1) res).getView(request, viewId); } catch(org.wyona.yarep.core.NoSuchNodeException e) { do404(request, response, doc, e.getMessage()); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "500"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) { if (log.isDebugEnabled()) log.debug("Resource is viewable V2"); if (!((ViewableV2) res).exists()) { //log.warn("No such ViewableV2 resource: " + res.getPath()); //log.warn("TODO: It seems like many ViewableV2 resources are not implementing exists() properly!"); //do404(request, response, doc, res.getPath()); //return; } String viewId = request.getParameter(VIEW_ID_PARAM_NAME); Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.setAttributeNS(NAMESPACE, "version", "2"); ViewDescriptor[] vd = ((ViewableV2) res).getViewDescriptors(); if (vd != null) { for (int i = 0; i < vd.length; i++) { Element descriptorElement = (Element) viewElement.appendChild(doc.createElement("descriptor")); if (vd[i].getMimeType() != null) { descriptorElement.appendChild(doc.createTextNode(vd[i].getMimeType())); } descriptorElement.setAttributeNS(NAMESPACE, "id", vd[i].getId()); } } else { viewElement.appendChild(doc.createTextNode("No View Descriptors!")); } size = ((ViewableV2) res).getSize(); Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size")); sizeElement.appendChild(doc.createTextNode(String.valueOf(size))); try { String revisionName = request.getParameter("yanel.resource.revision"); if (revisionName != null && ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { view = ((VersionableV2) res).getView(viewId, revisionName); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Workflowable", "1") && environment.getStateOfView().equals(StateOfView.LIVE)) { WorkflowableV1 workflowable = (WorkflowableV1)res; if (workflowable.isLive()) { view = workflowable.getLiveView(viewId); } else { String message = "The resource '" + res.getPath() + "' is WorkflowableV1, but has not been published yet. Instead the live version, the most recent version will be displayed!"; log.warn(message); view = ((ViewableV2) res).getView(viewId); // TODO: Maybe sending a 404 instead the most recent version should be configurable! /* do404(request, response, doc, message); return; */ } } else { view = ((ViewableV2) res).getView(viewId); } } catch(org.wyona.yarep.core.NoSuchNodeException e) { String message = "" + e; log.warn(message); do404(request, response, doc, message); return; } catch(org.wyona.yanel.core.ResourceNotFoundException e) { String message = "" + e; log.warn(message); do404(request, response, doc, message); return; } } else { Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("not-viewable")); String message = res.getClass().getName() + " is not viewable! (" + res.getPath() + ", " + res.getRealm() + ")"; noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!")); log.error(message); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttributeNS(NAMESPACE, "status", "501"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED); setYanelOutput(request, response, doc); return; } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { lastModified = ((ModifiableV2) res).getLastModified(); Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified")); lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString())); } else { Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // retrieve the revisions, but only in the meta usecase (for performance reasons): if (request.getParameter("yanel.resource.meta") != null) { RevisionInformation[] revisions = ((VersionableV2)res).getRevisions(); Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement("revisions")); if (revisions != null && revisions.length > 0) { for (int i = revisions.length - 1; i >= 0; i--) { Element revisionElement = (Element) revisionsElement.appendChild(doc.createElement("revision")); Element revisionNameElement = (Element) revisionElement.appendChild(doc.createElement("name")); revisionNameElement.appendChild(doc.createTextNode(revisions[i].getName())); Element revisionDateElement = (Element) revisionElement.appendChild(doc.createElement("date")); revisionDateElement.appendChild(doc.createTextNode(DateUtil.format(revisions[i].getDate()))); Element revisionUserElement = (Element) revisionElement.appendChild(doc.createElement("user")); revisionUserElement.appendChild(doc.createTextNode(revisions[i].getUser())); Element revisionCommentElement = (Element) revisionElement.appendChild(doc.createElement("comment")); revisionCommentElement.appendChild(doc.createTextNode(revisions[i].getComment())); } } else { Element noRevisionsYetElement = (Element) resourceElement.appendChild(doc.createElement("no-revisions-yet")); } } } else { Element notVersionableElement = (Element) resourceElement.appendChild(doc.createElement("not-versionable")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Translatable", "1")) { TranslatableV1 translatable = ((TranslatableV1) res); Element translationsElement = (Element) resourceElement.appendChild(doc.createElement("translations")); String[] languages = translatable.getLanguages(); for (int i=0; i<languages.length; i++) { Element translationElement = (Element) translationsElement.appendChild(doc.createElement("translation")); translationElement.setAttribute("language", languages[i]); String path = translatable.getTranslation(languages[i]).getPath(); translationElement.setAttribute("path", path); } } if (usecase != null && usecase.equals("checkout")) { if(log.isDebugEnabled()) log.debug("Checkout data ..."); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) { // note: this will throw an exception if the document is checked out already // by another user. String userID = environment.getIdentity().getUsername(); VersionableV2 versionable = (VersionableV2)res; if (versionable.isCheckedOut()) { String checkoutUserID = versionable.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { log.warn("Resource " + res.getPath() + " is already checked out by this user: " + checkoutUserID); } else { throw new Exception("Resource is already checked out by another user: " + checkoutUserID); } } else { versionable.checkout(userID); } } else { log.warn("Acquire lock has not been implemented yet ...!"); // acquireLock(); } } } else { Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null")); } } catch(org.wyona.yarep.core.NoSuchNodeException e) { String message = "" + e; log.warn(e, e); do404(request, response, doc, message); return; } catch(org.wyona.yanel.core.ResourceNotFoundException e) { String message = "" + e; log.warn(e, e); do404(request, response, doc, message); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString() + "\n\n" + getStackTrace(e); //String message = e.toString(); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } // TODO: Move this introspection generation somewhere else ... try { if (usecase != null && usecase.equals("introspection")) { if (ResourceAttributeHelper.hasAttributeImplemented(res, "Introspectable", "1")) { String introspection = ((IntrospectableV1)res).getIntrospection(); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.getWriter().print(introspection); } else { String message = "Resource is not introspectable."; Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(request, response, doc); } return; } } catch(Exception e) { log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(e.getMessage())); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; } String meta = request.getParameter("yanel.resource.meta"); if (meta != null) { if (meta.length() > 0) { log.warn("TODO: meta: " + meta); } else { log.debug("Show all meta"); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); setYanelOutput(request, response, doc); return; } if (view != null) { if (generateResponse(view, res, request, response, doc, size, lastModified) != null) return; } else { String message = "View is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElementNS(NAMESPACE, "exception")); exceptionElement.appendChild(doc.createTextNode(message)); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(request, response, doc); return; }
diff --git a/src/pojoGenerator/Main.java b/src/pojoGenerator/Main.java index b38d5c8..f61a062 100644 --- a/src/pojoGenerator/Main.java +++ b/src/pojoGenerator/Main.java @@ -1,255 +1,255 @@ package pojoGenerator; 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.io.InputStreamReader; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectHelper; public class Main { public static void main(String[] args) throws Exception { PathHolder.loadConfig(); deleteFolders(); createParentStructure(); checkOutFiles(); File f = new File(PathHolder.SOURCE_PATH); generatePojoClasses(f); File pojoPath = new File(PathHolder.TEMP_POJO); removeUnwantedFilesAndStrings(pojoPath); System.out.println("\nCompleted generating pojo's at path " + PathHolder.POJO_TARGET_PATH); } private static String getFileNameWithoutExtension(String name) { int pos = name.lastIndexOf("."); if (pos > 0) { name = name.substring(0, pos); } return name; } public static final String[] unwantedContainsArray = { "org.apache.commons.lang.builder", "org.codehaus.jackson", "javax.annotation", "additionalProperties>"}; public static final String[] unwantedStartsWithArray = { "@" }; private static void refactorFileAndGenerateDuplicate(File f) throws Exception { String path = PathHolder.POJO_TARGET_PATH + File.separator + f.getPath().substring(f.getPath().indexOf("com" + File.separator)); File targetFile = new File(path); File parent = targetFile.getParentFile(); if(!parent.exists() && !parent.mkdirs()){ throw new IllegalStateException("Couldn't create dir: " + parent); } FileReader fileReader = new FileReader(f); BufferedReader reader = new BufferedReader(fileReader); BufferedWriter writer = new BufferedWriter(new FileWriter(path)); String currentLine; boolean isValueFound = false; StringBuilder dataHolder = new StringBuilder(); while ((currentLine = reader.readLine()) != null) { String trimmedLine = currentLine.trim(); isValueFound = false; for (String value : unwantedStartsWithArray) { if (trimmedLine.startsWith(value)) { isValueFound = true; break; } } if (isValueFound) { continue; } isValueFound = false; for (String value : unwantedContainsArray) { if (trimmedLine.contains(value)) { isValueFound = true; break; } } if (isValueFound) { continue; } if (currentLine.startsWith("public class")) { dataHolder.append("import com.google.gson.Gson;\n"); dataHolder.append("import com.wethejumpingspiders.finance.base.PojoDataPartInterface;\n"); dataHolder.append("public class " + getFileNameWithoutExtension(f.getName()) + " implements PojoDataPartInterface {\n"); File servlet = f.getParentFile().getParentFile(); File base = servlet.getParentFile(); String getServletGroupMethod = "public String getServletGroup() {\n return \"" + base.getName() + "\";\n }"; String getServletNameMethod = "public String getServletName() {\n return \"" + servlet.getName() + "\";\n }"; - String toJSON = "public String toJSON() {\n Gson gson = new Gson(); \n return gson.toJson(this.getClass());\n }"; + String toJSON = "public String toJSON() {\n Gson gson = new Gson(); \n return gson.toJson(this);\n }"; dataHolder.append(getServletGroupMethod); dataHolder.append("\n"); dataHolder.append(getServletNameMethod); dataHolder.append("\n"); dataHolder.append(toJSON); continue; } dataHolder.append(currentLine); dataHolder.append("\n"); } String modifiedData = dataHolder.toString(); writer.write(modifiedData); fileReader.close(); writer.flush(); writer.close(); } private static void removeUnwantedFilesAndStrings(File f) throws Exception{ for (File file : f.listFiles()) { if (file.isDirectory()) { removeUnwantedFilesAndStrings(file); } else { if (file.getName().endsWith(".java")) { String[] nameOfFilesToBeDeleted = {"Request.java", "Request_.java", "Echo.java", "Response.java", "Response_.java"}; for (int i = 0; i < nameOfFilesToBeDeleted.length; i++) { if (file.getName().equalsIgnoreCase(nameOfFilesToBeDeleted[i])) { deleteDir(file); return; } } refactorFileAndGenerateDuplicate(file); } } } } private static void generatePojoClasses(File f) { for (File file : f.listFiles()) { if (file.isDirectory()) { generatePojoClasses(file); } else { if (file.getName().endsWith(".json")) { System.out.println(file.getName() + " is a .json file."); File servlet = file.getParentFile().getParentFile(); File base = servlet.getParentFile(); String basePackage = PathHolder.PACKAGENAME + "." + base.getName() + "." + servlet.getName(); if (file.getName().startsWith("request")) { createPojo(file.getAbsolutePath(), PathHolder.TEMP_POJO, basePackage + ".Request"); } else if (file.getName().startsWith("response")) { createPojo(file.getAbsolutePath(), PathHolder.TEMP_POJO, basePackage + ".Response"); } } } } } private static void createPojo(String fromJSONFileNamed, String targetFolder, String packageName) { System.out.println("\nTrying to generate POJO from " + fromJSONFileNamed + " \nto: " + targetFolder + "\nusingPackageName " + packageName); File buildFile = new File("build.xml"); Project p = new Project(); p.setUserProperty("ant.file", buildFile.getAbsolutePath()); p.setUserProperty("targetPackage", packageName); p.setUserProperty("targetDirectory", targetFolder); p.setUserProperty("source", fromJSONFileNamed); p.init(); ProjectHelper helper = ProjectHelper.getProjectHelper(); p.addReference("ant.projectHelper", helper); helper.parse(p, buildFile); p.executeTarget(p.getDefaultTarget()); } public static void checkOutFiles() throws Exception { File f = new File(PathHolder.CHECKOUT_PATH); Process p = Runtime.getRuntime().exec(PathHolder.SVN_CO_CMD, null, f); readFromProcess(p); } public static void deleteFolders() { String[] dirCreater = { PathHolder.SCHEMA_FILE, PathHolder.POJO_TARGET_PATH, PathHolder.TEMP_POJO}; for (int i = 0; i < dirCreater.length; i++) { deleteDir(new File(dirCreater[i])); } } public static void createParentStructure() { String[] path = { PathHolder.CHECKOUT_PATH, PathHolder.POJO_TARGET_PATH, PathHolder.TEMP_POJO}; File mainFolder = new File(PathHolder.MAIN_FOLDER); if (mainFolder.exists()) { deleteDir(mainFolder); } mainFolder.mkdir(); for (int i = 0; i < path.length; i++) { File file = new File(path[i]); file.mkdirs(); } } public static void deleteDir(File dir) { if (dir.isDirectory()) { File[] parent = dir.listFiles(); for (File file : parent) { if (file.isDirectory()) { deleteDir(file); } file.delete(); } } } private static void readFromProcess(Process p) throws IOException { BufferedReader bi = new BufferedReader(new InputStreamReader( p.getInputStream())); String lineString = null; while ((lineString = bi.readLine()) != null) { System.out.println(lineString); } bi.close(); } }
true
true
private static void refactorFileAndGenerateDuplicate(File f) throws Exception { String path = PathHolder.POJO_TARGET_PATH + File.separator + f.getPath().substring(f.getPath().indexOf("com" + File.separator)); File targetFile = new File(path); File parent = targetFile.getParentFile(); if(!parent.exists() && !parent.mkdirs()){ throw new IllegalStateException("Couldn't create dir: " + parent); } FileReader fileReader = new FileReader(f); BufferedReader reader = new BufferedReader(fileReader); BufferedWriter writer = new BufferedWriter(new FileWriter(path)); String currentLine; boolean isValueFound = false; StringBuilder dataHolder = new StringBuilder(); while ((currentLine = reader.readLine()) != null) { String trimmedLine = currentLine.trim(); isValueFound = false; for (String value : unwantedStartsWithArray) { if (trimmedLine.startsWith(value)) { isValueFound = true; break; } } if (isValueFound) { continue; } isValueFound = false; for (String value : unwantedContainsArray) { if (trimmedLine.contains(value)) { isValueFound = true; break; } } if (isValueFound) { continue; } if (currentLine.startsWith("public class")) { dataHolder.append("import com.google.gson.Gson;\n"); dataHolder.append("import com.wethejumpingspiders.finance.base.PojoDataPartInterface;\n"); dataHolder.append("public class " + getFileNameWithoutExtension(f.getName()) + " implements PojoDataPartInterface {\n"); File servlet = f.getParentFile().getParentFile(); File base = servlet.getParentFile(); String getServletGroupMethod = "public String getServletGroup() {\n return \"" + base.getName() + "\";\n }"; String getServletNameMethod = "public String getServletName() {\n return \"" + servlet.getName() + "\";\n }"; String toJSON = "public String toJSON() {\n Gson gson = new Gson(); \n return gson.toJson(this.getClass());\n }"; dataHolder.append(getServletGroupMethod); dataHolder.append("\n"); dataHolder.append(getServletNameMethod); dataHolder.append("\n"); dataHolder.append(toJSON); continue; } dataHolder.append(currentLine); dataHolder.append("\n"); } String modifiedData = dataHolder.toString(); writer.write(modifiedData); fileReader.close(); writer.flush(); writer.close(); }
private static void refactorFileAndGenerateDuplicate(File f) throws Exception { String path = PathHolder.POJO_TARGET_PATH + File.separator + f.getPath().substring(f.getPath().indexOf("com" + File.separator)); File targetFile = new File(path); File parent = targetFile.getParentFile(); if(!parent.exists() && !parent.mkdirs()){ throw new IllegalStateException("Couldn't create dir: " + parent); } FileReader fileReader = new FileReader(f); BufferedReader reader = new BufferedReader(fileReader); BufferedWriter writer = new BufferedWriter(new FileWriter(path)); String currentLine; boolean isValueFound = false; StringBuilder dataHolder = new StringBuilder(); while ((currentLine = reader.readLine()) != null) { String trimmedLine = currentLine.trim(); isValueFound = false; for (String value : unwantedStartsWithArray) { if (trimmedLine.startsWith(value)) { isValueFound = true; break; } } if (isValueFound) { continue; } isValueFound = false; for (String value : unwantedContainsArray) { if (trimmedLine.contains(value)) { isValueFound = true; break; } } if (isValueFound) { continue; } if (currentLine.startsWith("public class")) { dataHolder.append("import com.google.gson.Gson;\n"); dataHolder.append("import com.wethejumpingspiders.finance.base.PojoDataPartInterface;\n"); dataHolder.append("public class " + getFileNameWithoutExtension(f.getName()) + " implements PojoDataPartInterface {\n"); File servlet = f.getParentFile().getParentFile(); File base = servlet.getParentFile(); String getServletGroupMethod = "public String getServletGroup() {\n return \"" + base.getName() + "\";\n }"; String getServletNameMethod = "public String getServletName() {\n return \"" + servlet.getName() + "\";\n }"; String toJSON = "public String toJSON() {\n Gson gson = new Gson(); \n return gson.toJson(this);\n }"; dataHolder.append(getServletGroupMethod); dataHolder.append("\n"); dataHolder.append(getServletNameMethod); dataHolder.append("\n"); dataHolder.append(toJSON); continue; } dataHolder.append(currentLine); dataHolder.append("\n"); } String modifiedData = dataHolder.toString(); writer.write(modifiedData); fileReader.close(); writer.flush(); writer.close(); }
diff --git a/Basics/src/coolawesomeme/basics_plugin/EventListener.java b/Basics/src/coolawesomeme/basics_plugin/EventListener.java index db2e093..791aff0 100644 --- a/Basics/src/coolawesomeme/basics_plugin/EventListener.java +++ b/Basics/src/coolawesomeme/basics_plugin/EventListener.java @@ -1,35 +1,35 @@ package coolawesomeme.basics_plugin; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import coolawesomeme.basics_plugin.commands.BrbCommand; import coolawesomeme.basics_plugin.commands.ServerHelpCommand; public class EventListener implements Listener{ @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { PlayerDataStorage.makePlayerDataFile(event.getPlayer().getName()); if(BrbCommand.isOwnerBRBing){ if(!event.getPlayer().hasPlayedBefore()){ final PlayerJoinEvent newEvent = event; Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(new Basics(), new Runnable() { @Override public void run() { ServerHelpCommand.actualServerHelp(newEvent.getPlayer()); } }, 20L); }else{ event.getPlayer().sendMessage("Welcome to the " + Basics.serverName + ", " + event.getPlayer().getDisplayName() + "!"); event.getPlayer().sendMessage(""); event.getPlayer().sendMessage(MinecraftColors.lightRed + "Server is currently in BRB mode because the server owner is brbing!"); } }else{ - event.getPlayer().sendMessage("Welcome to the " + Basics.serverName + ", " + event.getPlayer().getDisplayName() + "!"); + event.getPlayer().sendMessage("Welcome to the " + Basics.serverName + ", " + event.getPlayer().getDisplayName() + "!"); } } }
true
true
public void onPlayerJoin(PlayerJoinEvent event) { PlayerDataStorage.makePlayerDataFile(event.getPlayer().getName()); if(BrbCommand.isOwnerBRBing){ if(!event.getPlayer().hasPlayedBefore()){ final PlayerJoinEvent newEvent = event; Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(new Basics(), new Runnable() { @Override public void run() { ServerHelpCommand.actualServerHelp(newEvent.getPlayer()); } }, 20L); }else{ event.getPlayer().sendMessage("Welcome to the " + Basics.serverName + ", " + event.getPlayer().getDisplayName() + "!"); event.getPlayer().sendMessage(""); event.getPlayer().sendMessage(MinecraftColors.lightRed + "Server is currently in BRB mode because the server owner is brbing!"); } }else{ event.getPlayer().sendMessage("Welcome to the " + Basics.serverName + ", " + event.getPlayer().getDisplayName() + "!"); } }
public void onPlayerJoin(PlayerJoinEvent event) { PlayerDataStorage.makePlayerDataFile(event.getPlayer().getName()); if(BrbCommand.isOwnerBRBing){ if(!event.getPlayer().hasPlayedBefore()){ final PlayerJoinEvent newEvent = event; Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(new Basics(), new Runnable() { @Override public void run() { ServerHelpCommand.actualServerHelp(newEvent.getPlayer()); } }, 20L); }else{ event.getPlayer().sendMessage("Welcome to the " + Basics.serverName + ", " + event.getPlayer().getDisplayName() + "!"); event.getPlayer().sendMessage(""); event.getPlayer().sendMessage(MinecraftColors.lightRed + "Server is currently in BRB mode because the server owner is brbing!"); } }else{ event.getPlayer().sendMessage("Welcome to the " + Basics.serverName + ", " + event.getPlayer().getDisplayName() + "!"); } }
diff --git a/parser/org/eclipse/cdt/core/dom/parser/GNUScannerExtensionConfiguration.java b/parser/org/eclipse/cdt/core/dom/parser/GNUScannerExtensionConfiguration.java index 30b7335ee..0ed8d0f32 100644 --- a/parser/org/eclipse/cdt/core/dom/parser/GNUScannerExtensionConfiguration.java +++ b/parser/org/eclipse/cdt/core/dom/parser/GNUScannerExtensionConfiguration.java @@ -1,106 +1,106 @@ /******************************************************************************* * Copyright (c) 2004, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM - Initial API and implementation * Anton Leherbauer (Wind River Systems) * Markus Schorn (Wind River Systems) * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.core.dom.parser; import org.eclipse.cdt.core.parser.GCCKeywords; import org.eclipse.cdt.core.parser.IGCCToken; import org.eclipse.cdt.core.parser.IMacro; import org.eclipse.cdt.core.parser.IPreprocessorDirective; import org.eclipse.cdt.core.parser.IToken; import org.eclipse.cdt.core.parser.Keywords; import org.eclipse.cdt.core.parser.util.CharArrayIntMap; /** * Base class for all gnu scanner configurations. Provides gnu-specific macros and keywords. * @since 5.0 */ public abstract class GNUScannerExtensionConfiguration extends AbstractScannerExtensionConfiguration { private static GNUScannerExtensionConfiguration sInstance; @SuppressWarnings("nls") public GNUScannerExtensionConfiguration() { addMacro("__complex__", "_Complex"); addMacro("__extension__", ""); addMacro("__imag__", "(int)"); addMacro("__real__", "(int)"); addMacro("__stdcall", ""); addMacro("__builtin_va_arg(ap,type)", "*(type *)ap"); addMacro("__builtin_constant_p(exp)", "0"); - addMacro("__builtin_types_compatible_p(x,y)", "__builtin_types_compatible_p(sizeof(x),sizeof(y)"); + addMacro("__builtin_types_compatible_p(x,y)", "__builtin_types_compatible_p(sizeof(x),sizeof(y))"); addPreprocessorKeyword(Keywords.cINCLUDE_NEXT, IPreprocessorDirective.ppInclude_next); addPreprocessorKeyword(Keywords.cIMPORT, IPreprocessorDirective.ppImport); addPreprocessorKeyword(Keywords.cWARNING, IPreprocessorDirective.ppWarning); addPreprocessorKeyword(Keywords.cIDENT, IPreprocessorDirective.ppIgnore); addPreprocessorKeyword(Keywords.cSCCS, IPreprocessorDirective.ppIgnore); addPreprocessorKeyword(Keywords.cASSERT, IPreprocessorDirective.ppIgnore); addPreprocessorKeyword(Keywords.cUNASSERT, IPreprocessorDirective.ppIgnore); addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ ); addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ ); addKeyword(GCCKeywords.cp__ASM, IToken.t_asm); addKeyword(GCCKeywords.cp__ASM__, IToken.t_asm); addKeyword(GCCKeywords.cp__ATTRIBUTE, IGCCToken.t__attribute__ ); addKeyword(GCCKeywords.cp__ATTRIBUTE__, IGCCToken.t__attribute__ ); addKeyword(GCCKeywords.cp__CONST, IToken.t_const); addKeyword(GCCKeywords.cp__CONST__, IToken.t_const); addKeyword(GCCKeywords.cp__DECLSPEC, IGCCToken.t__declspec ); addKeyword(GCCKeywords.cp__INLINE, IToken.t_inline); addKeyword(GCCKeywords.cp__INLINE__, IToken.t_inline); addKeyword(GCCKeywords.cp__RESTRICT, IToken.t_restrict); addKeyword(GCCKeywords.cp__RESTRICT__, IToken.t_restrict); addKeyword(GCCKeywords.cp__VOLATILE, IToken.t_volatile); addKeyword(GCCKeywords.cp__VOLATILE__, IToken.t_volatile); addKeyword(GCCKeywords.cp__SIGNED, IToken.t_signed); addKeyword(GCCKeywords.cp__SIGNED__, IToken.t_signed); addKeyword(GCCKeywords.cp__TYPEOF, IGCCToken.t_typeof); addKeyword(GCCKeywords.cp__TYPEOF__, IGCCToken.t_typeof); addKeyword(GCCKeywords.cpTYPEOF, IGCCToken.t_typeof ); } @Override public boolean support$InIdentifiers() { return true; } @Override public char[] supportAdditionalNumericLiteralSuffixes() { return "ij".toCharArray(); //$NON-NLS-1$ } /** * @deprecated simply derive from this class and use {@link #addMacro(String, String)} to * add additional macros. */ @Deprecated public static IMacro[] getAdditionalGNUMacros() { if (sInstance == null) { sInstance= new GNUScannerExtensionConfiguration() {}; } return sInstance.getAdditionalMacros(); } /** * @deprecated simply derive from this class and use {@link #addKeyword(char[], int)} to * add additional keywords. */ @Deprecated public static void addAdditionalGNUKeywords(CharArrayIntMap target) { if (sInstance == null) { sInstance= new GNUScannerExtensionConfiguration() {}; } target.putAll(sInstance.getAdditionalKeywords()); } }
true
true
public GNUScannerExtensionConfiguration() { addMacro("__complex__", "_Complex"); addMacro("__extension__", ""); addMacro("__imag__", "(int)"); addMacro("__real__", "(int)"); addMacro("__stdcall", ""); addMacro("__builtin_va_arg(ap,type)", "*(type *)ap"); addMacro("__builtin_constant_p(exp)", "0"); addMacro("__builtin_types_compatible_p(x,y)", "__builtin_types_compatible_p(sizeof(x),sizeof(y)"); addPreprocessorKeyword(Keywords.cINCLUDE_NEXT, IPreprocessorDirective.ppInclude_next); addPreprocessorKeyword(Keywords.cIMPORT, IPreprocessorDirective.ppImport); addPreprocessorKeyword(Keywords.cWARNING, IPreprocessorDirective.ppWarning); addPreprocessorKeyword(Keywords.cIDENT, IPreprocessorDirective.ppIgnore); addPreprocessorKeyword(Keywords.cSCCS, IPreprocessorDirective.ppIgnore); addPreprocessorKeyword(Keywords.cASSERT, IPreprocessorDirective.ppIgnore); addPreprocessorKeyword(Keywords.cUNASSERT, IPreprocessorDirective.ppIgnore); addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ ); addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ ); addKeyword(GCCKeywords.cp__ASM, IToken.t_asm); addKeyword(GCCKeywords.cp__ASM__, IToken.t_asm); addKeyword(GCCKeywords.cp__ATTRIBUTE, IGCCToken.t__attribute__ ); addKeyword(GCCKeywords.cp__ATTRIBUTE__, IGCCToken.t__attribute__ ); addKeyword(GCCKeywords.cp__CONST, IToken.t_const); addKeyword(GCCKeywords.cp__CONST__, IToken.t_const); addKeyword(GCCKeywords.cp__DECLSPEC, IGCCToken.t__declspec ); addKeyword(GCCKeywords.cp__INLINE, IToken.t_inline); addKeyword(GCCKeywords.cp__INLINE__, IToken.t_inline); addKeyword(GCCKeywords.cp__RESTRICT, IToken.t_restrict); addKeyword(GCCKeywords.cp__RESTRICT__, IToken.t_restrict); addKeyword(GCCKeywords.cp__VOLATILE, IToken.t_volatile); addKeyword(GCCKeywords.cp__VOLATILE__, IToken.t_volatile); addKeyword(GCCKeywords.cp__SIGNED, IToken.t_signed); addKeyword(GCCKeywords.cp__SIGNED__, IToken.t_signed); addKeyword(GCCKeywords.cp__TYPEOF, IGCCToken.t_typeof); addKeyword(GCCKeywords.cp__TYPEOF__, IGCCToken.t_typeof); addKeyword(GCCKeywords.cpTYPEOF, IGCCToken.t_typeof ); }
public GNUScannerExtensionConfiguration() { addMacro("__complex__", "_Complex"); addMacro("__extension__", ""); addMacro("__imag__", "(int)"); addMacro("__real__", "(int)"); addMacro("__stdcall", ""); addMacro("__builtin_va_arg(ap,type)", "*(type *)ap"); addMacro("__builtin_constant_p(exp)", "0"); addMacro("__builtin_types_compatible_p(x,y)", "__builtin_types_compatible_p(sizeof(x),sizeof(y))"); addPreprocessorKeyword(Keywords.cINCLUDE_NEXT, IPreprocessorDirective.ppInclude_next); addPreprocessorKeyword(Keywords.cIMPORT, IPreprocessorDirective.ppImport); addPreprocessorKeyword(Keywords.cWARNING, IPreprocessorDirective.ppWarning); addPreprocessorKeyword(Keywords.cIDENT, IPreprocessorDirective.ppIgnore); addPreprocessorKeyword(Keywords.cSCCS, IPreprocessorDirective.ppIgnore); addPreprocessorKeyword(Keywords.cASSERT, IPreprocessorDirective.ppIgnore); addPreprocessorKeyword(Keywords.cUNASSERT, IPreprocessorDirective.ppIgnore); addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ ); addKeyword(GCCKeywords.cp__ALIGNOF__, IGCCToken.t___alignof__ ); addKeyword(GCCKeywords.cp__ASM, IToken.t_asm); addKeyword(GCCKeywords.cp__ASM__, IToken.t_asm); addKeyword(GCCKeywords.cp__ATTRIBUTE, IGCCToken.t__attribute__ ); addKeyword(GCCKeywords.cp__ATTRIBUTE__, IGCCToken.t__attribute__ ); addKeyword(GCCKeywords.cp__CONST, IToken.t_const); addKeyword(GCCKeywords.cp__CONST__, IToken.t_const); addKeyword(GCCKeywords.cp__DECLSPEC, IGCCToken.t__declspec ); addKeyword(GCCKeywords.cp__INLINE, IToken.t_inline); addKeyword(GCCKeywords.cp__INLINE__, IToken.t_inline); addKeyword(GCCKeywords.cp__RESTRICT, IToken.t_restrict); addKeyword(GCCKeywords.cp__RESTRICT__, IToken.t_restrict); addKeyword(GCCKeywords.cp__VOLATILE, IToken.t_volatile); addKeyword(GCCKeywords.cp__VOLATILE__, IToken.t_volatile); addKeyword(GCCKeywords.cp__SIGNED, IToken.t_signed); addKeyword(GCCKeywords.cp__SIGNED__, IToken.t_signed); addKeyword(GCCKeywords.cp__TYPEOF, IGCCToken.t_typeof); addKeyword(GCCKeywords.cp__TYPEOF__, IGCCToken.t_typeof); addKeyword(GCCKeywords.cpTYPEOF, IGCCToken.t_typeof ); }
diff --git a/src/main/java/org/atlasapi/remotesite/hulu/HuluBrandContentExtractor.java b/src/main/java/org/atlasapi/remotesite/hulu/HuluBrandContentExtractor.java index a250a2cfa..d9594c178 100644 --- a/src/main/java/org/atlasapi/remotesite/hulu/HuluBrandContentExtractor.java +++ b/src/main/java/org/atlasapi/remotesite/hulu/HuluBrandContentExtractor.java @@ -1,83 +1,83 @@ package org.atlasapi.remotesite.hulu; import java.util.HashMap; import java.util.List; import java.util.Map; import org.atlasapi.media.entity.Brand; import org.atlasapi.media.entity.Episode; import org.atlasapi.media.entity.Publisher; import org.atlasapi.query.content.PerPublisherCurieExpander; import org.atlasapi.remotesite.ContentExtractor; import org.atlasapi.remotesite.FetchException; import org.atlasapi.remotesite.html.HtmlNavigator; import org.atlasapi.remotesite.hulu.HuluBrandAdapter.HuluBrandCanonicaliser; import org.codehaus.jackson.map.ObjectMapper; import org.jaxen.JaxenException; import org.jdom.Element; public class HuluBrandContentExtractor implements ContentExtractor<HtmlNavigator, Brand> { private static final String SOCIAL_FEED = "SocialFeed.facebook_template_data.subscribe = "; private static final ObjectMapper mapper = new ObjectMapper(); @SuppressWarnings("unchecked") @Override public Brand extract(HtmlNavigator source) { try { Brand brand = null; for (Element element : source.allElementsMatching("//body/script")) { String value = element.getValue(); if (value.startsWith(SOCIAL_FEED)) { try { Map<String, Object> attributes = mapper.readValue(value.replace(SOCIAL_FEED, ""), HashMap.class); String brandUri = new HuluBrandCanonicaliser().canonicalise((String) attributes.get("show_link")); brand = new Brand(brandUri, PerPublisherCurieExpander.CurieAlgorithm.HULU.compact(brandUri), Publisher.HULU); brand.setDescription((String) attributes.get("show_description")); brand.setTitle((String) attributes.get("show_title")); if (attributes.containsKey("images") && attributes.get("images") instanceof List) { List<Map<String, Object>> images = (List<Map<String, Object>>) attributes.get("images"); if (!images.isEmpty()) { brand.setThumbnail((String) images.get(0).get("src")); } } Element imageElement = source.firstElementOrNull("//img[@alt=\""+brand.getTitle()+"\"]"); if (imageElement != null) { brand.setImage(imageElement.getAttributeValue("src")); } break; } catch (Exception e) { throw new FetchException("Unable to map JSON values", e); } } } if (brand == null) { throw new FetchException("Page did not not contain a brand, possible change of markup?"); } brand.setTags(HuluItemContentExtractor.getTags(source)); for (Element element : source.allElementsMatching("//div[@id='episode-container']/div/ul/li/a']")) { String href = element.getAttributeValue("href"); String episodeUri = HuluFeed.canonicaliseEpisodeUri(href); if (episodeUri == null) { - throw new IllegalArgumentException("Cannot extract item uri from " + href); + continue; } Episode episode = new Episode(episodeUri, PerPublisherCurieExpander.CurieAlgorithm.HULU.compact(episodeUri), Publisher.HULU); brand.addItem(episode); } return brand; } catch (JaxenException e) { throw new FetchException("Unable to navigate HTML document", e); } } }
true
true
public Brand extract(HtmlNavigator source) { try { Brand brand = null; for (Element element : source.allElementsMatching("//body/script")) { String value = element.getValue(); if (value.startsWith(SOCIAL_FEED)) { try { Map<String, Object> attributes = mapper.readValue(value.replace(SOCIAL_FEED, ""), HashMap.class); String brandUri = new HuluBrandCanonicaliser().canonicalise((String) attributes.get("show_link")); brand = new Brand(brandUri, PerPublisherCurieExpander.CurieAlgorithm.HULU.compact(brandUri), Publisher.HULU); brand.setDescription((String) attributes.get("show_description")); brand.setTitle((String) attributes.get("show_title")); if (attributes.containsKey("images") && attributes.get("images") instanceof List) { List<Map<String, Object>> images = (List<Map<String, Object>>) attributes.get("images"); if (!images.isEmpty()) { brand.setThumbnail((String) images.get(0).get("src")); } } Element imageElement = source.firstElementOrNull("//img[@alt=\""+brand.getTitle()+"\"]"); if (imageElement != null) { brand.setImage(imageElement.getAttributeValue("src")); } break; } catch (Exception e) { throw new FetchException("Unable to map JSON values", e); } } } if (brand == null) { throw new FetchException("Page did not not contain a brand, possible change of markup?"); } brand.setTags(HuluItemContentExtractor.getTags(source)); for (Element element : source.allElementsMatching("//div[@id='episode-container']/div/ul/li/a']")) { String href = element.getAttributeValue("href"); String episodeUri = HuluFeed.canonicaliseEpisodeUri(href); if (episodeUri == null) { throw new IllegalArgumentException("Cannot extract item uri from " + href); } Episode episode = new Episode(episodeUri, PerPublisherCurieExpander.CurieAlgorithm.HULU.compact(episodeUri), Publisher.HULU); brand.addItem(episode); } return brand; } catch (JaxenException e) { throw new FetchException("Unable to navigate HTML document", e); } }
public Brand extract(HtmlNavigator source) { try { Brand brand = null; for (Element element : source.allElementsMatching("//body/script")) { String value = element.getValue(); if (value.startsWith(SOCIAL_FEED)) { try { Map<String, Object> attributes = mapper.readValue(value.replace(SOCIAL_FEED, ""), HashMap.class); String brandUri = new HuluBrandCanonicaliser().canonicalise((String) attributes.get("show_link")); brand = new Brand(brandUri, PerPublisherCurieExpander.CurieAlgorithm.HULU.compact(brandUri), Publisher.HULU); brand.setDescription((String) attributes.get("show_description")); brand.setTitle((String) attributes.get("show_title")); if (attributes.containsKey("images") && attributes.get("images") instanceof List) { List<Map<String, Object>> images = (List<Map<String, Object>>) attributes.get("images"); if (!images.isEmpty()) { brand.setThumbnail((String) images.get(0).get("src")); } } Element imageElement = source.firstElementOrNull("//img[@alt=\""+brand.getTitle()+"\"]"); if (imageElement != null) { brand.setImage(imageElement.getAttributeValue("src")); } break; } catch (Exception e) { throw new FetchException("Unable to map JSON values", e); } } } if (brand == null) { throw new FetchException("Page did not not contain a brand, possible change of markup?"); } brand.setTags(HuluItemContentExtractor.getTags(source)); for (Element element : source.allElementsMatching("//div[@id='episode-container']/div/ul/li/a']")) { String href = element.getAttributeValue("href"); String episodeUri = HuluFeed.canonicaliseEpisodeUri(href); if (episodeUri == null) { continue; } Episode episode = new Episode(episodeUri, PerPublisherCurieExpander.CurieAlgorithm.HULU.compact(episodeUri), Publisher.HULU); brand.addItem(episode); } return brand; } catch (JaxenException e) { throw new FetchException("Unable to navigate HTML document", e); } }
diff --git a/beam-processing/src/main/java/org/esa/beam/framework/processor/ui/PropertyFileParameterPage.java b/beam-processing/src/main/java/org/esa/beam/framework/processor/ui/PropertyFileParameterPage.java index 8002b6dad..21032d961 100644 --- a/beam-processing/src/main/java/org/esa/beam/framework/processor/ui/PropertyFileParameterPage.java +++ b/beam-processing/src/main/java/org/esa/beam/framework/processor/ui/PropertyFileParameterPage.java @@ -1,439 +1,440 @@ package org.esa.beam.framework.processor.ui; import org.esa.beam.framework.param.ParamChangeEvent; import org.esa.beam.framework.param.ParamChangeListener; import org.esa.beam.framework.param.ParamGroup; import org.esa.beam.framework.param.ParamProperties; import org.esa.beam.framework.param.Parameter; import org.esa.beam.framework.processor.DefaultRequestElementFactory; import org.esa.beam.framework.processor.Processor; import org.esa.beam.framework.processor.ProcessorException; import org.esa.beam.framework.processor.Request; import org.esa.beam.framework.processor.RequestValidator; import org.esa.beam.framework.ui.GridBagUtils; import org.esa.beam.framework.ui.UIUtils; import org.esa.beam.framework.ui.tool.ToolButtonFactory; import org.esa.beam.util.Debug; import org.esa.beam.util.io.BeamFileFilter; import javax.swing.AbstractButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.text.BadLocationException; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** * This parameter page creates an UI for editing a property file. * This page is intended to be used with the {@link MultiPageProcessorUI}. * * @author Marco Peters * @author Ralf Quast * @author Norman Fomferra */ public class PropertyFileParameterPage extends ParameterPage { /** * Name of the parameter which holds the path to the property file. */ public static final String PROPERTY_FILE_PARAM_NAME = "property_file"; /** * The default title of this page. */ public static final String DEFAULT_PAGE_TITLE = "Processing Parameters"; private final String defaultPropertyText; private final File defaultPropertyFile; private String storedPropertyText; private JTextArea textArea; private AbstractButton saveButton; private AbstractButton restoreDefaultsButton; /** * Creates a parameter page for editing a property file. * The constructor creates a {@link ParamGroup paramGroup} which contains a parameter with the name * {@link PropertyFileParameterPage#PROPERTY_FILE_PARAM_NAME} of type <code>java.io.File</code>. * This given file is used as the default parameter file. * * @param propertyFile the property file * * @see org.esa.beam.framework.processor.ProcessorConstants */ public PropertyFileParameterPage(final File propertyFile) { this(createDefaultParamGroup(propertyFile)); } /** * Creates a parameter page for editing a property file. * The {@link ParamGroup paramGroup} must contain a parameter with the name * {@link PropertyFileParameterPage#PROPERTY_FILE_PARAM_NAME} of type <code>java.io.File</code>. * The given file by this parameter is used as the default parameter file. * * @param paramGroup the paramGroup to create the UI from * * @see org.esa.beam.framework.processor.ProcessorConstants */ public PropertyFileParameterPage(final ParamGroup paramGroup) { super(paramGroup); setTitle(DEFAULT_PAGE_TITLE); defaultPropertyFile = getCurrentPropertyFile(); defaultPropertyText = getPropertyFileText(defaultPropertyFile); } /** * Sets the parameter values by these given with the {@link Request request}. * * @param request the request to obtain the parameters * * @throws ProcessorException if an error occured */ @Override public void setUIFromRequest(final Request request) throws ProcessorException { setPropertyFileParameter(request); } /** * Fills the given {@link Request request} with parameters. * * @param request the request to fill * * @throws ProcessorException if an error occured */ @Override public void initRequestFromUI(final Request request) throws ProcessorException { request.addParameter(getParamGroup().getParameter(PROPERTY_FILE_PARAM_NAME)); } /** * Sets the processor app for the UI */ @Override public void setApp(final ProcessorApp app) { super.setApp(app); final ParamGroup paramGroup = getParamGroup(); if (paramGroup != null) { app.markParentDirChanges(paramGroup.getParameter(PROPERTY_FILE_PARAM_NAME), "property_file_dir"); } app.addRequestValidator(new RequestValidator() { public boolean validateRequest(final Processor processor, final Request request) { if (!storedPropertyText.equals(textArea.getText())) { // here is parameter OK, not to confuse the user app.showInfoDialog("Parameter file is modified.\n" + "Unable to start processing.\n" + "\n" + "Please save the parameter file first.", null); return false; } return true; } }); } /** * It creates the UI by using the {@link ParamGroup parameter group} of this page. * <p/> * <p>It's only called once by the {@link MultiPageProcessorUI} during lifetime of an * instance of this class.</p> * * @return the UI component displayed as page of the {@link MultiPageProcessorUI}. */ @Override public JComponent createUI() { textArea = new JTextArea(); final JScrollPane textPane = new JScrollPane(textArea); textPane.setPreferredSize(new Dimension(400, 300)); final JPanel panel = GridBagUtils.createDefaultEmptyBorderPanel(); final GridBagConstraints gbc = GridBagUtils.createConstraints(null); gbc.gridy = 0; gbc.weightx = 1; gbc.anchor = GridBagConstraints.NORTHWEST; // property file chooser final Parameter param = getParamGroup().getParameter(PROPERTY_FILE_PARAM_NAME); param.addParamChangeListener(createPropertyFileChooserListener()); gbc.gridy++; gbc.gridwidth = 3; panel.add(param.getEditor().getLabelComponent(), gbc); saveButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Save16.gif"), false); saveButton.setEnabled(false); saveButton.setToolTipText("Saves the edited parameters"); saveButton.addActionListener(createSaveButtonListener()); restoreDefaultsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Undo16.gif"), false); restoreDefaultsButton.setEnabled(false); restoreDefaultsButton.setToolTipText("Restores the processor default parameters"); restoreDefaultsButton.addActionListener(createRestoreDefaultsButtonListener()); gbc.gridy++; gbc.gridwidth = 1; gbc.weightx = 0; panel.add(saveButton, gbc); panel.add(restoreDefaultsButton, gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; panel.add(param.getEditor().getComponent(), gbc); // property file editor gbc.gridy++; gbc.gridwidth = 3; + gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; gbc.insets.top = 5; panel.add(textPane, gbc); textArea.addKeyListener(createPropertyFileEditorKeyListener()); // init text area loadPropertyFile(); return panel; } private static ParamGroup createDefaultParamGroup(final File propertyFile) { final int fileSelectionMode = ParamProperties.FSM_FILES_ONLY; final DefaultRequestElementFactory factory = DefaultRequestElementFactory.getInstance(); final ParamProperties paramProps = factory.createFileParamProperties(fileSelectionMode, propertyFile); // here is parameter OK, not to confuse the user paramProps.setLabel("Processing parameters file"); /*I18N*/ final BeamFileFilter prpFileFilter = new BeamFileFilter("PROPERTIES", ".properties", "Property Files"); final BeamFileFilter txtFileFilter = new BeamFileFilter("TXT", ".txt", "Text Files"); paramProps.setChoosableFileFilters(new BeamFileFilter[]{ txtFileFilter, prpFileFilter }); paramProps.setCurrentFileFilter(txtFileFilter); final Parameter parameter = new Parameter(PROPERTY_FILE_PARAM_NAME, paramProps); parameter.setDefaultValue(); final ParamGroup paramGroup = new ParamGroup(); paramGroup.addParameter(parameter); return paramGroup; } private ParamChangeListener createPropertyFileChooserListener() { return new ParamChangeListener() { public void parameterValueChanged(final ParamChangeEvent event) { loadPropertyFile(); } }; } private void loadPropertyFile() { final boolean successLoading = readPropertyFile(); if (successLoading) { saveButton.setEnabled(false); restoreDefaultsButton.setEnabled(!getCurrentPropertyFile().equals(defaultPropertyFile)); } } private boolean readPropertyFile() { final File propertyFile = getCurrentPropertyFile(); if (propertyFile == null || !propertyFile.isFile()) { return false; } try { final FileReader in = new FileReader(propertyFile); try { textArea.read(in, getCurrentPropertyFile()); storedPropertyText = textArea.getText(); } finally { in.close(); } return true; } catch (IOException e) { Debug.trace(e); final ProcessorApp app = getApp(); if (app != null) { app.showWarningDialog("I/O Error", "Unable to read property file '" + propertyFile.getName() + "'." + "\n\n" + e.getMessage()); } return false; } } private File getCurrentPropertyFile() { return (File) getParamGroup().getParameter(PROPERTY_FILE_PARAM_NAME).getValue(); } private KeyListener createPropertyFileEditorKeyListener() { return new KeyAdapter() { @Override public void keyTyped(final KeyEvent e) { saveButton.setEnabled(true); restoreDefaultsButton.setEnabled(!textArea.getText().equals(defaultPropertyText)); } }; } private ActionListener createSaveButtonListener() { return new ActionListener() { public void actionPerformed(final ActionEvent event) { savePropertyFile(); } }; } private ActionListener createRestoreDefaultsButtonListener() { return new ActionListener() { public void actionPerformed(final ActionEvent event) { final int answer = JOptionPane.showConfirmDialog((Component) event.getSource(), "Do you really want to reload the default parameters file?\n" + "All current settings will be lost."); if (answer == JOptionPane.YES_OPTION) { setPropertyFileParameter(defaultPropertyFile); restoreDefaultsButton.setEnabled(false); } } }; } private void savePropertyFile() { final File propertyFile = getDestinationFile(); if (propertyFile == null) { return; } final PrintWriter pw = createPrintWriter(propertyFile); if (pw != null) { try { writePropertyFile(pw); } finally { pw.close(); } getParamGroup().getParameter(PROPERTY_FILE_PARAM_NAME).setValue(propertyFile, null); saveButton.setEnabled(false); storedPropertyText = textArea.getText(); } } private File getDestinationFile() { File propertyFile = getCurrentPropertyFile(); final ProcessorApp app = getApp(); if (app != null) { while (propertyFile.equals(defaultPropertyFile) || !app.promptForOverwrite(propertyFile)) { if (propertyFile.equals(defaultPropertyFile)) { final String msgText = "It is not allowed to overwrite the default parameters file.\n" + "Please choose a different file name."; if (getApp() != null) { getApp().showWarningDialog(getTitle(), msgText); } else { JOptionPane.showMessageDialog(null, msgText, getTitle(), JOptionPane.WARNING_MESSAGE); } } final JFileChooser chooser = new JFileChooser(propertyFile.getParentFile()); chooser.setSelectedFile(propertyFile); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(app.getMainFrame())) { propertyFile = chooser.getSelectedFile(); } else { return null; } } } return propertyFile; } private PrintWriter createPrintWriter(final File file) { try { return new PrintWriter(new FileWriter(file)); } catch (IOException e) { Debug.trace(e); final ProcessorApp app = getApp(); if (app != null) { app.showWarningDialog("I/O Error", "Unable to write '" + file.getName() + "'." + "\n\n" + e.getMessage()); } return null; } } private void writePropertyFile(final PrintWriter out) { for (int lineNumber = 0; lineNumber < textArea.getLineCount(); lineNumber++) { try { final int start = textArea.getLineStartOffset(lineNumber); final int len = textArea.getLineEndOffset(lineNumber) - start; final String line = textArea.getText(start, len); final String lineWithoutCRorLF = line.replaceAll("[\\n\\r]", ""); out.println(lineWithoutCRorLF); } catch (BadLocationException e) { Debug.trace(e); // should never come here } } } private String getPropertyFileText(File propertyFile) { final StringBuffer sb = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(propertyFile)); String line; while ((line = reader.readLine()) != null) { sb.append(line); sb.append(System.getProperty("line.separator", "\n")); } } catch (IOException e) { Debug.trace(e); final String msgText = "Not able to load parameters from file: \n" + e.getMessage(); if (getApp() != null) { getApp().showErrorDialog(getTitle(), msgText); } else { JOptionPane.showMessageDialog(null, msgText, getTitle(), JOptionPane.WARNING_MESSAGE); } sb.setLength(0); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { Debug.trace(e); // ignore } } } return sb.toString(); } private void setPropertyFileParameter(final Request request) { final Parameter parameter = request.getParameter(PROPERTY_FILE_PARAM_NAME); final File file; if (parameter != null) { file = new File(parameter.getValueAsText()); setPropertyFileParameter(file); } } private void setPropertyFileParameter(final File propertyFile) { if (propertyFile != null) { getParamGroup().getParameter(PROPERTY_FILE_PARAM_NAME).setValue(propertyFile, null); boolean success = readPropertyFile(); if (success) { saveButton.setEnabled(false); restoreDefaultsButton.setEnabled(!getCurrentPropertyFile().equals(defaultPropertyFile)); } } } }
true
true
public JComponent createUI() { textArea = new JTextArea(); final JScrollPane textPane = new JScrollPane(textArea); textPane.setPreferredSize(new Dimension(400, 300)); final JPanel panel = GridBagUtils.createDefaultEmptyBorderPanel(); final GridBagConstraints gbc = GridBagUtils.createConstraints(null); gbc.gridy = 0; gbc.weightx = 1; gbc.anchor = GridBagConstraints.NORTHWEST; // property file chooser final Parameter param = getParamGroup().getParameter(PROPERTY_FILE_PARAM_NAME); param.addParamChangeListener(createPropertyFileChooserListener()); gbc.gridy++; gbc.gridwidth = 3; panel.add(param.getEditor().getLabelComponent(), gbc); saveButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Save16.gif"), false); saveButton.setEnabled(false); saveButton.setToolTipText("Saves the edited parameters"); saveButton.addActionListener(createSaveButtonListener()); restoreDefaultsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Undo16.gif"), false); restoreDefaultsButton.setEnabled(false); restoreDefaultsButton.setToolTipText("Restores the processor default parameters"); restoreDefaultsButton.addActionListener(createRestoreDefaultsButtonListener()); gbc.gridy++; gbc.gridwidth = 1; gbc.weightx = 0; panel.add(saveButton, gbc); panel.add(restoreDefaultsButton, gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; panel.add(param.getEditor().getComponent(), gbc); // property file editor gbc.gridy++; gbc.gridwidth = 3; gbc.fill = GridBagConstraints.BOTH; gbc.insets.top = 5; panel.add(textPane, gbc); textArea.addKeyListener(createPropertyFileEditorKeyListener()); // init text area loadPropertyFile(); return panel; }
public JComponent createUI() { textArea = new JTextArea(); final JScrollPane textPane = new JScrollPane(textArea); textPane.setPreferredSize(new Dimension(400, 300)); final JPanel panel = GridBagUtils.createDefaultEmptyBorderPanel(); final GridBagConstraints gbc = GridBagUtils.createConstraints(null); gbc.gridy = 0; gbc.weightx = 1; gbc.anchor = GridBagConstraints.NORTHWEST; // property file chooser final Parameter param = getParamGroup().getParameter(PROPERTY_FILE_PARAM_NAME); param.addParamChangeListener(createPropertyFileChooserListener()); gbc.gridy++; gbc.gridwidth = 3; panel.add(param.getEditor().getLabelComponent(), gbc); saveButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Save16.gif"), false); saveButton.setEnabled(false); saveButton.setToolTipText("Saves the edited parameters"); saveButton.addActionListener(createSaveButtonListener()); restoreDefaultsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Undo16.gif"), false); restoreDefaultsButton.setEnabled(false); restoreDefaultsButton.setToolTipText("Restores the processor default parameters"); restoreDefaultsButton.addActionListener(createRestoreDefaultsButtonListener()); gbc.gridy++; gbc.gridwidth = 1; gbc.weightx = 0; panel.add(saveButton, gbc); panel.add(restoreDefaultsButton, gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; panel.add(param.getEditor().getComponent(), gbc); // property file editor gbc.gridy++; gbc.gridwidth = 3; gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; gbc.insets.top = 5; panel.add(textPane, gbc); textArea.addKeyListener(createPropertyFileEditorKeyListener()); // init text area loadPropertyFile(); return panel; }
diff --git a/OpenKitSDK/src/io/openkit/OKLoginFragment.java b/OpenKitSDK/src/io/openkit/OKLoginFragment.java index 00263b1..8664413 100644 --- a/OpenKitSDK/src/io/openkit/OKLoginFragment.java +++ b/OpenKitSDK/src/io/openkit/OKLoginFragment.java @@ -1,543 +1,549 @@ /** * Copyright 2012 OpenKit * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.openkit; import com.google.android.gms.auth.GooglePlayServicesAvailabilityException; import io.openkit.facebookutils.*; import io.openkit.facebookutils.FacebookUtilities.CreateOKUserRequestHandler; import io.openkit.facebook.*; import io.openkit.user.*; import android.support.v4.app.DialogFragment; import android.accounts.Account; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class OKLoginFragment extends DialogFragment { private static String loginText; private static int loginTextResourceID; private Button fbLoginButton, googleLoginButton, twitterLoginButton,guestLoginButton, dontLoginButton; private ProgressBar spinner; private TextView loginTextView; private boolean fbLoginButtonClicked = false; private static boolean fbLoginEnabled = true; private static boolean googleLoginEnabled = true; private static boolean twitterLoginEnabled = false; private static boolean guestLoginEnabled = false; private boolean isShowingSpinner = false; private OKLoginFragmentDelegate dialogDelegate; private GoogleAuthRequest mGoogAuthRequest; public static void setFbLoginEnabled(boolean enabled) { fbLoginEnabled = enabled; } public static void setGoogleLoginEnabled(boolean enabled) { googleLoginEnabled = enabled; } public static void setLoginText(String text){ loginText = text; } public static void setLoginTextResourceID(int id){ loginTextResourceID = id; } public void setDelegate(OKLoginFragmentDelegate delegate) { dialogDelegate = delegate; } @Override public void onCreate(Bundle savedInstanceState) { setRetainInstance(true); super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NO_TITLE, 0); setCancelable(false); } @Override public void onDestroyView() { if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().setTitle("Login"); int viewID, fbLoginButtonId, dontLoginButtonId, spinnerId, loginTextViewID, googleLoginButtonID, twitterLoginButtonID, guestLoginButtonID; viewID = getResources().getIdentifier("io_openkit_fragment_logindialog", "layout", getActivity().getPackageName()); fbLoginButtonId = getResources().getIdentifier("io_openkit_fbSignInButton", "id", getActivity().getPackageName()); dontLoginButtonId = getResources().getIdentifier("io_openkit_dontSignInButton", "id", getActivity().getPackageName()); spinnerId = getResources().getIdentifier("io_openkit_spinner", "id", getActivity().getPackageName()); loginTextViewID = getResources().getIdentifier("io_openkit_loginTitleTextView", "id", getActivity().getPackageName()); googleLoginButtonID = getResources().getIdentifier("io_openkit_googleSignInButton", "id", getActivity().getPackageName()); twitterLoginButtonID = getResources().getIdentifier("io_openkit_twitterSignInButton", "id", getActivity().getPackageName()); guestLoginButtonID = getResources().getIdentifier("io_openkit_guestSignInButton", "id", getActivity().getPackageName()); View view = inflater.inflate(viewID, container, false); fbLoginButton = (Button)view.findViewById(fbLoginButtonId); dontLoginButton = (Button)view.findViewById(dontLoginButtonId); spinner = (ProgressBar)view.findViewById(spinnerId); loginTextView = (TextView)view.findViewById(loginTextViewID); googleLoginButton = (Button)view.findViewById(googleLoginButtonID); twitterLoginButton = (Button)view.findViewById(twitterLoginButtonID); guestLoginButton = (Button)view.findViewById(guestLoginButtonID); //Show customizable string if set if(loginText != null) { loginTextView.setText(loginText); } else if (loginTextResourceID != 0) { loginTextView.setText(loginTextResourceID); } //Only show the correct buttons fbLoginButton.setVisibility(getButtonLayoutVisibility(fbLoginEnabled, fbLoginButton)); googleLoginButton.setVisibility(getButtonLayoutVisibility(googleLoginEnabled, googleLoginButton)); guestLoginButton.setVisibility(getButtonLayoutVisibility(guestLoginEnabled, guestLoginButton)); twitterLoginButton.setVisibility(getButtonLayoutVisibility(twitterLoginEnabled, twitterLoginButton)); if(isShowingSpinner){ showSpinner(); } fbLoginButton.setOnClickListener(fbLoginButtonClick); googleLoginButton.setOnClickListener(googleLoginButtonClick); dontLoginButton.setOnClickListener(dismissSignInClick); Session session = Session.getActiveSession(); if (session == null) { if (savedInstanceState != null) { session = Session.restoreSession(getActivity(), null, sessionStatusCallback, savedInstanceState); } if (session == null) { session = new Session(getActivity()); } Session.setActiveSession(session); if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) { session.openForRead(new Session.OpenRequest(this).setCallback(sessionStatusCallback)); } } return view; } private View.OnClickListener googleLoginButtonClick = new View.OnClickListener() { @Override public void onClick(View arg0) { //Check to see if there are any Google accounts defined Account[] googAccounts = GoogleUtils.getGoogleAccounts(OKLoginFragment.this.getActivity()); if(googAccounts.length == 0) { showLoginErrorMessageFromStringIdentifierName("io_openkit_googleNoAccts"); } else if(googAccounts.length == 1) { performGoogleAuth(googAccounts[0]); } else { //There are multiple accounts, show a selector to choose which Account to perform Auth on AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Choose an Account"); builder.setItems(GoogleUtils.getGoogleAccountNames(OKLoginFragment.this.getActivity()), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Account account = GoogleUtils.getGoogleAccounts(OKLoginFragment.this.getActivity())[which]; performGoogleAuth(account); } }); builder.create().show(); } } }; private void performGoogleAuth(Account account) { mGoogAuthRequest = new GoogleAuthRequest(OKLoginFragment.this,account); showSpinner(); mGoogAuthRequest.loginWithGoogleAccount(new GoogleAuthRequestHandler() { @Override public void onUserCancelled() { hideSpinner(); dialogDelegate.onLoginCancelled(); } @Override public void onReceivedAuthToken(final String authToken) { // Create the user from the UI thread because onReceivedAuthToken is called from a background thread // and all OK network requests are performed on a background thread anyways OKLoginFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { GoogleUtils.createOKUserFromGoogle(OKLoginFragment.this.getActivity(), authToken, new CreateOKUserRequestHandler() { @Override public void onSuccess(OKUser user) { OKLog.v("Correct callback is called"); hideSpinner(); OKLog.v("Created OKUser successfully!"); OpenKitSingleton.INSTANCE.handlerUserLoggedIn(user, OKLoginFragment.this.getActivity()); dialogDelegate.onLoginSucceeded(); } @Override public void onFail(Error error) { hideSpinner(); int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_OKLoginError", "string", OKLoginFragment.this.getActivity().getPackageName()); String message = OKLoginFragment.this.getString(errorMessageId); showLoginErrorMessage(message); } }); } }); } @Override public void onLoginFailedWithPlayException( final GooglePlayServicesAvailabilityException playEx) { //Need to run this on UIthread becuase this may be called from a background thread and this shows an error dialog OKLoginFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { hideSpinner(); int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_googlePlayServicesError", "string", OKLoginFragment.this.getActivity().getPackageName()); String message = OKLoginFragment.this.getString(errorMessageId); showLoginErrorMessage(message); //Can't use helper method below to show error message because we don't include the resources from Google play services SDK //GoogleUtils.showGooglePlayServicesErrorDialog(OKLoginFragment.this.getActivity(), playEx.getConnectionStatusCode()); } }); } @Override - public void onLoginFailed(Exception e) { - hideSpinner(); - int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_googleLoginError", "string", OKLoginFragment.this.getActivity().getPackageName()); - String message = OKLoginFragment.this.getString(errorMessageId); - showLoginErrorMessage(message); + public void onLoginFailed(final Exception e) { + OKLoginFragment.this.getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + OKLog.d("Google auth login failed with exception: " + e); + hideSpinner(); + int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_googleLoginError", "string", OKLoginFragment.this.getActivity().getPackageName()); + String message = OKLoginFragment.this.getString(errorMessageId); + showLoginErrorMessage(message); + } + }); } }); } private View.OnClickListener fbLoginButtonClick = new View.OnClickListener() { @Override public void onClick(View v) { OKLog.v("Pressed FB login button"); fbLoginButtonClicked = true; loginToFB(); } }; private View.OnClickListener dismissSignInClick = new View.OnClickListener() { @Override public void onClick(View v) { dialogDelegate.onLoginCancelled(); } }; private int getButtonLayoutVisibility(boolean enabled, Button button) { if(enabled) { return button.getVisibility(); } else { return View.GONE; } } // If the button is Visible, set it to Invisible (e.g. do not set View.Gone to View.Invisible) private void setButtonInvisibleIfNotGone(Button button) { if(button.getVisibility() == View.VISIBLE) { button.setVisibility(View.INVISIBLE); } } // If the button is Invisible, set it it Visible (e.g. do not set View.gone to View.Visible) private void setButtonVisibleIfNotGone(Button button) { if(button.getVisibility() == View.INVISIBLE) { button.setVisibility(View.INVISIBLE); } } private void showSpinner() { isShowingSpinner = true; spinner.setVisibility(View.VISIBLE); setButtonInvisibleIfNotGone(fbLoginButton); setButtonInvisibleIfNotGone(twitterLoginButton); setButtonInvisibleIfNotGone(googleLoginButton); setButtonInvisibleIfNotGone(guestLoginButton); setButtonInvisibleIfNotGone(dontLoginButton); } private void hideSpinner() { isShowingSpinner = false; spinner.setVisibility(View.INVISIBLE); setButtonVisibleIfNotGone(fbLoginButton); setButtonVisibleIfNotGone(twitterLoginButton); setButtonVisibleIfNotGone(googleLoginButton); setButtonVisibleIfNotGone(guestLoginButton); setButtonVisibleIfNotGone(dontLoginButton); } /** * Starts the Facebook authentication process. Performs Facebook authentication using the best method available * (native Android dialog, single sign on through Facebook application, or using a web view shown inside the app) */ private void loginToFB() { showSpinner(); Session session = Session.getActiveSession(); if(!session.isOpened() && !session.isClosed()){ session.openForRead(new Session.OpenRequest(this) //.setPermissions(Arrays.asList("basic_info")) .setCallback(sessionStatusCallback)); } else if(session.isOpened()) { //Facebook session is already open, just authorize the user with OpenKit authorizeFBUserWithOpenKit(); } else { Session.openActiveSession(getActivity(), this, true, sessionStatusCallback); } } /** * Called after the user is authenticated with Facebook. Uses the the Facebook authentication token to look up * the user's facebook id, then gets the corresponding OKUser to this facebook ID. */ private void authorizeFBUserWithOpenKit() { FacebookUtilities.CreateOKUserFromFacebook(new CreateOKUserRequestHandler() { @Override public void onSuccess(OKUser user) { hideSpinner(); OKLog.v("Created OKUser successfully!"); OpenKitSingleton.INSTANCE.handlerUserLoggedIn(user, OKLoginFragment.this.getActivity()); dialogDelegate.onLoginSucceeded(); } @Override public void onFail(Error error) { hideSpinner(); OKLog.v("Failed to create OKUSER: " + error); showLoginErrorMessage("Sorry, but there was an error reaching the OpenKit server. Please try again later"); } }); } private void showLoginErrorMessageFromStringIdentifierName(String id) { int errorMessageId = OKLoginFragment.this.getResources().getIdentifier(id, "string", OKLoginFragment.this.getActivity().getPackageName()); String message = OKLoginFragment.this.getString(errorMessageId); showLoginErrorMessage(message); } private void showLoginErrorMessage(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(OKLoginFragment.this.getActivity()); builder.setTitle("Error"); builder.setMessage(message); builder.setNegativeButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialogDelegate.onLoginFailed(); } }); builder.setCancelable(false); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } static String keyhashErrorString = "remote_app_id does not match stored id "; /** * Handler function for when Facebook login fails * @param exception Exception from Facebook SDK */ private void facebookLoginFailed(Exception exception) { OKLog.v("Facebook login failed"); if(exception != null && exception.getClass() == io.openkit.facebook.FacebookOperationCanceledException.class) { OKLog.v("User cancelled Facebook login"); //Special check for the keyhash issue, otherwise just dismiss because the user cancelled if(exception.getMessage().equalsIgnoreCase(keyhashErrorString)) { showLoginErrorMessage("There was an error logging in with Facebook. Your Facebook application may not be configured correctly. Make sure you have added the correct Android keyhash(es) to your Facebook application"); return; } else { dialogDelegate.onLoginCancelled(); } } else { showLoginErrorMessage("There was an unknown error while logging into Facebook. Please try again"); } } /* Facebook session state change handler. This method handles all cases of Facebook auth */ private Session.StatusCallback sessionStatusCallback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { // Log all facebook exceptions if(exception != null) { OKLog.v("SessionState changed exception: " + exception + " hash code: " + exception.hashCode()); } //Log what is happening with the Facebook session for debug help switch (state) { case OPENING: OKLog.v("SessionState Opening"); break; case CREATED: OKLog.v("SessionState Created"); break; case OPENED: OKLog.v("SessionState Opened"); break; case CLOSED_LOGIN_FAILED: OKLog.v("SessionState Closed Login Failed"); break; case OPENED_TOKEN_UPDATED: OKLog.v("SessionState Opened Token Updated"); break; case CREATED_TOKEN_LOADED: OKLog.v("SessionState created token loaded" ); break; case CLOSED: OKLog.v("SessionState closed"); break; default: OKLog.v("Session State Default case"); break; } // If the session is opened, authorize the user, if the session is closed if (state.isOpened()) { OKLog.v("FB Session is Open"); if(fbLoginButtonClicked){ OKLog.v("Authorizing user with Facebook"); authorizeFBUserWithOpenKit(); fbLoginButtonClicked = false; } } else if (state.isClosed()) { OKLog.v("FB Session is Closed"); if(fbLoginButtonClicked) { facebookLoginFailed(exception); fbLoginButtonClicked = false; } } } }; /* Below methods are overridden to add the Facebook session lifecycle callbacks */ @Override public void onStart() { super.onStart(); Session.getActiveSession().addCallback(sessionStatusCallback); } @Override public void onStop() { super.onStop(); Session.getActiveSession().removeCallback(sessionStatusCallback); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // Handle activity result for Google auth if (requestCode == GoogleAuthRequest.REQUEST_CODE_RECOVER_FROM_AUTH_ERROR) { if(mGoogAuthRequest != null) { mGoogAuthRequest.handleGoogleAuthorizeResult(resultCode, data); } return; } super.onActivityResult(requestCode, resultCode, data); // Handle activity result for Facebook auth Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Session session = Session.getActiveSession(); Session.saveSession(session, outState); } }
true
true
private void performGoogleAuth(Account account) { mGoogAuthRequest = new GoogleAuthRequest(OKLoginFragment.this,account); showSpinner(); mGoogAuthRequest.loginWithGoogleAccount(new GoogleAuthRequestHandler() { @Override public void onUserCancelled() { hideSpinner(); dialogDelegate.onLoginCancelled(); } @Override public void onReceivedAuthToken(final String authToken) { // Create the user from the UI thread because onReceivedAuthToken is called from a background thread // and all OK network requests are performed on a background thread anyways OKLoginFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { GoogleUtils.createOKUserFromGoogle(OKLoginFragment.this.getActivity(), authToken, new CreateOKUserRequestHandler() { @Override public void onSuccess(OKUser user) { OKLog.v("Correct callback is called"); hideSpinner(); OKLog.v("Created OKUser successfully!"); OpenKitSingleton.INSTANCE.handlerUserLoggedIn(user, OKLoginFragment.this.getActivity()); dialogDelegate.onLoginSucceeded(); } @Override public void onFail(Error error) { hideSpinner(); int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_OKLoginError", "string", OKLoginFragment.this.getActivity().getPackageName()); String message = OKLoginFragment.this.getString(errorMessageId); showLoginErrorMessage(message); } }); } }); } @Override public void onLoginFailedWithPlayException( final GooglePlayServicesAvailabilityException playEx) { //Need to run this on UIthread becuase this may be called from a background thread and this shows an error dialog OKLoginFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { hideSpinner(); int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_googlePlayServicesError", "string", OKLoginFragment.this.getActivity().getPackageName()); String message = OKLoginFragment.this.getString(errorMessageId); showLoginErrorMessage(message); //Can't use helper method below to show error message because we don't include the resources from Google play services SDK //GoogleUtils.showGooglePlayServicesErrorDialog(OKLoginFragment.this.getActivity(), playEx.getConnectionStatusCode()); } }); } @Override public void onLoginFailed(Exception e) { hideSpinner(); int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_googleLoginError", "string", OKLoginFragment.this.getActivity().getPackageName()); String message = OKLoginFragment.this.getString(errorMessageId); showLoginErrorMessage(message); } }); }
private void performGoogleAuth(Account account) { mGoogAuthRequest = new GoogleAuthRequest(OKLoginFragment.this,account); showSpinner(); mGoogAuthRequest.loginWithGoogleAccount(new GoogleAuthRequestHandler() { @Override public void onUserCancelled() { hideSpinner(); dialogDelegate.onLoginCancelled(); } @Override public void onReceivedAuthToken(final String authToken) { // Create the user from the UI thread because onReceivedAuthToken is called from a background thread // and all OK network requests are performed on a background thread anyways OKLoginFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { GoogleUtils.createOKUserFromGoogle(OKLoginFragment.this.getActivity(), authToken, new CreateOKUserRequestHandler() { @Override public void onSuccess(OKUser user) { OKLog.v("Correct callback is called"); hideSpinner(); OKLog.v("Created OKUser successfully!"); OpenKitSingleton.INSTANCE.handlerUserLoggedIn(user, OKLoginFragment.this.getActivity()); dialogDelegate.onLoginSucceeded(); } @Override public void onFail(Error error) { hideSpinner(); int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_OKLoginError", "string", OKLoginFragment.this.getActivity().getPackageName()); String message = OKLoginFragment.this.getString(errorMessageId); showLoginErrorMessage(message); } }); } }); } @Override public void onLoginFailedWithPlayException( final GooglePlayServicesAvailabilityException playEx) { //Need to run this on UIthread becuase this may be called from a background thread and this shows an error dialog OKLoginFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { hideSpinner(); int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_googlePlayServicesError", "string", OKLoginFragment.this.getActivity().getPackageName()); String message = OKLoginFragment.this.getString(errorMessageId); showLoginErrorMessage(message); //Can't use helper method below to show error message because we don't include the resources from Google play services SDK //GoogleUtils.showGooglePlayServicesErrorDialog(OKLoginFragment.this.getActivity(), playEx.getConnectionStatusCode()); } }); } @Override public void onLoginFailed(final Exception e) { OKLoginFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { OKLog.d("Google auth login failed with exception: " + e); hideSpinner(); int errorMessageId = OKLoginFragment.this.getResources().getIdentifier("io_openkit_googleLoginError", "string", OKLoginFragment.this.getActivity().getPackageName()); String message = OKLoginFragment.this.getString(errorMessageId); showLoginErrorMessage(message); } }); } }); }
diff --git a/geotools2/geotools-src/gmldatasource/tests/unit/org/geotools/gml/ProducerTest.java b/geotools2/geotools-src/gmldatasource/tests/unit/org/geotools/gml/ProducerTest.java index 4b47da497..c5163236f 100644 --- a/geotools2/geotools-src/gmldatasource/tests/unit/org/geotools/gml/ProducerTest.java +++ b/geotools2/geotools-src/gmldatasource/tests/unit/org/geotools/gml/ProducerTest.java @@ -1,222 +1,224 @@ /* * Geotools2 - OpenSource mapping toolkit * http://geotools.org * (C) 2002, Geotools Project Managment Committee (PMC) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package org.geotools.gml; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryCollection; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.LinearRing; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.PrecisionModel; import junit.framework.*; /* * ProducerTest.java * JUnit based test * */ import org.geotools.data.*; import org.geotools.data.gml.GMLDataSource; import org.geotools.feature.*; import org.geotools.gml.producer.*; import java.io.OutputStream; import java.net.URL; import java.nio.ByteBuffer; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * DOCUMENT ME! * * @author Chris Holmes, TOPP */ public class ProducerTest extends TestCase { /** The logger for the filter module. */ private static final Logger LOGGER = Logger.getLogger("org.geotools.gml"); static int NTests = 7; private Feature testFeature; private FeatureType schema; private FeatureFactory featureFactory; FeatureCollection table = null; public ProducerTest(java.lang.String testName) { super(testName); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(ProducerTest.class); return suite; } /** * This needs to be redone, for now it is just a demo that will print some * sample features. * * @throws Exception DOCUMENT ME! */ public void testProducer() throws Exception { System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl"); LOGGER.fine("testing producer"); String dataFolder = System.getProperty("dataFolder"); if (dataFolder == null) { //then we are being run by maven dataFolder = System.getProperty("basedir"); dataFolder += "/tests/unit/testData"; } URL url = new URL("file:///" + dataFolder + "/testGML7Features.gml"); LOGGER.fine("Testing to load " + url + " as Feature datasource"); DataSource ds = new GMLDataSource(url); AttributeType[] atts = { AttributeTypeFactory.newAttributeType("geoid", Integer.class), AttributeTypeFactory.newAttributeType("geom", Geometry.class), AttributeTypeFactory.newAttributeType("name", String.class) }; try { schema = FeatureTypeFactory.newFeatureType(atts, "rail", "http://www.openplans.org/data"); } catch (SchemaException e) { LOGGER.finer("problem with creating schema"); } LOGGER.fine("namespace is " + schema.getNamespace()); PrecisionModel precModel = new PrecisionModel(); int srid = 2035; GeometryFactory geomFactory = new GeometryFactory(precModel, srid); Coordinate[] points = { new Coordinate(15, 15), new Coordinate(15, 25), new Coordinate(25, 25), new Coordinate(25, 15), new Coordinate(15, 15) }; LinearRing shell = new LinearRing(points, precModel, srid); Polygon the_geom = new Polygon(shell, precModel, srid); Polygon[] polyArr = { the_geom, the_geom }; MultiPolygon multiPoly = geomFactory.createMultiPolygon(polyArr); Point point = geomFactory.createPoint(new Coordinate(3, 35)); Point[] pointArr = { point, point, point, point }; MultiPoint multiPoint = new MultiPoint(pointArr, precModel, srid); LineString line = new LineString(points, precModel, srid); LineString[] lineArr = { line, line, line }; MultiLineString multiLine = new MultiLineString(lineArr, precModel, srid); Geometry[] geomArr = { multiPoly, point, line, multiLine }; GeometryCollection multiGeom = new GeometryCollection(geomArr, precModel, srid); Integer featureId = new Integer(32); String name = "inse<rt polygon444444"; Object[] attributes = { featureId, point, name }; Feature polygonFeature = null; Feature lineFeature = null; Feature multiLineFeature = null; Feature mPointFeature = null; Feature mPolyFeature = null; Feature mGeomFeature = null; try { testFeature = schema.create(attributes, "rail.1"); attributes[1] = line; lineFeature = schema.create(attributes, "rail.2"); attributes[1] = the_geom; polygonFeature = schema.create(attributes, "rail.3"); attributes[1] = multiLine; multiLineFeature = schema.create(attributes, "rail.4"); attributes[1] = multiPoint; mPointFeature = schema.create(attributes, "rail.5"); attributes[1] = multiPoly; mPolyFeature = schema.create(attributes, "rail.6"); attributes[1] = multiGeom; mGeomFeature = schema.create(attributes, "rail.7"); } catch (IllegalAttributeException ife) { LOGGER.warning("problem in setup " + ife); } //table = ds.getFeatures();//new FeatureCollectionDefault(); table = FeatureCollections.newCollection(); table.add(testFeature); table.add(lineFeature); table.add(polygonFeature); table.add(multiLineFeature); table.add(mPointFeature); table.add(mPolyFeature); table.add(mGeomFeature); LOGGER.fine("the feature collection is " + table + ", and " + "the first feat is " + table.features().next()); FeatureTransformer fr = new FeatureTransformer(); - fr.setPrettyPrint(true); - fr.setDefaultNamespace("http://www.openplans.org/ch"); + //fr.setPrettyPrint(true); + //fr.setDefaultNamespace("http://www.openplans.org/ch"); //increase the capacity if the output gets longer. LogOutputStream out = new LogOutputStream(10000); + fr.setIndentation(2); + fr.getFeatureTypeNamespaces().declareDefaultNamespace("xxx", "http://www.geotools.org"); fr.transform(table, out); - LOGGER.fine("output is " + out.toString()); + LOGGER.info("output is " + out.toString()); } /** * little class to allow one to use an output stream and just call * toString on it. I couldn't find any java class that did this easily, * like a StringWriter. Maybe I just wasn't looking in the right place, * but this seems to work and was easy to implement. But it allows * us to not use System.out for the transform, so the logging level can * be recorded. */ private static class LogOutputStream extends OutputStream { private ByteBuffer bytes; public LogOutputStream(int capacity) { bytes = ByteBuffer.allocate(capacity); } public void write(int b) { bytes.put(new Integer(b).byteValue()); } public void write(byte[] b, int off, int len) { bytes.put(b, off, len); } public void write(byte[] b) { bytes.put(b); } public String toString() { return new String(bytes.array()); } } }
false
true
public void testProducer() throws Exception { System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl"); LOGGER.fine("testing producer"); String dataFolder = System.getProperty("dataFolder"); if (dataFolder == null) { //then we are being run by maven dataFolder = System.getProperty("basedir"); dataFolder += "/tests/unit/testData"; } URL url = new URL("file:///" + dataFolder + "/testGML7Features.gml"); LOGGER.fine("Testing to load " + url + " as Feature datasource"); DataSource ds = new GMLDataSource(url); AttributeType[] atts = { AttributeTypeFactory.newAttributeType("geoid", Integer.class), AttributeTypeFactory.newAttributeType("geom", Geometry.class), AttributeTypeFactory.newAttributeType("name", String.class) }; try { schema = FeatureTypeFactory.newFeatureType(atts, "rail", "http://www.openplans.org/data"); } catch (SchemaException e) { LOGGER.finer("problem with creating schema"); } LOGGER.fine("namespace is " + schema.getNamespace()); PrecisionModel precModel = new PrecisionModel(); int srid = 2035; GeometryFactory geomFactory = new GeometryFactory(precModel, srid); Coordinate[] points = { new Coordinate(15, 15), new Coordinate(15, 25), new Coordinate(25, 25), new Coordinate(25, 15), new Coordinate(15, 15) }; LinearRing shell = new LinearRing(points, precModel, srid); Polygon the_geom = new Polygon(shell, precModel, srid); Polygon[] polyArr = { the_geom, the_geom }; MultiPolygon multiPoly = geomFactory.createMultiPolygon(polyArr); Point point = geomFactory.createPoint(new Coordinate(3, 35)); Point[] pointArr = { point, point, point, point }; MultiPoint multiPoint = new MultiPoint(pointArr, precModel, srid); LineString line = new LineString(points, precModel, srid); LineString[] lineArr = { line, line, line }; MultiLineString multiLine = new MultiLineString(lineArr, precModel, srid); Geometry[] geomArr = { multiPoly, point, line, multiLine }; GeometryCollection multiGeom = new GeometryCollection(geomArr, precModel, srid); Integer featureId = new Integer(32); String name = "inse<rt polygon444444"; Object[] attributes = { featureId, point, name }; Feature polygonFeature = null; Feature lineFeature = null; Feature multiLineFeature = null; Feature mPointFeature = null; Feature mPolyFeature = null; Feature mGeomFeature = null; try { testFeature = schema.create(attributes, "rail.1"); attributes[1] = line; lineFeature = schema.create(attributes, "rail.2"); attributes[1] = the_geom; polygonFeature = schema.create(attributes, "rail.3"); attributes[1] = multiLine; multiLineFeature = schema.create(attributes, "rail.4"); attributes[1] = multiPoint; mPointFeature = schema.create(attributes, "rail.5"); attributes[1] = multiPoly; mPolyFeature = schema.create(attributes, "rail.6"); attributes[1] = multiGeom; mGeomFeature = schema.create(attributes, "rail.7"); } catch (IllegalAttributeException ife) { LOGGER.warning("problem in setup " + ife); } //table = ds.getFeatures();//new FeatureCollectionDefault(); table = FeatureCollections.newCollection(); table.add(testFeature); table.add(lineFeature); table.add(polygonFeature); table.add(multiLineFeature); table.add(mPointFeature); table.add(mPolyFeature); table.add(mGeomFeature); LOGGER.fine("the feature collection is " + table + ", and " + "the first feat is " + table.features().next()); FeatureTransformer fr = new FeatureTransformer(); fr.setPrettyPrint(true); fr.setDefaultNamespace("http://www.openplans.org/ch"); //increase the capacity if the output gets longer. LogOutputStream out = new LogOutputStream(10000); fr.transform(table, out); LOGGER.fine("output is " + out.toString()); }
public void testProducer() throws Exception { System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl"); LOGGER.fine("testing producer"); String dataFolder = System.getProperty("dataFolder"); if (dataFolder == null) { //then we are being run by maven dataFolder = System.getProperty("basedir"); dataFolder += "/tests/unit/testData"; } URL url = new URL("file:///" + dataFolder + "/testGML7Features.gml"); LOGGER.fine("Testing to load " + url + " as Feature datasource"); DataSource ds = new GMLDataSource(url); AttributeType[] atts = { AttributeTypeFactory.newAttributeType("geoid", Integer.class), AttributeTypeFactory.newAttributeType("geom", Geometry.class), AttributeTypeFactory.newAttributeType("name", String.class) }; try { schema = FeatureTypeFactory.newFeatureType(atts, "rail", "http://www.openplans.org/data"); } catch (SchemaException e) { LOGGER.finer("problem with creating schema"); } LOGGER.fine("namespace is " + schema.getNamespace()); PrecisionModel precModel = new PrecisionModel(); int srid = 2035; GeometryFactory geomFactory = new GeometryFactory(precModel, srid); Coordinate[] points = { new Coordinate(15, 15), new Coordinate(15, 25), new Coordinate(25, 25), new Coordinate(25, 15), new Coordinate(15, 15) }; LinearRing shell = new LinearRing(points, precModel, srid); Polygon the_geom = new Polygon(shell, precModel, srid); Polygon[] polyArr = { the_geom, the_geom }; MultiPolygon multiPoly = geomFactory.createMultiPolygon(polyArr); Point point = geomFactory.createPoint(new Coordinate(3, 35)); Point[] pointArr = { point, point, point, point }; MultiPoint multiPoint = new MultiPoint(pointArr, precModel, srid); LineString line = new LineString(points, precModel, srid); LineString[] lineArr = { line, line, line }; MultiLineString multiLine = new MultiLineString(lineArr, precModel, srid); Geometry[] geomArr = { multiPoly, point, line, multiLine }; GeometryCollection multiGeom = new GeometryCollection(geomArr, precModel, srid); Integer featureId = new Integer(32); String name = "inse<rt polygon444444"; Object[] attributes = { featureId, point, name }; Feature polygonFeature = null; Feature lineFeature = null; Feature multiLineFeature = null; Feature mPointFeature = null; Feature mPolyFeature = null; Feature mGeomFeature = null; try { testFeature = schema.create(attributes, "rail.1"); attributes[1] = line; lineFeature = schema.create(attributes, "rail.2"); attributes[1] = the_geom; polygonFeature = schema.create(attributes, "rail.3"); attributes[1] = multiLine; multiLineFeature = schema.create(attributes, "rail.4"); attributes[1] = multiPoint; mPointFeature = schema.create(attributes, "rail.5"); attributes[1] = multiPoly; mPolyFeature = schema.create(attributes, "rail.6"); attributes[1] = multiGeom; mGeomFeature = schema.create(attributes, "rail.7"); } catch (IllegalAttributeException ife) { LOGGER.warning("problem in setup " + ife); } //table = ds.getFeatures();//new FeatureCollectionDefault(); table = FeatureCollections.newCollection(); table.add(testFeature); table.add(lineFeature); table.add(polygonFeature); table.add(multiLineFeature); table.add(mPointFeature); table.add(mPolyFeature); table.add(mGeomFeature); LOGGER.fine("the feature collection is " + table + ", and " + "the first feat is " + table.features().next()); FeatureTransformer fr = new FeatureTransformer(); //fr.setPrettyPrint(true); //fr.setDefaultNamespace("http://www.openplans.org/ch"); //increase the capacity if the output gets longer. LogOutputStream out = new LogOutputStream(10000); fr.setIndentation(2); fr.getFeatureTypeNamespaces().declareDefaultNamespace("xxx", "http://www.geotools.org"); fr.transform(table, out); LOGGER.info("output is " + out.toString()); }
diff --git a/src/client/MapleClient.java b/src/client/MapleClient.java index 686d75d7..e51eb484 100644 --- a/src/client/MapleClient.java +++ b/src/client/MapleClient.java @@ -1,991 +1,991 @@ /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <[email protected]> Matthias Butz <[email protected]> Jan Christian Meyer <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package client; import gm.server.GMServer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ScheduledFuture; import javax.script.ScriptEngine; import net.MaplePacket; import tools.DatabaseConnection; import net.server.Channel; import net.server.Output; import net.server.Server; import net.server.MapleMessengerCharacter; import net.server.MaplePartyCharacter; import net.server.PartyOperation; import net.server.World; import net.server.guild.MapleGuildCharacter; import scripting.npc.NPCConversationManager; import scripting.npc.NPCScriptManager; import scripting.quest.QuestActionManager; import scripting.quest.QuestScriptManager; import server.MapleTrade; import server.TimerManager; import server.maps.HiredMerchant; import tools.HashCreator; import tools.MapleAESOFB; import tools.MaplePacketCreator; import tools.HexTool; import org.apache.mina.core.session.IoSession; import server.MapleMiniGame; import server.quest.MapleQuest; import tools.PrintError; public class MapleClient { public static final int LOGIN_NOTLOGGEDIN = 0; public static final int LOGIN_SERVER_TRANSITION = 1; public static final int LOGIN_LOGGEDIN = 2; public static final String CLIENT_KEY = "CLIENT"; private MapleAESOFB send; private MapleAESOFB receive; private IoSession session; private MapleCharacter player; private byte channel = 1; private int accId = 1; private boolean loggedIn = false; private boolean serverTransition = false; private Calendar birthday = null; private String accountName = null; private byte world; private long lastPong; private int gmlevel; private Set<String> macs = new HashSet<String>(); private Map<String, ScriptEngine> engines = new HashMap<String, ScriptEngine>(); private ScheduledFuture<?> idleTask = null; private byte characterSlots = 3; private byte loginattempt = 0; private String pin = null; private int pinattempt = 0; private String pic = null; private int picattempt = 0; private byte gender = -1; public MapleClient(MapleAESOFB send, MapleAESOFB receive, IoSession session) { this.send = send; this.receive = receive; this.session = session; } public synchronized MapleAESOFB getReceiveCrypto() { return receive; } public synchronized MapleAESOFB getSendCrypto() { return send; } public synchronized IoSession getSession() { return session; } public MapleCharacter getPlayer() { return player; } public void setPlayer(MapleCharacter player) { this.player = player; } public void sendCharList(int server) { this.session.write(MaplePacketCreator.getCharList(this, server)); } public List<MapleCharacter> loadCharacters(int serverId) { List<MapleCharacter> chars = new ArrayList<MapleCharacter>(15); try { for (CharNameAndId cni : loadCharactersInternal(serverId)) { chars.add(MapleCharacter.loadCharFromDB(cni.id, this, false)); } } catch (Exception e) { } return chars; } public List<String> loadCharacterNames(int serverId) { List<String> chars = new ArrayList<String>(15); for (CharNameAndId cni : loadCharactersInternal(serverId)) { chars.add(cni.name); } return chars; } private List<CharNameAndId> loadCharactersInternal(int serverId) { PreparedStatement ps; List<CharNameAndId> chars = new ArrayList<CharNameAndId>(15); try { ps = DatabaseConnection.getConnection().prepareStatement("SELECT id, name FROM characters WHERE accountid = ? AND world = ?"); ps.setInt(1, this.getAccID()); ps.setInt(2, serverId); ResultSet rs = ps.executeQuery(); while (rs.next()) { chars.add(new CharNameAndId(rs.getString("name"), rs.getInt("id"))); } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } return chars; } public boolean isLoggedIn() { return loggedIn; } public boolean hasBannedIP() { boolean ret = false; try { PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT COUNT(*) FROM ipbans WHERE ? LIKE CONCAT(ip, '%')"); ps.setString(1, session.getRemoteAddress().toString()); ResultSet rs = ps.executeQuery(); rs.next(); if (rs.getInt(1) > 0) { ret = true; } rs.close(); ps.close(); } catch (SQLException e) { } return ret; } public boolean hasBannedMac() { if (macs.isEmpty()) { return false; } boolean ret = false; int i = 0; try { StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM macbans WHERE mac IN ("); for (i = 0; i < macs.size(); i++) { sql.append("?"); if (i != macs.size() - 1) { sql.append(", "); } } sql.append(")"); PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement(sql.toString()); i = 0; for (String mac : macs) { i++; ps.setString(i, mac); } ResultSet rs = ps.executeQuery(); rs.next(); if (rs.getInt(1) > 0) { ret = true; } rs.close(); ps.close(); } catch (Exception e) { } return ret; } private void loadMacsIfNescessary() throws SQLException { if (macs.isEmpty()) { PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT macs FROM accounts WHERE id = ?"); ps.setInt(1, accId); ResultSet rs = ps.executeQuery(); if (rs.next()) { for (String mac : rs.getString("macs").split(", ")) { if (!mac.equals("")) { macs.add(mac); } } } rs.close(); ps.close(); } } public void banMacs() { Connection con = DatabaseConnection.getConnection(); try { loadMacsIfNescessary(); List<String> filtered = new LinkedList<String>(); PreparedStatement ps = con.prepareStatement("SELECT filter FROM macfilters"); ResultSet rs = ps.executeQuery(); while (rs.next()) { filtered.add(rs.getString("filter")); } rs.close(); ps.close(); ps = con.prepareStatement("INSERT INTO macbans (mac) VALUES (?)"); for (String mac : macs) { boolean matched = false; for (String filter : filtered) { if (mac.matches(filter)) { matched = true; break; } } if (!matched) { ps.setString(1, mac); ps.executeUpdate(); } } ps.close(); } catch (SQLException e) { } } public int finishLogin() { synchronized (MapleClient.class) { if (getLoginState() > LOGIN_NOTLOGGEDIN) { loggedIn = false; return 7; } updateLoginState(LOGIN_LOGGEDIN); } return 0; } public void setPin(String pin) { this.pin = pin; try { PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET pin = ? WHERE id = ?"); ps.setString(1, pin); ps.setInt(2, accId); ps.executeUpdate(); ps.close(); } catch (SQLException e) { } } public String getPin() { return pin; } public boolean checkPin(String other) { pinattempt++; if (pinattempt > 5) { getSession().close(true); } if (pin.equals(other)) { pinattempt = 0; return true; } return false; } public void setPic(String pic) { this.pic = pic; try { PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET pic = ? WHERE id = ?"); ps.setString(1, pic); ps.setInt(2, accId); ps.executeUpdate(); ps.close(); } catch (SQLException e) { } } public String getPic() { return pic; } public boolean checkPic(String other) { picattempt++; if (picattempt > 5) { getSession().close(true); } if (pic.equals(other)) { picattempt = 0; return true; } return false; } public int login(String login, String pwd) { loginattempt++; if (loginattempt > 4) { getSession().close(true); } int loginok = 5; Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("SELECT id, password, salt, gender, banned, gm, pin, pic, characterslots, tos FROM accounts WHERE name = ?"); ps.setString(1, login); rs = ps.executeQuery(); if (rs.next()) { if (rs.getByte("banned") == 1) { return 3; } accId = rs.getInt("id"); gmlevel = rs.getInt("gm"); pin = rs.getString("pin"); pic = rs.getString("pic"); gender = rs.getByte("gender"); characterSlots = rs.getByte("characterslots"); String passhash = rs.getString("password"); String salt = rs.getString("salt"); // we do not unban byte tos = rs.getByte("tos"); ps.close(); rs.close(); if (getLoginState() > LOGIN_NOTLOGGEDIN) { // already loggedin loggedIn = false; loginok = 7; } else if (pwd.equals(passhash) || checkHash(passhash, "SHA-1", pwd) || checkHash(passhash, "SHA-512", pwd + salt)) { if (tos == 0) { loginok = 23; } else { loginok = 0; } } else { loggedIn = false; loginok = 4; } if (loginok == 0) { // We're going to change the hashing algorithm to SHA-512 with salt, so we can be secure! :3 SecureRandom random = new SecureRandom(); byte bytes[] = new byte[32]; // 32 bit salt (results may vary. depends on RNG algorithm) random.nextBytes(bytes); String saltNew = HexTool.toString(bytes); String passhashNew = HashCreator.getHash("SHA-512", pwd + saltNew); ps = con.prepareStatement("UPDATE accounts SET password = ?, salt = ? WHERE id = ?"); ps.setString(1, passhashNew); ps.setString(2, saltNew); ps.setInt(3, accId); - rs = ps.executeQuery(); + ps.executeUpdate(); ps.close(); rs.close(); } ps = con.prepareStatement("INSERT INTO iplog (accountid, ip) VALUES (?, ?)"); ps.setInt(1, accId); ps.setString(2, session.getRemoteAddress().toString()); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { try { if (ps != null && !ps.isClosed()) { ps.close(); } if (rs != null && !rs.isClosed()) { rs.close(); } } catch (SQLException e) { } } if (loginok == 0) { loginattempt = 0; } return loginok; } public Calendar getTempBanCalendar() { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = null; ResultSet rs = null; final Calendar lTempban = Calendar.getInstance(); try { ps = con.prepareStatement("SELECT `tempban` FROM accounts WHERE id = ?"); ps.setInt(1, getAccID()); rs = ps.executeQuery(); long blubb = rs.getLong("tempban"); if (blubb == 0) { // basically if timestamp in db is 0000-00-00 return null; } final Calendar today = Calendar.getInstance(); lTempban.setTimeInMillis(rs.getTimestamp("tempban").getTime()); if (today.getTimeInMillis() < lTempban.getTimeInMillis()) { return lTempban; } return null; } catch (SQLException e) { // idc } finally { try { if (ps != null) { ps.close(); } if (rs != null) { rs.close(); } } catch (SQLException e) { } } return null;// why oh why!?! } public static long dottedQuadToLong(String dottedQuad) throws RuntimeException { String[] quads = dottedQuad.split("\\."); if (quads.length != 4) { throw new RuntimeException("Invalid IP Address format."); } long ipAddress = 0; for (int i = 0; i < 4; i++) { int quad = Integer.parseInt(quads[i]); ipAddress += (long) (quad % 256) * (long) Math.pow(256, (double) (4 - i)); } return ipAddress; } public static String getChannelServerIPFromSubnet(String clientIPAddress, byte channel) { long ipAddress = dottedQuadToLong(clientIPAddress); Properties subnetInfo = Server.getInstance().getSubnetInfo(); if (subnetInfo.contains("net.login.subnetcount")) { int subnetCount = Integer.parseInt(subnetInfo.getProperty("net.login.subnetcount")); for (int i = 0; i < subnetCount; i++) { String[] connectionInfo = subnetInfo.getProperty("net.login.subnet." + i).split(":"); long subnet = dottedQuadToLong(connectionInfo[0]); long channelIP = dottedQuadToLong(connectionInfo[1]); byte channelNumber = Byte.parseByte(connectionInfo[2]); if (((ipAddress & subnet) == (channelIP & subnet)) && (channel == channelNumber)) { return connectionInfo[1]; } } } return "0.0.0.0"; } public void updateMacs(String macData) { macs.addAll(Arrays.asList(macData.split(", "))); StringBuilder newMacData = new StringBuilder(); Iterator<String> iter = macs.iterator(); PreparedStatement ps = null; while (iter.hasNext()) { String cur = iter.next(); newMacData.append(cur); if (iter.hasNext()) { newMacData.append(", "); } } try { ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET macs = ? WHERE id = ?"); ps.setString(1, newMacData.toString()); ps.setInt(2, accId); ps.executeUpdate(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (ps != null && !ps.isClosed()) { ps.close(); } } catch (SQLException ex) { } } } public void setAccID(int id) { this.accId = id; } public int getAccID() { return accId; } public void updateLoginState(int newstate) { try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("UPDATE accounts SET loggedin = ?, lastlogin = CURRENT_TIMESTAMP() WHERE id = ?"); ps.setInt(1, newstate); ps.setInt(2, getAccID()); ps.executeUpdate(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } if (newstate == LOGIN_NOTLOGGEDIN) { loggedIn = false; serverTransition = false; } else { serverTransition = (newstate == LOGIN_SERVER_TRANSITION); loggedIn = !serverTransition; } } public int getLoginState() { try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT loggedin, lastlogin, UNIX_TIMESTAMP(birthday) as birthday FROM accounts WHERE id = ?"); ps.setInt(1, getAccID()); ResultSet rs = ps.executeQuery(); if (!rs.next()) { rs.close(); ps.close(); throw new RuntimeException("getLoginState - MapleClient"); } birthday = Calendar.getInstance(); long blubb = rs.getLong("birthday"); if (blubb > 0) { birthday.setTimeInMillis(blubb * 1000); } int state = rs.getInt("loggedin"); if (state == LOGIN_SERVER_TRANSITION) { if (rs.getTimestamp("lastlogin").getTime() + 30000 < System.currentTimeMillis()) { state = LOGIN_NOTLOGGEDIN; updateLoginState(LOGIN_NOTLOGGEDIN); } } else if (state == LOGIN_LOGGEDIN && player == null) { state = LOGIN_NOTLOGGEDIN; updateLoginState(LOGIN_NOTLOGGEDIN); } rs.close(); ps.close(); if (state == LOGIN_LOGGEDIN) { loggedIn = true; } else if (state == LOGIN_SERVER_TRANSITION) { ps = con.prepareStatement("UPDATE accounts SET loggedin = 0 WHERE id = ?"); ps.setInt(1, getAccID()); ps.executeUpdate(); ps.close(); } else { loggedIn = false; } return state; } catch (SQLException e) { loggedIn = false; e.printStackTrace(); throw new RuntimeException("login state"); } } public boolean checkBirthDate(Calendar date) { return date.get(Calendar.YEAR) == birthday.get(Calendar.YEAR) && date.get(Calendar.MONTH) == birthday.get(Calendar.MONTH) && date.get(Calendar.DAY_OF_MONTH) == birthday.get(Calendar.DAY_OF_MONTH); } private void removePlayer() { try { getWorldServer().removePlayer(player);// out of channel too. Server.getInstance().getLoad(world).get(channel).decrementAndGet(); if (player.getMap() != null) { player.getMap().removePlayer(player); } if (player.getTrade() != null) { MapleTrade.cancelTrade(player); } if (gmlevel > 0) { GMServer.getInstance().removeInGame(player.getName()); } player.cancelAllBuffs(true); if (player.getEventInstance() != null) { player.getEventInstance().playerDisconnected(player); } player.cancelAllDebuffs(); } catch (final Throwable t) { PrintError.print(PrintError.ACCOUNT_STUCK, t); } } public final void disconnect() {// once per MapleClient instance try { if (player != null && isLoggedIn()) { removePlayer(); player.saveToDB(true); World worlda = getWorldServer(); player.saveCooldowns(); player.unequipPendantOfSpirit(); MapleMiniGame game = player.getMiniGame(); if (game != null) { player.setMiniGame(null); if (game.isOwner(player)) { player.getMap().broadcastMessage(MaplePacketCreator.removeCharBox(player)); game.broadcastToVisitor(MaplePacketCreator.getMiniGameClose()); } else { game.removeVisitor(player); } } HiredMerchant merchant = player.getHiredMerchant(); if (merchant != null) { if (merchant.isOwner(player)) { merchant.setOpen(true); } else { merchant.removeVisitor(player); } try { merchant.saveItems(false); } catch (SQLException ex) { Output.print("An error occurred while saving Hired Merchant items."); } } if (player.getMessenger() != null) { MapleMessengerCharacter messengerplayer = new MapleMessengerCharacter(player); worlda.leaveMessenger(player.getMessenger().getId(), messengerplayer); player.setMessenger(null); } NPCScriptManager npcsm = NPCScriptManager.getInstance(); if (npcsm != null) { npcsm.dispose(this); } if (!player.isAlive()) { player.setHp(50, true); } for (MapleQuestStatus status : player.getStartedQuests()) { MapleQuest quest = status.getQuest(); if (quest.getTimeLimit() > 0) { MapleQuestStatus newStatus = new MapleQuestStatus(quest, MapleQuestStatus.Status.NOT_STARTED); newStatus.setForfeited(player.getQuest(quest).getForfeited() + 1); player.updateQuest(newStatus); } } if (player.getParty() != null) { MaplePartyCharacter chrp = player.getMPC(); chrp.setOnline(false); worlda.updateParty(player.getParty().getId(), PartyOperation.LOG_ONOFF, chrp); } if (!this.serverTransition && isLoggedIn()) { worlda.loggedOff(player.getName(), player.getId(), channel, player.getBuddylist().getBuddyIds()); } else { worlda.loggedOn(player.getName(), player.getId(), channel, player.getBuddylist().getBuddyIds()); } if (player.getGuildId() > 0) { Server.getInstance().setGuildMemberOnline(player.getMGC(), false, (byte) -1); int allianceId = player.getGuild().getAllianceId(); if (allianceId > 0) { Server.getInstance().allianceMessage(allianceId, MaplePacketCreator.allianceMemberOnline(player, false), player.getId(), -1); } } } } finally { player = null; session.close(); } if (!this.serverTransition) { this.updateLoginState(LOGIN_NOTLOGGEDIN); } } public final void empty() { if (this.player != null) { this.player.getMount().empty(); this.player.empty(); } this.player = null; this.session = null; this.engines.clear(); this.engines = null; this.send = null; this.receive = null; this.channel = -1; } public byte getChannel() { return channel; } public Channel getChannelServer() { return Server.getInstance().getChannel(world, channel); } public World getWorldServer() { return Server.getInstance().getWorld(world); } public Channel getChannelServer(byte channel) { return Server.getInstance().getChannel(world, channel); } public boolean deleteCharacter(int cid) { Connection con = DatabaseConnection.getConnection(); try { PreparedStatement ps = con.prepareStatement("SELECT id, guildid, guildrank, name, allianceRank FROM characters WHERE id = ? AND accountid = ?"); ps.setInt(1, cid); ps.setInt(2, accId); ResultSet rs = ps.executeQuery(); if (!rs.next()) { rs.close(); ps.close(); return false; } if (rs.getInt("guildid") > 0) { try { Server.getInstance().deleteGuildCharacter(new MapleGuildCharacter(cid, 0, rs.getString("name"), (byte) -1, (byte) -1, 0, rs.getInt("guildrank"), rs.getInt("guildid"), false, rs.getInt("allianceRank"))); } catch (Exception re) { rs.close(); ps.close(); return false; } } rs.close(); ps = con.prepareStatement("DELETE FROM wishlists WHERE charid = ?"); ps.setInt(1, cid); ps.executeUpdate(); ps = con.prepareStatement("DELETE FROM characters WHERE id = ?"); ps.setInt(1, cid); ps.executeUpdate(); String[] toDel = {"famelog", "inventoryitems", "keymap", "queststatus", "savedlocations", "skillmacros", "skills", "eventstats"}; for (String s : toDel) { ps = con.prepareStatement("DELETE FROM `" + s + "` WHERE characterid = ?"); ps.setInt(1, cid); ps.executeUpdate(); } return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public String getAccountName() { return accountName; } public void setAccountName(String a) { this.accountName = a; } public void setChannel(byte channel) { this.channel = channel; } public byte getWorld() { return world; } public void setWorld(byte world) { this.world = world; } public void pongReceived() { lastPong = System.currentTimeMillis(); } public void sendPing() { final long then = System.currentTimeMillis(); announce(MaplePacketCreator.getPing()); TimerManager.getInstance().schedule(new Runnable() { @Override public void run() { try { if (lastPong < then) { if (getSession() != null && getSession().isConnected()) { getSession().close(true); } } } catch (NullPointerException e) { } } }, 15000); } public Set<String> getMacs() { return Collections.unmodifiableSet(macs); } public int gmLevel() { return this.gmlevel; } public void setScriptEngine(String name, ScriptEngine e) { engines.put(name, e); } public ScriptEngine getScriptEngine(String name) { return engines.get(name); } public void removeScriptEngine(String name) { engines.remove(name); } public ScheduledFuture<?> getIdleTask() { return idleTask; } public void setIdleTask(ScheduledFuture<?> idleTask) { this.idleTask = idleTask; } public NPCConversationManager getCM() { return NPCScriptManager.getInstance().getCM(this); } public QuestActionManager getQM() { return QuestScriptManager.getInstance().getQM(this); } public boolean acceptToS() { boolean disconnectForBeingAFaggot = false; if (accountName == null) { return true; } try { PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT `tos` FROM accounts WHERE id = ?"); ps.setInt(1, accId); ResultSet rs = ps.executeQuery(); if (rs.next()) { if (rs.getByte("tos") == 1) { disconnectForBeingAFaggot = true; } } ps.close(); rs.close(); rs = null; ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET tos = 1 WHERE id = ?"); ps.setInt(1, accId); ps.executeUpdate(); ps.close(); } catch (SQLException e) { } return disconnectForBeingAFaggot; } private static class CharNameAndId { public String name; public int id; public CharNameAndId(String name, int id) { super(); this.name = name; this.id = id; } } public static boolean checkHash(String hash, String type, String password) { try { MessageDigest digester = MessageDigest.getInstance(type); digester.update(password.getBytes("UTF-8"), 0, password.length()); return HexTool.toString(digester.digest()).replace(" ", "").toLowerCase().equals(hash); } catch (Exception e) { throw new RuntimeException("Encoding the string failed", e); } } public short getCharacterSlots() { return characterSlots; } public boolean gainCharacterSlot() { if (characterSlots < 15) { Connection con = DatabaseConnection.getConnection(); try { PreparedStatement ps = con.prepareStatement("UPDATE accounts SET characterslots = ? WHERE id = ?"); ps.setInt(1, this.characterSlots += 1); ps.setInt(2, accId); ps.executeUpdate(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } return true; } return false; } public final byte getGReason() { final Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("SELECT `greason` FROM `accounts` WHERE id = ?"); ps.setInt(1, accId); rs = ps.executeQuery(); if (rs.next()) { return rs.getByte("greason"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (ps != null) { ps.close(); } if (rs != null) { rs.close(); } } catch (SQLException e) { } } return 0; } public byte getGender() { return gender; } public void setGender(byte m) { this.gender = m; try { PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET gender = ? WHERE id = ?"); ps.setByte(1, gender); ps.setInt(2, accId); ps.executeUpdate(); ps.close(); } catch (SQLException e) { } } public void announce(MaplePacket packet) { session.write(packet); } public void saveLastKnownIP() { String sockAddr = getSession().getRemoteAddress().toString(); Connection con; try { con = DatabaseConnection.getConnection(); } catch (Exception e) { PrintError.print(PrintError.EXCEPTION_CAUGHT, e); return; } try { PreparedStatement ps = con.prepareStatement("UPDATE accounts SET lastknownip = ? WHERE name = ?"); ps.setString(1, sockAddr.substring(1, sockAddr.lastIndexOf(':'))); ps.setString(2, accountName); ps.executeUpdate(); ps.close(); } catch (SQLException e) { PrintError.print(PrintError.EXCEPTION_CAUGHT, e); } } }
true
true
public int login(String login, String pwd) { loginattempt++; if (loginattempt > 4) { getSession().close(true); } int loginok = 5; Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("SELECT id, password, salt, gender, banned, gm, pin, pic, characterslots, tos FROM accounts WHERE name = ?"); ps.setString(1, login); rs = ps.executeQuery(); if (rs.next()) { if (rs.getByte("banned") == 1) { return 3; } accId = rs.getInt("id"); gmlevel = rs.getInt("gm"); pin = rs.getString("pin"); pic = rs.getString("pic"); gender = rs.getByte("gender"); characterSlots = rs.getByte("characterslots"); String passhash = rs.getString("password"); String salt = rs.getString("salt"); // we do not unban byte tos = rs.getByte("tos"); ps.close(); rs.close(); if (getLoginState() > LOGIN_NOTLOGGEDIN) { // already loggedin loggedIn = false; loginok = 7; } else if (pwd.equals(passhash) || checkHash(passhash, "SHA-1", pwd) || checkHash(passhash, "SHA-512", pwd + salt)) { if (tos == 0) { loginok = 23; } else { loginok = 0; } } else { loggedIn = false; loginok = 4; } if (loginok == 0) { // We're going to change the hashing algorithm to SHA-512 with salt, so we can be secure! :3 SecureRandom random = new SecureRandom(); byte bytes[] = new byte[32]; // 32 bit salt (results may vary. depends on RNG algorithm) random.nextBytes(bytes); String saltNew = HexTool.toString(bytes); String passhashNew = HashCreator.getHash("SHA-512", pwd + saltNew); ps = con.prepareStatement("UPDATE accounts SET password = ?, salt = ? WHERE id = ?"); ps.setString(1, passhashNew); ps.setString(2, saltNew); ps.setInt(3, accId); rs = ps.executeQuery(); ps.close(); rs.close(); } ps = con.prepareStatement("INSERT INTO iplog (accountid, ip) VALUES (?, ?)"); ps.setInt(1, accId); ps.setString(2, session.getRemoteAddress().toString()); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { try { if (ps != null && !ps.isClosed()) { ps.close(); } if (rs != null && !rs.isClosed()) { rs.close(); } } catch (SQLException e) { } } if (loginok == 0) { loginattempt = 0; } return loginok; }
public int login(String login, String pwd) { loginattempt++; if (loginattempt > 4) { getSession().close(true); } int loginok = 5; Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("SELECT id, password, salt, gender, banned, gm, pin, pic, characterslots, tos FROM accounts WHERE name = ?"); ps.setString(1, login); rs = ps.executeQuery(); if (rs.next()) { if (rs.getByte("banned") == 1) { return 3; } accId = rs.getInt("id"); gmlevel = rs.getInt("gm"); pin = rs.getString("pin"); pic = rs.getString("pic"); gender = rs.getByte("gender"); characterSlots = rs.getByte("characterslots"); String passhash = rs.getString("password"); String salt = rs.getString("salt"); // we do not unban byte tos = rs.getByte("tos"); ps.close(); rs.close(); if (getLoginState() > LOGIN_NOTLOGGEDIN) { // already loggedin loggedIn = false; loginok = 7; } else if (pwd.equals(passhash) || checkHash(passhash, "SHA-1", pwd) || checkHash(passhash, "SHA-512", pwd + salt)) { if (tos == 0) { loginok = 23; } else { loginok = 0; } } else { loggedIn = false; loginok = 4; } if (loginok == 0) { // We're going to change the hashing algorithm to SHA-512 with salt, so we can be secure! :3 SecureRandom random = new SecureRandom(); byte bytes[] = new byte[32]; // 32 bit salt (results may vary. depends on RNG algorithm) random.nextBytes(bytes); String saltNew = HexTool.toString(bytes); String passhashNew = HashCreator.getHash("SHA-512", pwd + saltNew); ps = con.prepareStatement("UPDATE accounts SET password = ?, salt = ? WHERE id = ?"); ps.setString(1, passhashNew); ps.setString(2, saltNew); ps.setInt(3, accId); ps.executeUpdate(); ps.close(); rs.close(); } ps = con.prepareStatement("INSERT INTO iplog (accountid, ip) VALUES (?, ?)"); ps.setInt(1, accId); ps.setString(2, session.getRemoteAddress().toString()); ps.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { try { if (ps != null && !ps.isClosed()) { ps.close(); } if (rs != null && !rs.isClosed()) { rs.close(); } } catch (SQLException e) { } } if (loginok == 0) { loginattempt = 0; } return loginok; }
diff --git a/trunk/org/xbill/DNS/KEYRecord.java b/trunk/org/xbill/DNS/KEYRecord.java index 19cbcc8..5abeec2 100644 --- a/trunk/org/xbill/DNS/KEYRecord.java +++ b/trunk/org/xbill/DNS/KEYRecord.java @@ -1,222 +1,222 @@ // Copyright (c) 1999 Brian Wellington ([email protected]) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Key - contains a cryptographic public key. The data can be converted * to objects implementing java.security.interfaces.PublicKey * @see DNSSEC * * @author Brian Wellington */ public class KEYRecord extends Record { private short flags; private byte proto, alg; private byte [] key; private int footprint = -1; /* flags */ /** This key cannot be used for confidentiality (encryption) */ public static final int FLAG_NOCONF = 0x8000; /** This key cannot be used for authentication */ public static final int FLAG_NOAUTH = 0x4000; /** This key cannot be used for authentication or confidentiality */ public static final int FLAG_NOKEY = 0xC000; /** A zone key */ public static final int OWNER_ZONE = 0x0100; /** A host/end entity key */ public static final int OWNER_HOST = 0x0200; /** A user key */ public static final int OWNER_USER = 0x0000; /* protocols */ /** Key was created for use with transaction level security */ public static final int PROTOCOL_TLS = 1; /** Key was created for use with email */ public static final int PROTOCOL_EMAIL = 2; /** Key was created for use with DNSSEC */ public static final int PROTOCOL_DNSSEC = 3; /** Key was created for use with IPSEC */ public static final int PROTOCOL_IPSEC = 4; /** Key was created for use with any protocol */ public static final int PROTOCOL_ANY = 255; private KEYRecord() {} /** * Creates a KEY Record from the given data * @param flags Flags describing the key's properties * @param proto The protocol that the key was created for * @param alg The key's algorithm * @param key Binary data representing the key */ public KEYRecord(Name _name, short _dclass, int _ttl, int _flags, int _proto, int _alg, byte [] _key) { super(_name, Type.KEY, _dclass, _ttl); flags = (short) _flags; proto = (byte) _proto; alg = (byte) _alg; key = _key; } KEYRecord(Name _name, short _dclass, int _ttl, int length, DataByteInputStream in, Compression c) throws IOException { super(_name, Type.KEY, _dclass, _ttl); if (in == null) return; flags = in.readShort(); proto = in.readByte(); alg = in.readByte(); if (length > 4) { key = new byte[length - 4]; in.read(key); } } KEYRecord(Name _name, short _dclass, int _ttl, MyStringTokenizer st, Name origin) throws IOException { super(_name, Type.KEY, _dclass, _ttl); flags = (short) Integer.decode(st.nextToken()).intValue(); proto = (byte) Integer.parseInt(st.nextToken()); alg = (byte) Integer.parseInt(st.nextToken()); /* If this is a null key, there's no key data */ if (!((flags & (FLAG_NOKEY)) == (FLAG_NOKEY))) key = base64.fromString(st.remainingTokens()); else key = null; } /** * Converts rdata to a String */ public String rdataToString() { StringBuffer sb = new StringBuffer(); if (key != null || (flags & (FLAG_NOKEY)) == (FLAG_NOKEY) ) { if (!Options.check("nohex")) { sb.append("0x"); sb.append(Integer.toHexString(flags & 0xFFFF)); } else sb.append(flags & 0xFFFF); sb.append(" "); sb.append(proto & 0xFF); sb.append(" "); sb.append(alg & 0xFF); if (key != null) { sb.append(" (\n"); sb.append(base64.formatString(key, 64, "\t", true)); sb.append(" ; key_tag = "); sb.append(getFootprint() & 0xFFFF); } } return sb.toString(); } /** * Returns the flags describing the key's properties */ public short getFlags() { return flags; } /** * Returns the protocol that the key was created for */ public byte getProtocol() { return proto; } /** * Returns the key's algorithm */ public byte getAlgorithm() { return alg; } /** * Returns the binary data representing the key */ public byte [] getKey() { return key; } /** * Returns the key's footprint (after computing it) */ public short getFootprint() { if (footprint >= 0) return (short)footprint; int foot = 0; DataByteOutputStream out = new DataByteOutputStream(); try { rrToWire(out, null); } catch (IOException e) {} byte [] rdata = out.toByteArray(); if (alg == DNSSEC.RSA) { int d1 = rdata[key.length - 3] & 0xFF; int d2 = rdata[key.length - 2] & 0xFF; foot = (d1 << 8) + d2; } else { int i; for (i = 0; i < rdata.length - 1; i += 2) { int d1 = rdata[i] & 0xFF; int d2 = rdata[i + 1] & 0xFF; foot += ((d1 << 8) + d2); } - if (i <= rdata.length) { + if (i < rdata.length) { int d1 = rdata[i] & 0xFF; foot += (d1 << 8); } foot += ((foot >> 16) & 0xffff); } footprint = (foot & 0xffff); return (short) footprint; } void rrToWire(DataByteOutputStream out, Compression c) throws IOException { if (key == null && (flags & (FLAG_NOKEY)) != (FLAG_NOKEY) ) return; out.writeShort(flags); out.writeByte(proto); out.writeByte(alg); if (key != null) out.write(key); } }
true
true
public short getFootprint() { if (footprint >= 0) return (short)footprint; int foot = 0; DataByteOutputStream out = new DataByteOutputStream(); try { rrToWire(out, null); } catch (IOException e) {} byte [] rdata = out.toByteArray(); if (alg == DNSSEC.RSA) { int d1 = rdata[key.length - 3] & 0xFF; int d2 = rdata[key.length - 2] & 0xFF; foot = (d1 << 8) + d2; } else { int i; for (i = 0; i < rdata.length - 1; i += 2) { int d1 = rdata[i] & 0xFF; int d2 = rdata[i + 1] & 0xFF; foot += ((d1 << 8) + d2); } if (i <= rdata.length) { int d1 = rdata[i] & 0xFF; foot += (d1 << 8); } foot += ((foot >> 16) & 0xffff); } footprint = (foot & 0xffff); return (short) footprint; }
public short getFootprint() { if (footprint >= 0) return (short)footprint; int foot = 0; DataByteOutputStream out = new DataByteOutputStream(); try { rrToWire(out, null); } catch (IOException e) {} byte [] rdata = out.toByteArray(); if (alg == DNSSEC.RSA) { int d1 = rdata[key.length - 3] & 0xFF; int d2 = rdata[key.length - 2] & 0xFF; foot = (d1 << 8) + d2; } else { int i; for (i = 0; i < rdata.length - 1; i += 2) { int d1 = rdata[i] & 0xFF; int d2 = rdata[i + 1] & 0xFF; foot += ((d1 << 8) + d2); } if (i < rdata.length) { int d1 = rdata[i] & 0xFF; foot += (d1 << 8); } foot += ((foot >> 16) & 0xffff); } footprint = (foot & 0xffff); return (short) footprint; }
diff --git a/src/org/openjump/core/ui/io/file/DataSourceFileLayerLoader.java b/src/org/openjump/core/ui/io/file/DataSourceFileLayerLoader.java index 07632912..cac1a6b2 100644 --- a/src/org/openjump/core/ui/io/file/DataSourceFileLayerLoader.java +++ b/src/org/openjump/core/ui/io/file/DataSourceFileLayerLoader.java @@ -1,164 +1,167 @@ /* ***************************************************************************** The Open Java Unified Mapping Platform (OpenJUMP) is an extensible, interactive GUI for visualizing and manipulating spatial features with geometry and attributes. Copyright (C) 2007 Revolution Systems Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. For more information see: http://openjump.org/ ******************************************************************************/ package org.openjump.core.ui.io.file; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.openjump.core.ui.util.ExceptionUtil; import org.openjump.core.ui.util.TaskUtil; import org.openjump.util.UriUtil; import com.vividsolutions.jump.I18N; import com.vividsolutions.jump.coordsys.CoordinateSystemRegistry; import com.vividsolutions.jump.feature.FeatureCollection; import com.vividsolutions.jump.io.datasource.Connection; import com.vividsolutions.jump.io.datasource.DataSource; import com.vividsolutions.jump.io.datasource.DataSourceQuery; import com.vividsolutions.jump.task.TaskMonitor; import com.vividsolutions.jump.util.LangUtil; import com.vividsolutions.jump.workbench.WorkbenchContext; import com.vividsolutions.jump.workbench.model.Category; import com.vividsolutions.jump.workbench.model.Layer; import com.vividsolutions.jump.workbench.model.LayerManager; import com.vividsolutions.jump.workbench.ui.HTMLFrame; import com.vividsolutions.jump.workbench.ui.WorkbenchFrame; /** * The DataSourceFileLayerLoader is an implementation of {@link FileLayerLoader} * that wraps an existing file based {@link DataSource} class. * * @author Paul Austin */ public class DataSourceFileLayerLoader extends AbstractFileLayerLoader { /** The {@link DataSource} class. */ private Class dataSourceClass; /** The workbench context. */ private WorkbenchContext workbenchContext; /** * Construct a new DataSourceFileLayerLoader. * * @param workbenchContext The workbench context. * @param dataSourceClass The {@link DataSource} class. * @param description The file format name. * @param extensions The list of supported extensions. */ public DataSourceFileLayerLoader(WorkbenchContext workbenchContext, Class dataSourceClass, String description, List<String> extensions) { super(description, extensions); this.workbenchContext = workbenchContext; this.dataSourceClass = dataSourceClass; } /** * Open the file specified by the URI with the map of option values. * * @param monitor The TaskMonitor. * @param uri The URI to the file to load. * @param options The map of options. * @return True if the file could be loaded false otherwise. */ public boolean open(TaskMonitor monitor, URI uri, Map<String, Object> options) { DataSource dataSource = (DataSource)LangUtil.newInstance(dataSourceClass); Map<String, Object> properties = toProperties(uri, options); dataSource.setProperties(properties); String name = UriUtil.getFileNameWithoutExtension(uri); DataSourceQuery dataSourceQuery = new DataSourceQuery(dataSource, null, name); ArrayList exceptions = new ArrayList(); String layerName = dataSourceQuery.toString(); monitor.report("Loading " + layerName + "..."); Connection connection = dataSourceQuery.getDataSource().getConnection(); try { FeatureCollection dataset = dataSourceQuery.getDataSource() .installCoordinateSystem( connection.executeQuery(dataSourceQuery.getQuery(), exceptions, monitor), CoordinateSystemRegistry.instance(workbenchContext.getBlackboard())); if (dataset != null) { LayerManager layerManager = workbenchContext.getLayerManager(); Layer layer = new Layer(layerName, layerManager.generateLayerFillColor(), dataset, layerManager); Category category = TaskUtil.getSelectedCategoryName(workbenchContext); layerManager.addLayerable(category.getName(), layer); layer.setName(layerName); + if (uri.getScheme().equals("zip")) { + layer.setReadonly(true); + } // category.add(0, layer); layer.setDataSourceQuery(dataSourceQuery); layer.setFeatureCollectionModified(false); } } finally { connection.close(); } if (!exceptions.isEmpty()) { WorkbenchFrame workbenchFrame = workbenchContext.getWorkbench() .getFrame(); HTMLFrame outputFrame = workbenchFrame.getOutputFrame(); outputFrame.createNewDocument(); ExceptionUtil.reportExceptions(exceptions, dataSourceQuery, workbenchFrame, outputFrame); workbenchFrame.warnUser(I18N.get("datasource.LoadDatasetPlugIn.problems-were-encountered")); return false; } return true; } /** * Convert the URI and map of options for the data source. If the URI is a ZIP * uri the File option will be set to the ZIP file name and the CompressedFile * set to the entry in the ZIP file. * * @param uri The URI to the file. * @param options The selected options. * @return The options. */ protected Map<String, Object> toProperties(URI uri, Map<String, Object> options) { Map<String, Object> properties = new HashMap<String, Object>(); File file; if (uri.getScheme().equals("zip")) { file = UriUtil.getZipFile(uri); String compressedFile = UriUtil.getZipEntryName(uri); properties.put("CompressedFile", compressedFile); } else { file = new File(uri); } String filePath = file.getAbsolutePath(); properties.put(DataSource.FILE_KEY, filePath); properties.putAll(options); return properties; } }
true
true
public boolean open(TaskMonitor monitor, URI uri, Map<String, Object> options) { DataSource dataSource = (DataSource)LangUtil.newInstance(dataSourceClass); Map<String, Object> properties = toProperties(uri, options); dataSource.setProperties(properties); String name = UriUtil.getFileNameWithoutExtension(uri); DataSourceQuery dataSourceQuery = new DataSourceQuery(dataSource, null, name); ArrayList exceptions = new ArrayList(); String layerName = dataSourceQuery.toString(); monitor.report("Loading " + layerName + "..."); Connection connection = dataSourceQuery.getDataSource().getConnection(); try { FeatureCollection dataset = dataSourceQuery.getDataSource() .installCoordinateSystem( connection.executeQuery(dataSourceQuery.getQuery(), exceptions, monitor), CoordinateSystemRegistry.instance(workbenchContext.getBlackboard())); if (dataset != null) { LayerManager layerManager = workbenchContext.getLayerManager(); Layer layer = new Layer(layerName, layerManager.generateLayerFillColor(), dataset, layerManager); Category category = TaskUtil.getSelectedCategoryName(workbenchContext); layerManager.addLayerable(category.getName(), layer); layer.setName(layerName); // category.add(0, layer); layer.setDataSourceQuery(dataSourceQuery); layer.setFeatureCollectionModified(false); } } finally { connection.close(); } if (!exceptions.isEmpty()) { WorkbenchFrame workbenchFrame = workbenchContext.getWorkbench() .getFrame(); HTMLFrame outputFrame = workbenchFrame.getOutputFrame(); outputFrame.createNewDocument(); ExceptionUtil.reportExceptions(exceptions, dataSourceQuery, workbenchFrame, outputFrame); workbenchFrame.warnUser(I18N.get("datasource.LoadDatasetPlugIn.problems-were-encountered")); return false; } return true; }
public boolean open(TaskMonitor monitor, URI uri, Map<String, Object> options) { DataSource dataSource = (DataSource)LangUtil.newInstance(dataSourceClass); Map<String, Object> properties = toProperties(uri, options); dataSource.setProperties(properties); String name = UriUtil.getFileNameWithoutExtension(uri); DataSourceQuery dataSourceQuery = new DataSourceQuery(dataSource, null, name); ArrayList exceptions = new ArrayList(); String layerName = dataSourceQuery.toString(); monitor.report("Loading " + layerName + "..."); Connection connection = dataSourceQuery.getDataSource().getConnection(); try { FeatureCollection dataset = dataSourceQuery.getDataSource() .installCoordinateSystem( connection.executeQuery(dataSourceQuery.getQuery(), exceptions, monitor), CoordinateSystemRegistry.instance(workbenchContext.getBlackboard())); if (dataset != null) { LayerManager layerManager = workbenchContext.getLayerManager(); Layer layer = new Layer(layerName, layerManager.generateLayerFillColor(), dataset, layerManager); Category category = TaskUtil.getSelectedCategoryName(workbenchContext); layerManager.addLayerable(category.getName(), layer); layer.setName(layerName); if (uri.getScheme().equals("zip")) { layer.setReadonly(true); } // category.add(0, layer); layer.setDataSourceQuery(dataSourceQuery); layer.setFeatureCollectionModified(false); } } finally { connection.close(); } if (!exceptions.isEmpty()) { WorkbenchFrame workbenchFrame = workbenchContext.getWorkbench() .getFrame(); HTMLFrame outputFrame = workbenchFrame.getOutputFrame(); outputFrame.createNewDocument(); ExceptionUtil.reportExceptions(exceptions, dataSourceQuery, workbenchFrame, outputFrame); workbenchFrame.warnUser(I18N.get("datasource.LoadDatasetPlugIn.problems-were-encountered")); return false; } return true; }
diff --git a/src/main/java/org/isatools/tablib/export/graph2tab/StructuredTable.java b/src/main/java/org/isatools/tablib/export/graph2tab/StructuredTable.java index d006f89..f2bc24a 100644 --- a/src/main/java/org/isatools/tablib/export/graph2tab/StructuredTable.java +++ b/src/main/java/org/isatools/tablib/export/graph2tab/StructuredTable.java @@ -1,230 +1,230 @@ /* The ISAconverter, ISAvalidator & BII Management Tool are components of the ISA software suite (http://www.isa-tools.org) Exhibit A The ISAconverter, ISAvalidator & BII Management Tool are licensed under the Mozilla Public License (MPL) version 1.1/GPL version 2.0/LGPL version 2.1 "The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"). You may not use this file except in compliance with the License. You may obtain copies of the Licenses at http://www.mozilla.org/MPL/MPL-1.1.html. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is the ISAconverter, ISAvalidator & BII Management Tool. The Initial Developer of the Original Code is the ISA Team (Eamonn Maguire, [email protected]; Philippe Rocca-Serra, [email protected]; Susanna-Assunta Sansone, [email protected]; http://www.isa-tools.org). All portions of the code written by the ISA Team are Copyright (c) 2007-2011 ISA Team. All Rights Reserved. Contributor(s): Rocca-Serra P, Brandizi M, Maguire E, Sklyar N, Taylor C, Begley K, Field D, Harris S, Hide W, Hofmann O, Neumann S, Sterk P, Tong W, Sansone SA. ISA software suite: supporting standards-compliant experimental annotation and enabling curation at the community level. Bioinformatics 2010;26(18):2354-6. Alternatively, the contents of this file may be used under the terms of either the GNU General Public License Version 2 or later (the "GPL") - http://www.gnu.org/licenses/gpl-2.0.html, or the GNU Lesser General Public License Version 2.1 or later (the "LGPL") - http://www.gnu.org/licenses/lgpl-2.1.html, in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL, the GPL or the LGPL. Sponsors: The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). */ package org.isatools.tablib.export.graph2tab; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.isatools.tablib.export.graph2tab.minflow.MinFlowCalculator; import uk.ac.ebi.utils.collections.ListUtils; /** * * A Structured table. This is used internally by {@link TableBuilder#getTable()}. Essentially it allows to represent * a piece of the final resulting table as a list of nested columns (similarly to what it is done in {@link TabValueGroup}) * This way it's easy to build the final table by progressively merging the nodes that are found in the set of paths that * {@link MinFlowCalculator#getMinPathCover()} obtains from the initial input. * A structured table is composed of an header, an array of values for that header (ie, the column) and optionally * a tail, which represent linked headers and their values. The header columns and the tail columns need to be kept * together when new header/values are merged into an existing structured table. A structured table is built by * merging multiple {@link TabValueGroup}. * * <dl><dt>date</dt><dd>Jun 21, 2011</dd></dl> * @author brandizi * */ class StructuredTable { private final String header; private final List<String> rows = new ArrayList<String> (); private final List<StructuredTable> tail = new ArrayList<StructuredTable> (); /** * Creates a new structured table that contains the same header given by {@link TabValueGroup#getHeader() tbg.getHeader} * and adds the value ( {@link TabValueGroup#getValue() tbg.getValue} ) as last row * of the table, so this will appear in {@link StructuredTable#getRows()}. * Moreover, the tail of the table group {@link TabValueGroup#getTail()} becomes * the tail of the new structured table {@link #getTail()}, by applying the same composition criteria (i.e., this * constructor recursively calls itself over the tails it finds). * * @param tbg * @param rowsSize */ public StructuredTable ( TabValueGroup tbg, int rowsSize ) { this.header = tbg.getHeader (); addRowValue ( tbg.getValue (), rowsSize ); for ( TabValueGroup tailTbg: tbg.getTail () ) this.tail.add ( new StructuredTable ( tailTbg, rowsSize ) ); } /** * The table's initial column header */ public String getHeader () { return header; } /** * Adds a value to the row, given the information on what is the new desired size for the column represented by head of * this structured table, i.e., a new value for this {@link #getHeader() table's header}. This is used by * {@link TableBuilder#getTable()}, which knows which row (== newSize) it is building. * */ public void addRowValue ( String value, int newSize ) { ListUtils.set ( this.rows, newSize - 1, value ); } /** * Adds a nested table to the current header/column. For instance, A Term Source REF column can be added to an existing * Characteristics[] column. See {@link TabValueGroup}. */ public void appendTable ( StructuredTable table ) { this.tail.add ( table ); } /** * The table values for this header (i.e., the values for the first single column). */ public List<String> getRows () { return Collections.unmodifiableList ( rows ); } /** * The nested tables, i.e., the tables that goes together with the top-level column. See {@link TabValueGroup}. */ public List<StructuredTable> getTail () { return Collections.unmodifiableList ( tail ); } /** * Merges into existing structured tables a set of {@link TabValueGroup}s, typically the values provided with by * {@link Node#getTabValues()}, i.e., the contribute that a node gives to the final resulting table. * For instance, if so fare we have built a (structured) table with the headers: * Sample Name, Characteristics [�Organism ], Characteristics [ Organ Part ]� and a new node * arrives that contains: Sample Name, ( Characteristics [ Organism ], ( Term Source REF, ( Term Accession ) ) ), * Characteristics [ Sex ] the layer is changed so that it contains the new structure: * Sample Name, ( Characteristics [ Organism ], ( Term Source REF, ( Term Accession ) ) ), Characteristics [ Organ Part ], * Characteristics [ Sex ]. Note the usage of () to mark the nesting of StructuredTable(s) * * A new row is added to the {@link #getRows() rows property} of the corresponding StructuredTable * that reflects the values of the new node (so, the value is in {@link #getRows() this.getRows()} or in some other * StructuredTable that can be found by recursing over the {@link #getTail() tail}). * * Existing headers for which the node has no value to provide with are left null in the new row. * */ public static void mergeTabValues ( List<StructuredTable> tables, int newSize, List<TabValueGroup> tbvs ) { if ( tables == null ) throw new RuntimeException ( "mergeRows() expects a non null table array as parameter" ); if ( tbvs == null ) { mergeNullTabValues ( tables, newSize ); return; } for ( TabValueGroup tbg: tbvs ) { String rowHeader = tbg.getHeader (); boolean done = false; for ( StructuredTable table: tables ) { - if ( !rowHeader.equals ( table.getHeader () ) ) continue; + if ( rowHeader == null || !rowHeader.equals ( table.getHeader () ) ) continue; if ( table.getRows ().size () < newSize ) { // The header is still free for the row being built, so fill it. table.addRowValue ( tbg.getValue (), newSize ); mergeTabValues ( table.tail, newSize, tbg.getTail () ); done = true; break; } } if ( done ) continue; // else, we still have to fit the new header/value, so let's append it to the current array tables.add ( new StructuredTable ( tbg, newSize ) ); } // for rows } // mergeRows() /** * This is a facility similar to {@link #mergeTabValues(List, int, List)} (and actually used by it), adds a null * to every row that can be found in the parameter structured tables (it recurses on all the tails). * */ private static void mergeNullTabValues ( List<StructuredTable> tables, int newSize ) { for ( StructuredTable table: tables ) { table.addRowValue ( null, newSize ); mergeNullTabValues ( table.tail, newSize ); } } /** * Collects the first headers ({@link #getHeader()} and all the headers in {@link #getTail()}) into a plain list). * Obviously recurses on {@link #getTail()}. */ public void exportAllHeaders ( List<String> existingHeaders ) { existingHeaders.add ( header ); for ( StructuredTable tailTb: tail ) tailTb.exportAllHeaders ( existingHeaders ); } /** * Collects all the rows for this header ({@link #getRows()} and all the rows in {@link #getTail()}) into a plain list). * Obviously recurses on {@link #getTail()}. */ public void exportAllRows ( List<String> existingRow, int irow ) { existingRow.add ( ListUtils.get ( this.rows, irow ) ); for ( StructuredTable tailTb: tail ) tailTb.exportAllRows ( existingRow, irow ); } }
true
true
public static void mergeTabValues ( List<StructuredTable> tables, int newSize, List<TabValueGroup> tbvs ) { if ( tables == null ) throw new RuntimeException ( "mergeRows() expects a non null table array as parameter" ); if ( tbvs == null ) { mergeNullTabValues ( tables, newSize ); return; } for ( TabValueGroup tbg: tbvs ) { String rowHeader = tbg.getHeader (); boolean done = false; for ( StructuredTable table: tables ) { if ( !rowHeader.equals ( table.getHeader () ) ) continue; if ( table.getRows ().size () < newSize ) { // The header is still free for the row being built, so fill it. table.addRowValue ( tbg.getValue (), newSize ); mergeTabValues ( table.tail, newSize, tbg.getTail () ); done = true; break; } } if ( done ) continue; // else, we still have to fit the new header/value, so let's append it to the current array tables.add ( new StructuredTable ( tbg, newSize ) ); } // for rows } // mergeRows()
public static void mergeTabValues ( List<StructuredTable> tables, int newSize, List<TabValueGroup> tbvs ) { if ( tables == null ) throw new RuntimeException ( "mergeRows() expects a non null table array as parameter" ); if ( tbvs == null ) { mergeNullTabValues ( tables, newSize ); return; } for ( TabValueGroup tbg: tbvs ) { String rowHeader = tbg.getHeader (); boolean done = false; for ( StructuredTable table: tables ) { if ( rowHeader == null || !rowHeader.equals ( table.getHeader () ) ) continue; if ( table.getRows ().size () < newSize ) { // The header is still free for the row being built, so fill it. table.addRowValue ( tbg.getValue (), newSize ); mergeTabValues ( table.tail, newSize, tbg.getTail () ); done = true; break; } } if ( done ) continue; // else, we still have to fit the new header/value, so let's append it to the current array tables.add ( new StructuredTable ( tbg, newSize ) ); } // for rows } // mergeRows()
diff --git a/Infamy/TutorialInfamyWorld.java b/Infamy/TutorialInfamyWorld.java index 2864e58..8e652fa 100755 --- a/Infamy/TutorialInfamyWorld.java +++ b/Infamy/TutorialInfamyWorld.java @@ -1,250 +1,250 @@ import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; import java.util.*; /** * Write a description of class InfamyWorld here. * * @author (your name) * @version (a version number or a date) */ public class TutorialInfamyWorld extends HumanWorld { //phases 0, combat //1, retreat //2, cover public Dialogue dia; public Dialogue tutorialDiaIntro; public Dialogue tutorialDia; public int dialogueCounter; public int dialogueTimer; public Flag germanFlag; public Flag britishFlag; private int germansKilled = 0; private int numGermans = 0; private int phase = 0; private int phaseTimer = 0; private MountedMachineGun gun1; private MountedMachineGun gun2; /** * Constructor for objects of class InfamyWorld. * */ public TutorialInfamyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1024, 600, 1); dialogueTimer = 0; setBackground("Background.png"); dialogueCounter = 0; //AddTutorialDialogue("Kill all the enemies and capture the flag!!\n Move with AWSD and shoot with mouse1", 512, 50, false); //AddTutorialDialogue("Kill all the enemies and capture the flag!!\n Move with AWSD as shoot with mouse1", 512, 525, false); //AddTutorialDialogue("Hey Winston!!\nCome over here!", 200, 300, false); //AddTutorialDialogue("Talk to your fellow soldier and\nother NPC's by pressing the 'e' key.\nMove Winston with the 'wasd' keys.", 400, 100, true); populate(); spawnWave(GERM, NUM_ADVANCERS_3, false); spawnWave(BRIT, NUM_ADVANCERS_3, false); spawnG = true; spawnB = true; // Greenfoot.setWorld(new BombTheBase()); } public void populate() { germanFlag = new Flag("German"); addObject(germanFlag, 974, 245); britishFlag = new Flag("British"); addObject(britishFlag, 50, 245); EnemyNPC germanDefender1 = new EnemyNPC(true); addHuman(germanDefender1, 900, 400); EnemyNPC germanDefender2 = new EnemyNPC(true); addHuman(germanDefender2, 900, 100); CrossHair crosshair = new CrossHair(); addObject(crosshair, 0, 0); //Sandbag sb1 = new Sandbag(); //sb1.turn(90); // addObject(sb1, 600, 130); Sandbag sb2 = new Sandbag(); //sb2.turn(90); addObject(sb2, 500, 400); Sandbag sb3 = new Sandbag(); //sb3.turn(90); addObject(sb3, 300, 375); Sandbag sb4 = new Sandbag(); //sb4.turn(90); addObject(sb4, 400, 190); FadingDialogue f = new FadingDialogue(512, 50, "1912 France, 87th Infantry", 10, 10); addObject(f, 512, 50); FadingDialogue g = new FadingDialogue(512, 480, "Kill all the enemies and capture the flag!!\n Move with AWSD and shoot with mouse1", 10, 10); addObject(g, 512, 480); BritNPC npc2 = new BritNPC(true); addHuman(npc2, 130, 400); BritNPC npc1 = new BritNPC(true); addHuman(npc1, 130, 100); WinstonCrowley move = new WinstonCrowley(); addHuman(move, 95, 500); super.populate(); numGermans = 5; } public int germansKilled() { int newNum = getObjects(German.class).size(); if(numGermans - newNum > 0){ germansKilled += numGermans - newNum; } numGermans = newNum; return germansKilled; } public void act() { super.act(); Date d = new Date(); if (dialogueTimer == 500) { removeObject(tutorialDia); } if (phase == 0){ spawnG = germansKilled() < 5 && (d.getTime() - baseTimeG) > germSpawn; spawnB = (d.getTime() - baseTimeB) > britSpawn; if(germansKilled == 4){ phase++; spawnB = false; spawnG = false; } } if(phase == 1) { for(Human character : (ArrayList<Human>)getObjects(Human.class)){ if(!(character instanceof WinstonCrowley)&&!character.isDefender()) character.setRetreat(true); } FadingDialogue g = new FadingDialogue(512, 480, "Watch Out Machine Guns are coming!\n" + " Take cover in your trench!\n" + "(to take cover hold 'c' while in your trench)", 15, 15); addObject(g, 512, 480); phase++; } if(phase == 2) { if (phaseTimer / 100 == 1) { phase++; phaseTimer = 0; } else phaseTimer++; } if(phase == 3) { gun1 = new MountedMachineGun(800,10,10); gun2 = new MountedMachineGun(800, 200,10); addHuman(gun1, 1000, 200); addHuman(gun2, 1000, 500); phase++; } if(phase == 4) { - if(gun1.isPlanted() && gun2.isPlanted()) + if( (gun1 == null || gun1.isPlanted()) && (gun2 == null || gun2.isPlanted())) phase++; } if(phase == 5) { FadingDialogue g = new FadingDialogue(512, 480, "Keep your head down!", 10, 10); addObject(g, 512, 480); phase++; } if(phase == 6){ if((phaseTimer / 500) == 1){ phase++; phaseTimer =0; } else phaseTimer++; } if(phase == 7){ boolean gun1Present = getObjects(MountedMachineGun.class).contains(gun1); boolean gun2Present = getObjects(MountedMachineGun.class).contains(gun2); if( gun1Present && gun1.getX() < 1000) gun1.animateBack(); if(gun2Present && gun2.getX() < 1000) gun2.animateBack(); if(!gun1Present && !gun2Present) phase += 2; if((gun2Present && gun2.getX() == 1000) || (gun1Present && gun1.getX() == 1000)){ phase++; } } if(phase == 8) { if(getObjects(MountedMachineGun.class).contains(gun1)){ removeObject(gun1.getHealthBar()); removeObject(gun1); } if(getObjects(MountedMachineGun.class).contains(gun2)){ removeObject(gun2.getHealthBar()); removeObject(gun2); } phase++; } if(phase == 9){ FadingDialogue g = new FadingDialogue(512, 480, "Heads up! Mortars!\n" + "(Mortars will still hit you if you are under cover in the trench)", 10, 10); addObject(g, 512, 480); phase++; } if(phase == 10) { if(phaseTimer % 70 == 0){ Mortar mortar = new Mortar(125, (int)(Math.random() * 400 + 100)); addObject(mortar, 0,0); } if(phaseTimer / 70 == 5) { phaseTimer = 0; phase++; } phaseTimer++; } if(phase == 11) { Greenfoot.setWorld(new SecondLevel()); } if(spawnB && bCounter == 0) { spawnWave(BRIT,britAmmount, true); spawnB = false; baseTimeB = d.getTime(); } if (spawnG && gCounter == 0) { spawnWave(GERM, germAmmount, true); spawnG = false; baseTimeG = d.getTime(); } } }
true
true
public void act() { super.act(); Date d = new Date(); if (dialogueTimer == 500) { removeObject(tutorialDia); } if (phase == 0){ spawnG = germansKilled() < 5 && (d.getTime() - baseTimeG) > germSpawn; spawnB = (d.getTime() - baseTimeB) > britSpawn; if(germansKilled == 4){ phase++; spawnB = false; spawnG = false; } } if(phase == 1) { for(Human character : (ArrayList<Human>)getObjects(Human.class)){ if(!(character instanceof WinstonCrowley)&&!character.isDefender()) character.setRetreat(true); } FadingDialogue g = new FadingDialogue(512, 480, "Watch Out Machine Guns are coming!\n" + " Take cover in your trench!\n" + "(to take cover hold 'c' while in your trench)", 15, 15); addObject(g, 512, 480); phase++; } if(phase == 2) { if (phaseTimer / 100 == 1) { phase++; phaseTimer = 0; } else phaseTimer++; } if(phase == 3) { gun1 = new MountedMachineGun(800,10,10); gun2 = new MountedMachineGun(800, 200,10); addHuman(gun1, 1000, 200); addHuman(gun2, 1000, 500); phase++; } if(phase == 4) { if(gun1.isPlanted() && gun2.isPlanted()) phase++; } if(phase == 5) { FadingDialogue g = new FadingDialogue(512, 480, "Keep your head down!", 10, 10); addObject(g, 512, 480); phase++; } if(phase == 6){ if((phaseTimer / 500) == 1){ phase++; phaseTimer =0; } else phaseTimer++; } if(phase == 7){ boolean gun1Present = getObjects(MountedMachineGun.class).contains(gun1); boolean gun2Present = getObjects(MountedMachineGun.class).contains(gun2); if( gun1Present && gun1.getX() < 1000) gun1.animateBack(); if(gun2Present && gun2.getX() < 1000) gun2.animateBack(); if(!gun1Present && !gun2Present) phase += 2; if((gun2Present && gun2.getX() == 1000) || (gun1Present && gun1.getX() == 1000)){ phase++; } } if(phase == 8) { if(getObjects(MountedMachineGun.class).contains(gun1)){ removeObject(gun1.getHealthBar()); removeObject(gun1); } if(getObjects(MountedMachineGun.class).contains(gun2)){ removeObject(gun2.getHealthBar()); removeObject(gun2); } phase++; } if(phase == 9){ FadingDialogue g = new FadingDialogue(512, 480, "Heads up! Mortars!\n" + "(Mortars will still hit you if you are under cover in the trench)", 10, 10); addObject(g, 512, 480); phase++; } if(phase == 10) { if(phaseTimer % 70 == 0){ Mortar mortar = new Mortar(125, (int)(Math.random() * 400 + 100)); addObject(mortar, 0,0); } if(phaseTimer / 70 == 5) { phaseTimer = 0; phase++; } phaseTimer++; } if(phase == 11) { Greenfoot.setWorld(new SecondLevel()); } if(spawnB && bCounter == 0) { spawnWave(BRIT,britAmmount, true); spawnB = false; baseTimeB = d.getTime(); } if (spawnG && gCounter == 0) { spawnWave(GERM, germAmmount, true); spawnG = false; baseTimeG = d.getTime(); } }
public void act() { super.act(); Date d = new Date(); if (dialogueTimer == 500) { removeObject(tutorialDia); } if (phase == 0){ spawnG = germansKilled() < 5 && (d.getTime() - baseTimeG) > germSpawn; spawnB = (d.getTime() - baseTimeB) > britSpawn; if(germansKilled == 4){ phase++; spawnB = false; spawnG = false; } } if(phase == 1) { for(Human character : (ArrayList<Human>)getObjects(Human.class)){ if(!(character instanceof WinstonCrowley)&&!character.isDefender()) character.setRetreat(true); } FadingDialogue g = new FadingDialogue(512, 480, "Watch Out Machine Guns are coming!\n" + " Take cover in your trench!\n" + "(to take cover hold 'c' while in your trench)", 15, 15); addObject(g, 512, 480); phase++; } if(phase == 2) { if (phaseTimer / 100 == 1) { phase++; phaseTimer = 0; } else phaseTimer++; } if(phase == 3) { gun1 = new MountedMachineGun(800,10,10); gun2 = new MountedMachineGun(800, 200,10); addHuman(gun1, 1000, 200); addHuman(gun2, 1000, 500); phase++; } if(phase == 4) { if( (gun1 == null || gun1.isPlanted()) && (gun2 == null || gun2.isPlanted())) phase++; } if(phase == 5) { FadingDialogue g = new FadingDialogue(512, 480, "Keep your head down!", 10, 10); addObject(g, 512, 480); phase++; } if(phase == 6){ if((phaseTimer / 500) == 1){ phase++; phaseTimer =0; } else phaseTimer++; } if(phase == 7){ boolean gun1Present = getObjects(MountedMachineGun.class).contains(gun1); boolean gun2Present = getObjects(MountedMachineGun.class).contains(gun2); if( gun1Present && gun1.getX() < 1000) gun1.animateBack(); if(gun2Present && gun2.getX() < 1000) gun2.animateBack(); if(!gun1Present && !gun2Present) phase += 2; if((gun2Present && gun2.getX() == 1000) || (gun1Present && gun1.getX() == 1000)){ phase++; } } if(phase == 8) { if(getObjects(MountedMachineGun.class).contains(gun1)){ removeObject(gun1.getHealthBar()); removeObject(gun1); } if(getObjects(MountedMachineGun.class).contains(gun2)){ removeObject(gun2.getHealthBar()); removeObject(gun2); } phase++; } if(phase == 9){ FadingDialogue g = new FadingDialogue(512, 480, "Heads up! Mortars!\n" + "(Mortars will still hit you if you are under cover in the trench)", 10, 10); addObject(g, 512, 480); phase++; } if(phase == 10) { if(phaseTimer % 70 == 0){ Mortar mortar = new Mortar(125, (int)(Math.random() * 400 + 100)); addObject(mortar, 0,0); } if(phaseTimer / 70 == 5) { phaseTimer = 0; phase++; } phaseTimer++; } if(phase == 11) { Greenfoot.setWorld(new SecondLevel()); } if(spawnB && bCounter == 0) { spawnWave(BRIT,britAmmount, true); spawnB = false; baseTimeB = d.getTime(); } if (spawnG && gCounter == 0) { spawnWave(GERM, germAmmount, true); spawnG = false; baseTimeG = d.getTime(); } }
diff --git a/src/com/android/settings/wifi/AccessPoint.java b/src/com/android/settings/wifi/AccessPoint.java index f6581a5fa..20146eb27 100644 --- a/src/com/android/settings/wifi/AccessPoint.java +++ b/src/com/android/settings/wifi/AccessPoint.java @@ -1,398 +1,398 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.wifi; import android.content.Context; import android.net.NetworkInfo.DetailedState; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.preference.Preference; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.android.settings.R; class AccessPoint extends Preference { static final String TAG = "Settings.AccessPoint"; private static final String KEY_DETAILEDSTATE = "key_detailedstate"; private static final String KEY_WIFIINFO = "key_wifiinfo"; private static final String KEY_SCANRESULT = "key_scanresult"; private static final String KEY_CONFIG = "key_config"; private static final int[] STATE_SECURED = { R.attr.state_encrypted }; private static final int[] STATE_NONE = {}; /** These values are matched in string arrays -- changes must be kept in sync */ static final int SECURITY_NONE = 0; static final int SECURITY_WEP = 1; static final int SECURITY_PSK = 2; static final int SECURITY_EAP = 3; enum PskType { UNKNOWN, WPA, WPA2, WPA_WPA2 } String ssid; String bssid; int security; int networkId; boolean wpsAvailable = false; PskType pskType = PskType.UNKNOWN; private WifiConfiguration mConfig; /* package */ScanResult mScanResult; private int mRssi; private WifiInfo mInfo; private DetailedState mState; static int getSecurity(WifiConfiguration config) { if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { return SECURITY_PSK; } if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { return SECURITY_EAP; } return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; } private static int getSecurity(ScanResult result) { if (result.capabilities.contains("WEP")) { return SECURITY_WEP; } else if (result.capabilities.contains("PSK")) { return SECURITY_PSK; } else if (result.capabilities.contains("EAP")) { return SECURITY_EAP; } return SECURITY_NONE; } public String getSecurityString(boolean concise) { Context context = getContext(); switch(security) { case SECURITY_EAP: return concise ? context.getString(R.string.wifi_security_short_eap) : context.getString(R.string.wifi_security_eap); case SECURITY_PSK: switch (pskType) { case WPA: return concise ? context.getString(R.string.wifi_security_short_wpa) : context.getString(R.string.wifi_security_wpa); case WPA2: return concise ? context.getString(R.string.wifi_security_short_wpa2) : context.getString(R.string.wifi_security_wpa2); case WPA_WPA2: return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) : context.getString(R.string.wifi_security_wpa_wpa2); case UNKNOWN: default: return concise ? context.getString(R.string.wifi_security_short_psk_generic) : context.getString(R.string.wifi_security_psk_generic); } case SECURITY_WEP: return concise ? context.getString(R.string.wifi_security_short_wep) : context.getString(R.string.wifi_security_wep); case SECURITY_NONE: default: return concise ? "" : context.getString(R.string.wifi_security_none); } } private static PskType getPskType(ScanResult result) { boolean wpa = result.capabilities.contains("WPA-PSK"); boolean wpa2 = result.capabilities.contains("WPA2-PSK"); if (wpa2 && wpa) { return PskType.WPA_WPA2; } else if (wpa2) { return PskType.WPA2; } else if (wpa) { return PskType.WPA; } else { Log.w(TAG, "Received abnormal flag string: " + result.capabilities); return PskType.UNKNOWN; } } AccessPoint(Context context, WifiConfiguration config) { super(context); setWidgetLayoutResource(R.layout.preference_widget_wifi_signal); loadConfig(config); refresh(); } AccessPoint(Context context, ScanResult result) { super(context); setWidgetLayoutResource(R.layout.preference_widget_wifi_signal); loadResult(result); refresh(); } AccessPoint(Context context, Bundle savedState) { super(context); setWidgetLayoutResource(R.layout.preference_widget_wifi_signal); mConfig = savedState.getParcelable(KEY_CONFIG); if (mConfig != null) { loadConfig(mConfig); } mScanResult = (ScanResult) savedState.getParcelable(KEY_SCANRESULT); if (mScanResult != null) { loadResult(mScanResult); } mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO); if (savedState.containsKey(KEY_DETAILEDSTATE)) { mState = DetailedState.valueOf(savedState.getString(KEY_DETAILEDSTATE)); } update(mInfo, mState); } public void saveWifiState(Bundle savedState) { savedState.putParcelable(KEY_CONFIG, mConfig); savedState.putParcelable(KEY_SCANRESULT, mScanResult); savedState.putParcelable(KEY_WIFIINFO, mInfo); if (mState != null) { savedState.putString(KEY_DETAILEDSTATE, mState.toString()); } } private void loadConfig(WifiConfiguration config) { ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID)); bssid = config.BSSID; security = getSecurity(config); networkId = config.networkId; mRssi = Integer.MAX_VALUE; mConfig = config; } private void loadResult(ScanResult result) { ssid = result.SSID; bssid = result.BSSID; security = getSecurity(result); wpsAvailable = security != SECURITY_EAP && result.capabilities.contains("WPS"); if (security == SECURITY_PSK) pskType = getPskType(result); networkId = -1; mRssi = result.level; mScanResult = result; } @Override protected void onBindView(View view) { super.onBindView(view); ImageView signal = (ImageView) view.findViewById(R.id.signal); if (mRssi == Integer.MAX_VALUE) { signal.setImageDrawable(null); } else { signal.setImageLevel(getLevel()); signal.setImageResource(R.drawable.wifi_signal); signal.setImageState((security != SECURITY_NONE) ? STATE_SECURED : STATE_NONE, true); } } @Override public int compareTo(Preference preference) { if (!(preference instanceof AccessPoint)) { return 1; } AccessPoint other = (AccessPoint) preference; // Active one goes first. if (mInfo != null && other.mInfo == null) return -1; if (mInfo == null && other.mInfo != null) return 1; // Reachable one goes before unreachable one. if (mRssi != Integer.MAX_VALUE && other.mRssi == Integer.MAX_VALUE) return -1; if (mRssi == Integer.MAX_VALUE && other.mRssi != Integer.MAX_VALUE) return 1; // Configured one goes before unconfigured one. if (networkId != WifiConfiguration.INVALID_NETWORK_ID && other.networkId == WifiConfiguration.INVALID_NETWORK_ID) return -1; if (networkId == WifiConfiguration.INVALID_NETWORK_ID && other.networkId != WifiConfiguration.INVALID_NETWORK_ID) return 1; // Sort by signal strength. int difference = WifiManager.compareSignalLevel(other.mRssi, mRssi); if (difference != 0) { return difference; } // Sort by ssid. return ssid.compareToIgnoreCase(other.ssid); } @Override public boolean equals(Object other) { if (!(other instanceof AccessPoint)) return false; return (this.compareTo((AccessPoint) other) == 0); } @Override public int hashCode() { int result = 0; if (mInfo != null) result += 13 * mInfo.hashCode(); result += 19 * mRssi; result += 23 * networkId; result += 29 * ssid.hashCode(); return result; } boolean update(ScanResult result) { if (ssid.equals(result.SSID) && security == getSecurity(result)) { if (WifiManager.compareSignalLevel(result.level, mRssi) > 0) { int oldLevel = getLevel(); mRssi = result.level; if (getLevel() != oldLevel) { notifyChanged(); } } // This flag only comes from scans, is not easily saved in config if (security == SECURITY_PSK) { pskType = getPskType(result); } refresh(); return true; } return false; } void update(WifiInfo info, DetailedState state) { boolean reorder = false; if (info != null && networkId != WifiConfiguration.INVALID_NETWORK_ID && networkId == info.getNetworkId()) { reorder = (mInfo == null); mRssi = info.getRssi(); mInfo = info; mState = state; refresh(); } else if (mInfo != null) { reorder = true; mInfo = null; mState = null; refresh(); } if (reorder) { notifyHierarchyChanged(); } } int getLevel() { if (mRssi == Integer.MAX_VALUE) { return -1; } return WifiManager.calculateSignalLevel(mRssi, 4); } WifiConfiguration getConfig() { return mConfig; } WifiInfo getInfo() { return mInfo; } DetailedState getState() { return mState; } static String removeDoubleQuotes(String string) { int length = string.length(); if ((length > 1) && (string.charAt(0) == '"') && (string.charAt(length - 1) == '"')) { return string.substring(1, length - 1); } return string; } static String convertToQuotedString(String string) { return "\"" + string + "\""; } /** Updates the title and summary; may indirectly call notifyChanged() */ private void refresh() { setTitle(ssid); Context context = getContext(); - if (mState != null) { // This is the active connection - setSummary(Summary.get(context, mState)); - } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range - setSummary(context.getString(R.string.wifi_not_in_range)); - } else if (mConfig != null && mConfig.status == WifiConfiguration.Status.DISABLED) { + if (mConfig != null && mConfig.status == WifiConfiguration.Status.DISABLED) { switch (mConfig.disableReason) { case WifiConfiguration.DISABLED_AUTH_FAILURE: setSummary(context.getString(R.string.wifi_disabled_password_failure)); break; case WifiConfiguration.DISABLED_DHCP_FAILURE: case WifiConfiguration.DISABLED_DNS_FAILURE: setSummary(context.getString(R.string.wifi_disabled_network_failure)); break; case WifiConfiguration.DISABLED_UNKNOWN_REASON: setSummary(context.getString(R.string.wifi_disabled_generic)); } + } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range + setSummary(context.getString(R.string.wifi_not_in_range)); + } else if (mState != null) { // This is the active connection + setSummary(Summary.get(context, mState)); } else { // In range, not disabled. StringBuilder summary = new StringBuilder(); if (mConfig != null) { // Is saved network summary.append(context.getString(R.string.wifi_remembered)); } if (security != SECURITY_NONE) { String securityStrFormat; if (summary.length() == 0) { securityStrFormat = context.getString(R.string.wifi_secured_first_item); } else { securityStrFormat = context.getString(R.string.wifi_secured_second_item); } summary.append(String.format(securityStrFormat, getSecurityString(true))); } if (mConfig == null && wpsAvailable) { // Only list WPS available for unsaved networks if (summary.length() == 0) { summary.append(context.getString(R.string.wifi_wps_available_first_item)); } else { summary.append(context.getString(R.string.wifi_wps_available_second_item)); } } setSummary(summary.toString()); } } /** * Generate and save a default wifiConfiguration with common values. * Can only be called for unsecured networks. * @hide */ protected void generateOpenNetworkConfig() { if (security != SECURITY_NONE) throw new IllegalStateException(); if (mConfig != null) return; mConfig = new WifiConfiguration(); mConfig.SSID = AccessPoint.convertToQuotedString(ssid); mConfig.allowedKeyManagement.set(KeyMgmt.NONE); } }
false
true
private void refresh() { setTitle(ssid); Context context = getContext(); if (mState != null) { // This is the active connection setSummary(Summary.get(context, mState)); } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range setSummary(context.getString(R.string.wifi_not_in_range)); } else if (mConfig != null && mConfig.status == WifiConfiguration.Status.DISABLED) { switch (mConfig.disableReason) { case WifiConfiguration.DISABLED_AUTH_FAILURE: setSummary(context.getString(R.string.wifi_disabled_password_failure)); break; case WifiConfiguration.DISABLED_DHCP_FAILURE: case WifiConfiguration.DISABLED_DNS_FAILURE: setSummary(context.getString(R.string.wifi_disabled_network_failure)); break; case WifiConfiguration.DISABLED_UNKNOWN_REASON: setSummary(context.getString(R.string.wifi_disabled_generic)); } } else { // In range, not disabled. StringBuilder summary = new StringBuilder(); if (mConfig != null) { // Is saved network summary.append(context.getString(R.string.wifi_remembered)); } if (security != SECURITY_NONE) { String securityStrFormat; if (summary.length() == 0) { securityStrFormat = context.getString(R.string.wifi_secured_first_item); } else { securityStrFormat = context.getString(R.string.wifi_secured_second_item); } summary.append(String.format(securityStrFormat, getSecurityString(true))); } if (mConfig == null && wpsAvailable) { // Only list WPS available for unsaved networks if (summary.length() == 0) { summary.append(context.getString(R.string.wifi_wps_available_first_item)); } else { summary.append(context.getString(R.string.wifi_wps_available_second_item)); } } setSummary(summary.toString()); } }
private void refresh() { setTitle(ssid); Context context = getContext(); if (mConfig != null && mConfig.status == WifiConfiguration.Status.DISABLED) { switch (mConfig.disableReason) { case WifiConfiguration.DISABLED_AUTH_FAILURE: setSummary(context.getString(R.string.wifi_disabled_password_failure)); break; case WifiConfiguration.DISABLED_DHCP_FAILURE: case WifiConfiguration.DISABLED_DNS_FAILURE: setSummary(context.getString(R.string.wifi_disabled_network_failure)); break; case WifiConfiguration.DISABLED_UNKNOWN_REASON: setSummary(context.getString(R.string.wifi_disabled_generic)); } } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range setSummary(context.getString(R.string.wifi_not_in_range)); } else if (mState != null) { // This is the active connection setSummary(Summary.get(context, mState)); } else { // In range, not disabled. StringBuilder summary = new StringBuilder(); if (mConfig != null) { // Is saved network summary.append(context.getString(R.string.wifi_remembered)); } if (security != SECURITY_NONE) { String securityStrFormat; if (summary.length() == 0) { securityStrFormat = context.getString(R.string.wifi_secured_first_item); } else { securityStrFormat = context.getString(R.string.wifi_secured_second_item); } summary.append(String.format(securityStrFormat, getSecurityString(true))); } if (mConfig == null && wpsAvailable) { // Only list WPS available for unsaved networks if (summary.length() == 0) { summary.append(context.getString(R.string.wifi_wps_available_first_item)); } else { summary.append(context.getString(R.string.wifi_wps_available_second_item)); } } setSummary(summary.toString()); } }
diff --git a/src/main/java/jscover/report/JSONDataSaver.java b/src/main/java/jscover/report/JSONDataSaver.java index 0302b941..fdd981a2 100644 --- a/src/main/java/jscover/report/JSONDataSaver.java +++ b/src/main/java/jscover/report/JSONDataSaver.java @@ -1,403 +1,404 @@ /** GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package jscover.report; import jscover.util.IoUtils; import java.io.File; import java.util.*; import java.util.logging.Logger; import static java.util.logging.Level.SEVERE; public class JSONDataSaver { private static final Logger logger = Logger.getLogger(JSONDataSaver.class.getName()); protected static Set<File> files = new HashSet<File>(); private JSONDataMerger jsonDataMerger = new JSONDataMerger(); private IoUtils ioUtils = IoUtils.getInstance(); public void saveJSONData(File reportDir, String data, List<ScriptCoverageCount> unloadJSData) { try { lockOnReportDir(reportDir); reportDir.mkdirs(); File jsonFile = new File(reportDir, "jscoverage.json"); SortedMap<String, FileData> extraData = new TreeMap<String, FileData>(); if (jsonFile.exists()) { logger.info("Saving/merging JSON with existing JSON"); String existingJSON = ioUtils.toString(jsonFile); extraData.putAll(jsonDataMerger.mergeJSONCoverageStrings(existingJSON, data)); ioUtils.copy(jsonDataMerger.toJSON(extraData), jsonFile); } else if (unloadJSData != null) { logger.info("Saving/merging JSON with unloaded JavaScript JSON"); //Only scan for unloaded JS if JSON not saved before extraData.putAll(jsonDataMerger.createEmptyJSON(unloadJSData)); extraData.putAll(jsonDataMerger.jsonToMap(data)); ioUtils.copy(jsonDataMerger.toJSON(extraData), jsonFile); - } else + } else { logger.info("Saving JSON"); ioUtils.copy(data, jsonFile); + } } finally { unlockOnReportDir(reportDir); } } private void lockOnReportDir(File reportDir) { synchronized (files) { while (files.contains(reportDir)) try { files.wait(); } catch (InterruptedException ex) { logger.log(SEVERE, Thread.currentThread().getName() +" INTERRUPTED", ex); } files.add(reportDir); files.notifyAll(); // must own the lock } } private void unlockOnReportDir(File reportDir) { synchronized (files) { files.remove(reportDir); files.notifyAll(); } } }
false
true
public void saveJSONData(File reportDir, String data, List<ScriptCoverageCount> unloadJSData) { try { lockOnReportDir(reportDir); reportDir.mkdirs(); File jsonFile = new File(reportDir, "jscoverage.json"); SortedMap<String, FileData> extraData = new TreeMap<String, FileData>(); if (jsonFile.exists()) { logger.info("Saving/merging JSON with existing JSON"); String existingJSON = ioUtils.toString(jsonFile); extraData.putAll(jsonDataMerger.mergeJSONCoverageStrings(existingJSON, data)); ioUtils.copy(jsonDataMerger.toJSON(extraData), jsonFile); } else if (unloadJSData != null) { logger.info("Saving/merging JSON with unloaded JavaScript JSON"); //Only scan for unloaded JS if JSON not saved before extraData.putAll(jsonDataMerger.createEmptyJSON(unloadJSData)); extraData.putAll(jsonDataMerger.jsonToMap(data)); ioUtils.copy(jsonDataMerger.toJSON(extraData), jsonFile); } else logger.info("Saving JSON"); ioUtils.copy(data, jsonFile); } finally { unlockOnReportDir(reportDir); } }
public void saveJSONData(File reportDir, String data, List<ScriptCoverageCount> unloadJSData) { try { lockOnReportDir(reportDir); reportDir.mkdirs(); File jsonFile = new File(reportDir, "jscoverage.json"); SortedMap<String, FileData> extraData = new TreeMap<String, FileData>(); if (jsonFile.exists()) { logger.info("Saving/merging JSON with existing JSON"); String existingJSON = ioUtils.toString(jsonFile); extraData.putAll(jsonDataMerger.mergeJSONCoverageStrings(existingJSON, data)); ioUtils.copy(jsonDataMerger.toJSON(extraData), jsonFile); } else if (unloadJSData != null) { logger.info("Saving/merging JSON with unloaded JavaScript JSON"); //Only scan for unloaded JS if JSON not saved before extraData.putAll(jsonDataMerger.createEmptyJSON(unloadJSData)); extraData.putAll(jsonDataMerger.jsonToMap(data)); ioUtils.copy(jsonDataMerger.toJSON(extraData), jsonFile); } else { logger.info("Saving JSON"); ioUtils.copy(data, jsonFile); } } finally { unlockOnReportDir(reportDir); } }
diff --git a/src/org/java/android/BuyersGuideActivity.java b/src/org/java/android/BuyersGuideActivity.java index 179e71c..f97ecdb 100644 --- a/src/org/java/android/BuyersGuideActivity.java +++ b/src/org/java/android/BuyersGuideActivity.java @@ -1,56 +1,52 @@ package org.java.android; import java.util.ArrayList; import org.java.android.adapter.JsonArrayAdapter; import org.java.android.entities.JsonData; import org.java.android.task.JsonTask; import org.java.android.R; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.widget.ListView; import android.widget.ProgressBar; public class BuyersGuideActivity extends Activity { private static final String id = "id"; private static final String name = "name"; private static final String url = "url"; private static final String icon = "icon"; public static ProgressBar progressBar; public static ArrayList<JsonData> data; private static ListView listView; static JsonArrayAdapter adapter; private static Object object; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = (ListView)findViewById(R.id.listView1); progressBar = (ProgressBar)findViewById(R.id.progressBar); object = this; progressBar.setProgress(0); new JsonTask().execute(); listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Object object = listView.getItemAtPosition(position); JsonData jsonData = (JsonData) object; - Toast t = new Toast(getApplicationContext()); - t.setText(jsonData.getName()); - t.setDuration(100); - t.show(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(jsonData.getURL())); startActivity(intent); } }); } public static void fillData(){ BuyersGuideActivity.progressBar.setVisibility(ProgressBar.GONE); BuyersGuideActivity.adapter = new JsonArrayAdapter((Context)object,R.layout.list_item,data); BuyersGuideActivity.listView.setAdapter(BuyersGuideActivity.adapter); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = (ListView)findViewById(R.id.listView1); progressBar = (ProgressBar)findViewById(R.id.progressBar); object = this; progressBar.setProgress(0); new JsonTask().execute(); listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Object object = listView.getItemAtPosition(position); JsonData jsonData = (JsonData) object; Toast t = new Toast(getApplicationContext()); t.setText(jsonData.getName()); t.setDuration(100); t.show(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(jsonData.getURL())); startActivity(intent); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = (ListView)findViewById(R.id.listView1); progressBar = (ProgressBar)findViewById(R.id.progressBar); object = this; progressBar.setProgress(0); new JsonTask().execute(); listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Object object = listView.getItemAtPosition(position); JsonData jsonData = (JsonData) object; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(jsonData.getURL())); startActivity(intent); } }); }
diff --git a/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java b/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java index 5f5e4391..d1f0e7aa 100644 --- a/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java +++ b/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java @@ -1,559 +1,561 @@ /** * $RCSfile: ,v $ * $Revision: $ * $Date: $ * * Copyright (C) 2004-2010 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.sparkimpl.plugin.transcripts; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.TimerTask; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.text.html.HTMLEditorKit; import org.jdesktop.swingx.calendar.DateUtils; import org.jivesoftware.MainWindowListener; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.component.BackgroundPanel; import org.jivesoftware.spark.plugin.ContextMenuListener; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.ChatRoomButton; import org.jivesoftware.spark.ui.ChatRoomClosingListener; import org.jivesoftware.spark.ui.ChatRoomListener; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.ui.ContactList; import org.jivesoftware.spark.ui.VCardPanel; import org.jivesoftware.spark.ui.rooms.ChatRoomImpl; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.SwingWorker; import org.jivesoftware.spark.util.TaskEngine; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; /** * The <code>ChatTranscriptPlugin</code> is responsible for transcript handling within Spark. * * @author Derek DeMoro */ public class ChatTranscriptPlugin implements ChatRoomListener { private final String timeFormat = "HH:mm:ss"; private final String dateFormat = ((SimpleDateFormat)SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL)).toPattern(); private final SimpleDateFormat notificationDateFormatter; private final SimpleDateFormat messageDateFormatter; private HashMap<ChatRoom,Message> lastMessage = new HashMap<ChatRoom,Message>(); private JDialog Frame; /** * Register the listeners for transcript persistence. */ public ChatTranscriptPlugin() { SparkManager.getChatManager().addChatRoomListener(this); notificationDateFormatter = new SimpleDateFormat(dateFormat); messageDateFormatter = new SimpleDateFormat(timeFormat); final ContactList contactList = SparkManager.getWorkspace().getContactList(); final Action viewHistoryAction = new AbstractAction() { private static final long serialVersionUID = -6498776252446416099L; public void actionPerformed(ActionEvent actionEvent) { ContactItem item = contactList.getSelectedUsers().iterator().next(); final String jid = item.getJID(); showHistory(jid); } }; viewHistoryAction.putValue(Action.NAME, Res.getString("menuitem.view.contact.history")); viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16)); final Action showStatusMessageAction = new AbstractAction() { private static final long serialVersionUID = -5000370836304286019L; public void actionPerformed(ActionEvent actionEvent) { ContactItem item = contactList.getSelectedUsers().iterator().next(); showStatusMessage(item); } }; showStatusMessageAction.putValue(Action.NAME, Res.getString("menuitem.show.contact.statusmessage")); contactList.addContextMenuListener(new ContextMenuListener() { public void poppingUp(Object object, JPopupMenu popup) { if (object instanceof ContactItem) { popup.add(viewHistoryAction); popup.add(showStatusMessageAction); } } public void poppingDown(JPopupMenu popup) { } public boolean handleDefaultAction(MouseEvent e) { return false; } }); SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() { public void shutdown() { persistConversations(); } public void mainWindowActivated() { } public void mainWindowDeactivated() { } }); SparkManager.getConnection().addConnectionListener(new ConnectionListener() { public void connectionClosed() { } public void connectionClosedOnError(Exception e) { persistConversations(); } public void reconnectingIn(int i) { } public void reconnectionSuccessful() { } public void reconnectionFailed(Exception exception) { } }); } public void persistConversations() { for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) { if (room instanceof ChatRoomImpl) { ChatRoomImpl roomImpl = (ChatRoomImpl)room; if (roomImpl.isActive()) { persistChatRoom(roomImpl); } } } } public boolean canShutDown() { return true; } public void chatRoomOpened(final ChatRoom room) { LocalPreferences pref = SettingsManager.getLocalPreferences(); if (!pref.isChatHistoryEnabled()) { return; } final String jid = room.getRoomname(); File transcriptFile = ChatTranscripts.getTranscriptFile(jid); if (!transcriptFile.exists()) { return; } if (room instanceof ChatRoomImpl) { new ChatRoomDecorator(room); } } public void chatRoomLeft(ChatRoom room) { } public void chatRoomClosed(final ChatRoom room) { // Persist only agent to agent chat rooms. if (room.getChatType() == Message.Type.chat) { persistChatRoom(room); } } public void persistChatRoom(final ChatRoom room) { LocalPreferences pref = SettingsManager.getLocalPreferences(); if (!pref.isChatHistoryEnabled()) { return; } final String jid = room.getRoomname(); final List<Message> transcripts = room.getTranscripts(); ChatTranscript transcript = new ChatTranscript(); int count = 0; int i = 0; if (lastMessage.get(room) != null) { count = transcripts.indexOf(lastMessage.get(room)) + 1; } for (Message message : transcripts) { if (i < count) { i++; continue; } lastMessage.put(room,message); HistoryMessage history = new HistoryMessage(); history.setTo(message.getTo()); history.setFrom(message.getFrom()); history.setBody(message.getBody()); Date date = (Date)message.getProperty("date"); if (date != null) { history.setDate(date); } else { history.setDate(new Date()); } transcript.addHistoryMessage(history); } ChatTranscripts.appendToTranscript(jid, transcript); } public void chatRoomActivated(ChatRoom room) { } public void userHasJoined(ChatRoom room, String userid) { } public void userHasLeft(ChatRoom room, String userid) { } public void uninstall() { // Do nothing. } private void showHistory(final String jid) { SwingWorker transcriptLoader = new SwingWorker() { public Object construct() { String bareJID = StringUtils.parseBareAddress(jid); return ChatTranscripts.getChatTranscript(bareJID); } public void finished() { final JPanel mainPanel = new BackgroundPanel(); mainPanel.setLayout(new BorderLayout()); // add search text input final JPanel topPanel = new BackgroundPanel(); topPanel.setLayout(new GridBagLayout()); final VCardPanel vacardPanel = new VCardPanel(jid); final JTextField searchField = new JTextField(25); searchField.setText(Res.getString("message.search.for.history")); searchField.setToolTipText(Res.getString("message.search.for.history")); searchField.setForeground((Color) UIManager.get("TextField.lightforeground")); topPanel.add(vacardPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 5, 1, 1), 0, 0)); topPanel.add(searchField, new GridBagConstraints(1, 0, GridBagConstraints.REMAINDER, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, new Insets(1, 1, 6, 1), 0, 0)); mainPanel.add(topPanel, BorderLayout.NORTH); final JEditorPane window = new JEditorPane(); window.setEditorKit(new HTMLEditorKit()); window.setBackground(Color.white); final JScrollPane pane = new JScrollPane(window); pane.getVerticalScrollBar().setBlockIncrement(200); pane.getVerticalScrollBar().setUnitIncrement(20); mainPanel.add(pane, BorderLayout.CENTER); final JFrame frame = new JFrame(Res.getString("title.history.for", jid)); frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage()); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(mainPanel, BorderLayout.CENTER); frame.pack(); frame.setSize(600, 400); window.setCaretPosition(0); window.requestFocus(); GraphicUtils.centerWindowOnScreen(frame); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { window.setText(""); } }); window.setEditable(false); final StringBuilder builder = new StringBuilder(); builder.append("<html><body><table cellpadding=0 cellspacing=0>"); final TimerTask transcriptTask = new TimerTask() { public void run() { final ChatTranscript transcript = (ChatTranscript)get(); - final List<HistoryMessage> list = transcript.getMessages(); + final List<HistoryMessage> list = transcript.getMessage( + Res.getString("message.search.for.history").equals(searchField.getText()) + ? null : searchField.getText()); final String personalNickname = SparkManager.getUserManager().getNickname(); Date lastPost = null; String lastPerson = null; boolean initialized = false; for (HistoryMessage message : list) { String color = "blue"; String from = message.getFrom(); String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom()); String body = org.jivesoftware.spark.util.StringUtils.escapeHTMLTags(message.getBody()); if (nickname.equals(message.getFrom())) { String otherJID = StringUtils.parseBareAddress(message.getFrom()); String myJID = SparkManager.getSessionManager().getBareAddress(); if (otherJID.equals(myJID)) { nickname = personalNickname; } else { nickname = StringUtils.parseName(nickname); } } if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) { color = "red"; } long lastPostTime = lastPost != null ? lastPost.getTime() : 0; int diff = 0; if (DateUtils.getDaysDiff(lastPostTime, message .getDate().getTime()) != 0) { diff = DateUtils.getDaysDiff(lastPostTime, message.getDate().getTime()); } else { diff = DateUtils.getDayOfWeek(lastPostTime) - DateUtils.getDayOfWeek(message .getDate().getTime()); } if (diff != 0) { if (initialized) { builder.append("<tr><td><br></td></tr>"); } builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>").append(notificationDateFormatter.format(message.getDate())).append("</u></b></font></td></tr>"); lastPerson = null; initialized = true; } String value = "[" + messageDateFormatter.format(message.getDate()) + "]&nbsp;&nbsp; "; boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname); if (newInsertions) { builder.append("<tr valign=top><td colspan=2 nowrap>"); builder.append("<font size=4 color='").append(color).append("'><b>"); builder.append(nickname); builder.append("</b></font>"); builder.append("</td></tr>"); } builder.append("<tr valign=top><td align=left nowrap>"); builder.append(value); builder.append("</td><td align=left>"); builder.append(body); builder.append("</td></tr>"); lastPost = message.getDate(); lastPerson = nickname; } builder.append("</table></body></html>"); // Handle no history if (transcript.getMessages().size() == 0) { builder.append("<b>").append(Res.getString("message.no.history.found")).append("</b>"); } window.setText(builder.toString()); builder.replace(0, builder.length(), ""); } }; searchField.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if(e.getKeyChar() == KeyEvent.VK_ENTER) { TaskEngine.getInstance().schedule(transcriptTask, 10); searchField.requestFocus(); } } @Override public void keyPressed(KeyEvent e) { } }); searchField.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { searchField.setText(""); searchField.setForeground((Color) UIManager.get("TextField.foreground")); } public void focusLost(FocusEvent e) { searchField.setForeground((Color) UIManager.get("TextField.lightforeground")); searchField.setText(Res.getString("message.search.for.history")); } }); TaskEngine.getInstance().schedule(transcriptTask, 10); } }; transcriptLoader.start(); } private void showStatusMessage(ContactItem item) { Frame = new JDialog(); Frame.setTitle(item.getDisplayName() + " - Status"); JPanel pane = new JPanel(); JTextArea textArea = new JTextArea(5, 30); JButton btn_close = new JButton(Res.getString("button.close")); btn_close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Frame.setVisible(false); } }); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); pane.add(new JScrollPane(textArea)); Frame.setLayout(new BorderLayout()); Frame.add(pane, BorderLayout.CENTER); Frame.add(btn_close, BorderLayout.SOUTH); textArea.setEditable(false); textArea.setText(item.getStatus()); Frame.setLocationRelativeTo(SparkManager.getMainWindow()); Frame.setBounds(Frame.getX() - 175, Frame.getY() - 75, 350, 150); Frame.setSize(350, 150); Frame.setResizable(false); Frame.setVisible(true); } /** * Sort HistoryMessages by date. */ final Comparator dateComparator = new Comparator() { public int compare(Object messageOne, Object messageTwo) { final HistoryMessage historyMessageOne = (HistoryMessage)messageOne; final HistoryMessage historyMessageTwo = (HistoryMessage)messageTwo; long time1 = historyMessageOne.getDate().getTime(); long time2 = historyMessageTwo.getDate().getTime(); if (time1 < time2) { return 1; } else if (time1 > time2) { return -1; } return 0; } }; private class ChatRoomDecorator implements ActionListener, ChatRoomClosingListener { private ChatRoom chatRoom; private ChatRoomButton chatHistoryButton; private final LocalPreferences localPreferences; public ChatRoomDecorator(ChatRoom chatRoom) { this.chatRoom = chatRoom; chatRoom.addClosingListener(this); // Add History Button localPreferences = SettingsManager.getLocalPreferences(); if (!localPreferences.isChatHistoryEnabled()) { return; } chatHistoryButton = new ChatRoomButton(SparkRes.getImageIcon(SparkRes.HISTORY_24x24_IMAGE)); chatRoom.getToolBar().addChatRoomButton(chatHistoryButton); chatHistoryButton.setToolTipText(Res.getString("tooltip.view.history")); chatHistoryButton.addActionListener(this); } public void closing() { if (localPreferences.isChatHistoryEnabled()) { chatHistoryButton.removeActionListener(this); } chatRoom.removeClosingListener(this); } public void actionPerformed(ActionEvent e) { ChatRoomImpl roomImpl = (ChatRoomImpl)chatRoom; showHistory(roomImpl.getParticipantJID()); } } }
true
true
private void showHistory(final String jid) { SwingWorker transcriptLoader = new SwingWorker() { public Object construct() { String bareJID = StringUtils.parseBareAddress(jid); return ChatTranscripts.getChatTranscript(bareJID); } public void finished() { final JPanel mainPanel = new BackgroundPanel(); mainPanel.setLayout(new BorderLayout()); // add search text input final JPanel topPanel = new BackgroundPanel(); topPanel.setLayout(new GridBagLayout()); final VCardPanel vacardPanel = new VCardPanel(jid); final JTextField searchField = new JTextField(25); searchField.setText(Res.getString("message.search.for.history")); searchField.setToolTipText(Res.getString("message.search.for.history")); searchField.setForeground((Color) UIManager.get("TextField.lightforeground")); topPanel.add(vacardPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 5, 1, 1), 0, 0)); topPanel.add(searchField, new GridBagConstraints(1, 0, GridBagConstraints.REMAINDER, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, new Insets(1, 1, 6, 1), 0, 0)); mainPanel.add(topPanel, BorderLayout.NORTH); final JEditorPane window = new JEditorPane(); window.setEditorKit(new HTMLEditorKit()); window.setBackground(Color.white); final JScrollPane pane = new JScrollPane(window); pane.getVerticalScrollBar().setBlockIncrement(200); pane.getVerticalScrollBar().setUnitIncrement(20); mainPanel.add(pane, BorderLayout.CENTER); final JFrame frame = new JFrame(Res.getString("title.history.for", jid)); frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage()); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(mainPanel, BorderLayout.CENTER); frame.pack(); frame.setSize(600, 400); window.setCaretPosition(0); window.requestFocus(); GraphicUtils.centerWindowOnScreen(frame); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { window.setText(""); } }); window.setEditable(false); final StringBuilder builder = new StringBuilder(); builder.append("<html><body><table cellpadding=0 cellspacing=0>"); final TimerTask transcriptTask = new TimerTask() { public void run() { final ChatTranscript transcript = (ChatTranscript)get(); final List<HistoryMessage> list = transcript.getMessages(); final String personalNickname = SparkManager.getUserManager().getNickname(); Date lastPost = null; String lastPerson = null; boolean initialized = false; for (HistoryMessage message : list) { String color = "blue"; String from = message.getFrom(); String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom()); String body = org.jivesoftware.spark.util.StringUtils.escapeHTMLTags(message.getBody()); if (nickname.equals(message.getFrom())) { String otherJID = StringUtils.parseBareAddress(message.getFrom()); String myJID = SparkManager.getSessionManager().getBareAddress(); if (otherJID.equals(myJID)) { nickname = personalNickname; } else { nickname = StringUtils.parseName(nickname); } } if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) { color = "red"; } long lastPostTime = lastPost != null ? lastPost.getTime() : 0; int diff = 0; if (DateUtils.getDaysDiff(lastPostTime, message .getDate().getTime()) != 0) { diff = DateUtils.getDaysDiff(lastPostTime, message.getDate().getTime()); } else { diff = DateUtils.getDayOfWeek(lastPostTime) - DateUtils.getDayOfWeek(message .getDate().getTime()); } if (diff != 0) { if (initialized) { builder.append("<tr><td><br></td></tr>"); } builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>").append(notificationDateFormatter.format(message.getDate())).append("</u></b></font></td></tr>"); lastPerson = null; initialized = true; } String value = "[" + messageDateFormatter.format(message.getDate()) + "]&nbsp;&nbsp; "; boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname); if (newInsertions) { builder.append("<tr valign=top><td colspan=2 nowrap>"); builder.append("<font size=4 color='").append(color).append("'><b>"); builder.append(nickname); builder.append("</b></font>"); builder.append("</td></tr>"); } builder.append("<tr valign=top><td align=left nowrap>"); builder.append(value); builder.append("</td><td align=left>"); builder.append(body); builder.append("</td></tr>"); lastPost = message.getDate(); lastPerson = nickname; } builder.append("</table></body></html>"); // Handle no history if (transcript.getMessages().size() == 0) { builder.append("<b>").append(Res.getString("message.no.history.found")).append("</b>"); } window.setText(builder.toString()); builder.replace(0, builder.length(), ""); } }; searchField.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if(e.getKeyChar() == KeyEvent.VK_ENTER) { TaskEngine.getInstance().schedule(transcriptTask, 10); searchField.requestFocus(); } } @Override public void keyPressed(KeyEvent e) { } }); searchField.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { searchField.setText(""); searchField.setForeground((Color) UIManager.get("TextField.foreground")); } public void focusLost(FocusEvent e) { searchField.setForeground((Color) UIManager.get("TextField.lightforeground")); searchField.setText(Res.getString("message.search.for.history")); } }); TaskEngine.getInstance().schedule(transcriptTask, 10); } }; transcriptLoader.start(); }
private void showHistory(final String jid) { SwingWorker transcriptLoader = new SwingWorker() { public Object construct() { String bareJID = StringUtils.parseBareAddress(jid); return ChatTranscripts.getChatTranscript(bareJID); } public void finished() { final JPanel mainPanel = new BackgroundPanel(); mainPanel.setLayout(new BorderLayout()); // add search text input final JPanel topPanel = new BackgroundPanel(); topPanel.setLayout(new GridBagLayout()); final VCardPanel vacardPanel = new VCardPanel(jid); final JTextField searchField = new JTextField(25); searchField.setText(Res.getString("message.search.for.history")); searchField.setToolTipText(Res.getString("message.search.for.history")); searchField.setForeground((Color) UIManager.get("TextField.lightforeground")); topPanel.add(vacardPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 5, 1, 1), 0, 0)); topPanel.add(searchField, new GridBagConstraints(1, 0, GridBagConstraints.REMAINDER, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, new Insets(1, 1, 6, 1), 0, 0)); mainPanel.add(topPanel, BorderLayout.NORTH); final JEditorPane window = new JEditorPane(); window.setEditorKit(new HTMLEditorKit()); window.setBackground(Color.white); final JScrollPane pane = new JScrollPane(window); pane.getVerticalScrollBar().setBlockIncrement(200); pane.getVerticalScrollBar().setUnitIncrement(20); mainPanel.add(pane, BorderLayout.CENTER); final JFrame frame = new JFrame(Res.getString("title.history.for", jid)); frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage()); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(mainPanel, BorderLayout.CENTER); frame.pack(); frame.setSize(600, 400); window.setCaretPosition(0); window.requestFocus(); GraphicUtils.centerWindowOnScreen(frame); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { window.setText(""); } }); window.setEditable(false); final StringBuilder builder = new StringBuilder(); builder.append("<html><body><table cellpadding=0 cellspacing=0>"); final TimerTask transcriptTask = new TimerTask() { public void run() { final ChatTranscript transcript = (ChatTranscript)get(); final List<HistoryMessage> list = transcript.getMessage( Res.getString("message.search.for.history").equals(searchField.getText()) ? null : searchField.getText()); final String personalNickname = SparkManager.getUserManager().getNickname(); Date lastPost = null; String lastPerson = null; boolean initialized = false; for (HistoryMessage message : list) { String color = "blue"; String from = message.getFrom(); String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom()); String body = org.jivesoftware.spark.util.StringUtils.escapeHTMLTags(message.getBody()); if (nickname.equals(message.getFrom())) { String otherJID = StringUtils.parseBareAddress(message.getFrom()); String myJID = SparkManager.getSessionManager().getBareAddress(); if (otherJID.equals(myJID)) { nickname = personalNickname; } else { nickname = StringUtils.parseName(nickname); } } if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) { color = "red"; } long lastPostTime = lastPost != null ? lastPost.getTime() : 0; int diff = 0; if (DateUtils.getDaysDiff(lastPostTime, message .getDate().getTime()) != 0) { diff = DateUtils.getDaysDiff(lastPostTime, message.getDate().getTime()); } else { diff = DateUtils.getDayOfWeek(lastPostTime) - DateUtils.getDayOfWeek(message .getDate().getTime()); } if (diff != 0) { if (initialized) { builder.append("<tr><td><br></td></tr>"); } builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>").append(notificationDateFormatter.format(message.getDate())).append("</u></b></font></td></tr>"); lastPerson = null; initialized = true; } String value = "[" + messageDateFormatter.format(message.getDate()) + "]&nbsp;&nbsp; "; boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname); if (newInsertions) { builder.append("<tr valign=top><td colspan=2 nowrap>"); builder.append("<font size=4 color='").append(color).append("'><b>"); builder.append(nickname); builder.append("</b></font>"); builder.append("</td></tr>"); } builder.append("<tr valign=top><td align=left nowrap>"); builder.append(value); builder.append("</td><td align=left>"); builder.append(body); builder.append("</td></tr>"); lastPost = message.getDate(); lastPerson = nickname; } builder.append("</table></body></html>"); // Handle no history if (transcript.getMessages().size() == 0) { builder.append("<b>").append(Res.getString("message.no.history.found")).append("</b>"); } window.setText(builder.toString()); builder.replace(0, builder.length(), ""); } }; searchField.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if(e.getKeyChar() == KeyEvent.VK_ENTER) { TaskEngine.getInstance().schedule(transcriptTask, 10); searchField.requestFocus(); } } @Override public void keyPressed(KeyEvent e) { } }); searchField.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { searchField.setText(""); searchField.setForeground((Color) UIManager.get("TextField.foreground")); } public void focusLost(FocusEvent e) { searchField.setForeground((Color) UIManager.get("TextField.lightforeground")); searchField.setText(Res.getString("message.search.for.history")); } }); TaskEngine.getInstance().schedule(transcriptTask, 10); } }; transcriptLoader.start(); }
diff --git a/src/com/example/testgame/MainActivity.java b/src/com/example/testgame/MainActivity.java index 62c58e8..26c54b3 100644 --- a/src/com/example/testgame/MainActivity.java +++ b/src/com/example/testgame/MainActivity.java @@ -1,264 +1,264 @@ package com.example.testgame; import com.testgame.scene.*; import org.andengine.engine.Engine; import org.andengine.engine.LimitedFPSEngine; import org.andengine.engine.camera.BoundCamera; import org.andengine.engine.camera.SmoothCamera; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.engine.options.EngineOptions; import org.andengine.engine.options.ScreenOrientation; import org.andengine.engine.options.WakeLockOptions; import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy; import org.andengine.entity.scene.Scene; import org.andengine.input.touch.detector.ScrollDetector; import org.andengine.ui.activity.BaseGameActivity; import org.json.JSONException; import org.json.JSONObject; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import android.view.KeyEvent; import com.parse.Parse; import com.parse.ParseFacebookUtils; import com.parse.ParsePush; import com.parse.ParseUser; import com.testgame.resource.ResourcesManager; import com.testgame.scene.SceneManager; public class MainActivity extends BaseGameActivity { final int mCameraWidth = 480; final int mCameraHeight = 800; private BoundCamera mCamera; private BroadcastReceiver newTurn; private IntentFilter turnIntent; private ResourcesManager resourcesManager; @Override public Engine onCreateEngine(EngineOptions pEngineOptions) { return new LimitedFPSEngine(pEngineOptions, 60); } @Override public EngineOptions onCreateEngineOptions() { newTurn = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { if(resourcesManager.inGame == false){ return; } JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(json.getString("deviceId").equals(resourcesManager.opponentDeviceID)){ if(SceneManager.getInstance().getGameScene() != null) Log.d("Turn", "New Turn starting"); ((GameScene) SceneManager.getInstance().getGameScene()).startCompTurn(); } } catch(Exception e){ } } }; BroadcastReceiver invite = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(resourcesManager.inGame == true){ try { JSONObject data = new JSONObject("{\"alert\": \"Invitation Denied\", \"action\": \"com.testgame.CANCEL\", \"name\": \""+ParseUser.getCurrentUser().getString("Name")+"\"}"); ParsePush push = new ParsePush(); push.setChannel("user_"+json.getString("userid")); push.setData(data); push.sendInBackground(); return; } catch (JSONException e) { e.printStackTrace(); } } if(SceneManager.getInstance().getMainMenuScene() != null) ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createInvite(json); } catch (JSONException e) { e.printStackTrace(); } } }; BroadcastReceiver deny = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(SceneManager.getInstance().getMainMenuScene() != null) - ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createDialog(json.getString("name")+ "does not wish to play."); + ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createDialog(json.getString("name")+ " does not wish to play."); } catch (JSONException e) { e.printStackTrace(); } } }; BroadcastReceiver accept = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(SceneManager.getInstance().getMainMenuScene() != null) ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createAcceptDialog(json); } catch (JSONException e) { e.printStackTrace(); } } }; BroadcastReceiver quit = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(SceneManager.getInstance().getGameScene() != null && resourcesManager.gameId.equals(json.getString("gameId"))) ((GameScene) SceneManager.getInstance().getGameScene()).quitDialog("Opponent has quit the game! You win!"); } catch(Exception e){ } } }; IntentFilter inviteFilter = new IntentFilter(); inviteFilter.addAction("com.testgame.INVITE"); IntentFilter denyFilter = new IntentFilter(); denyFilter.addAction("com.testgame.CANCEL"); IntentFilter acceptFilter = new IntentFilter(); acceptFilter.addAction("com.testgame.ACCEPT"); IntentFilter quitFilter = new IntentFilter(); quitFilter.addAction("com.testgame.QUIT"); turnIntent = new IntentFilter(); turnIntent.addAction("com.testgame.NEXT_TURN"); registerReceiver(newTurn, turnIntent); registerReceiver(invite, inviteFilter); registerReceiver(deny, denyFilter); registerReceiver(accept, acceptFilter); registerReceiver(quit, quitFilter); Parse.initialize(this, "QFJ1DxJol0sSIq068kUDgbE5IVDnADHO2tJbiRQH", "ARuOWkguSH0ndGjMVCDcDc39hBsNQ3J6g6X7slpY"); ParseFacebookUtils.initialize("248250035306788"); mCamera = new SmoothCamera(0, 0, mCameraWidth, mCameraHeight, 500, 500, 50.0f); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), this.mCamera); engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true); engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON); return engineOptions; } @Override public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) { ResourcesManager.prepareManager(mEngine, this, mCamera, getVertexBufferObjectManager()); resourcesManager = ResourcesManager.getInstance(); pOnCreateResourcesCallback.onCreateResourcesFinished(); } @Override public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) { SceneManager.getInstance().createSplashScene(pOnCreateSceneCallback); } @Override public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback) { mEngine.registerUpdateHandler(new TimerHandler(2f, new ITimerCallback() { public void onTimePassed(final TimerHandler pTimerHandler) { mEngine.unregisterUpdateHandler(pTimerHandler); SceneManager.getInstance().createMenuScene(); } })); pOnPopulateSceneCallback.onPopulateSceneFinished(); } @Override protected void onDestroy() { super.onDestroy(); System.exit(0); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { SceneManager.getInstance().getCurrentScene().onBackKeyPressed(); } return false; } public void onScroll(ScrollDetector pScollDetector, int pPointerID, float pDistanceX, float pDistanceY) { mCamera.setCenter(mCamera.getCenterX() - pDistanceX, mCamera.getCenterY() - pDistanceY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data); } @Override public void onPause() { super.onPause(); if (resourcesManager != null) resourcesManager.pause_music(); } @Override public void onResume() { super.onResume(); if (resourcesManager != null)resourcesManager.play_music(); } }
true
true
public EngineOptions onCreateEngineOptions() { newTurn = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { if(resourcesManager.inGame == false){ return; } JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(json.getString("deviceId").equals(resourcesManager.opponentDeviceID)){ if(SceneManager.getInstance().getGameScene() != null) Log.d("Turn", "New Turn starting"); ((GameScene) SceneManager.getInstance().getGameScene()).startCompTurn(); } } catch(Exception e){ } } }; BroadcastReceiver invite = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(resourcesManager.inGame == true){ try { JSONObject data = new JSONObject("{\"alert\": \"Invitation Denied\", \"action\": \"com.testgame.CANCEL\", \"name\": \""+ParseUser.getCurrentUser().getString("Name")+"\"}"); ParsePush push = new ParsePush(); push.setChannel("user_"+json.getString("userid")); push.setData(data); push.sendInBackground(); return; } catch (JSONException e) { e.printStackTrace(); } } if(SceneManager.getInstance().getMainMenuScene() != null) ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createInvite(json); } catch (JSONException e) { e.printStackTrace(); } } }; BroadcastReceiver deny = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(SceneManager.getInstance().getMainMenuScene() != null) ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createDialog(json.getString("name")+ "does not wish to play."); } catch (JSONException e) { e.printStackTrace(); } } }; BroadcastReceiver accept = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(SceneManager.getInstance().getMainMenuScene() != null) ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createAcceptDialog(json); } catch (JSONException e) { e.printStackTrace(); } } }; BroadcastReceiver quit = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(SceneManager.getInstance().getGameScene() != null && resourcesManager.gameId.equals(json.getString("gameId"))) ((GameScene) SceneManager.getInstance().getGameScene()).quitDialog("Opponent has quit the game! You win!"); } catch(Exception e){ } } }; IntentFilter inviteFilter = new IntentFilter(); inviteFilter.addAction("com.testgame.INVITE"); IntentFilter denyFilter = new IntentFilter(); denyFilter.addAction("com.testgame.CANCEL"); IntentFilter acceptFilter = new IntentFilter(); acceptFilter.addAction("com.testgame.ACCEPT"); IntentFilter quitFilter = new IntentFilter(); quitFilter.addAction("com.testgame.QUIT"); turnIntent = new IntentFilter(); turnIntent.addAction("com.testgame.NEXT_TURN"); registerReceiver(newTurn, turnIntent); registerReceiver(invite, inviteFilter); registerReceiver(deny, denyFilter); registerReceiver(accept, acceptFilter); registerReceiver(quit, quitFilter); Parse.initialize(this, "QFJ1DxJol0sSIq068kUDgbE5IVDnADHO2tJbiRQH", "ARuOWkguSH0ndGjMVCDcDc39hBsNQ3J6g6X7slpY"); ParseFacebookUtils.initialize("248250035306788"); mCamera = new SmoothCamera(0, 0, mCameraWidth, mCameraHeight, 500, 500, 50.0f); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), this.mCamera); engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true); engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON); return engineOptions; }
public EngineOptions onCreateEngineOptions() { newTurn = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { if(resourcesManager.inGame == false){ return; } JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(json.getString("deviceId").equals(resourcesManager.opponentDeviceID)){ if(SceneManager.getInstance().getGameScene() != null) Log.d("Turn", "New Turn starting"); ((GameScene) SceneManager.getInstance().getGameScene()).startCompTurn(); } } catch(Exception e){ } } }; BroadcastReceiver invite = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(resourcesManager.inGame == true){ try { JSONObject data = new JSONObject("{\"alert\": \"Invitation Denied\", \"action\": \"com.testgame.CANCEL\", \"name\": \""+ParseUser.getCurrentUser().getString("Name")+"\"}"); ParsePush push = new ParsePush(); push.setChannel("user_"+json.getString("userid")); push.setData(data); push.sendInBackground(); return; } catch (JSONException e) { e.printStackTrace(); } } if(SceneManager.getInstance().getMainMenuScene() != null) ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createInvite(json); } catch (JSONException e) { e.printStackTrace(); } } }; BroadcastReceiver deny = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(SceneManager.getInstance().getMainMenuScene() != null) ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createDialog(json.getString("name")+ " does not wish to play."); } catch (JSONException e) { e.printStackTrace(); } } }; BroadcastReceiver accept = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(SceneManager.getInstance().getMainMenuScene() != null) ((MainMenuScene) SceneManager.getInstance().getMainMenuScene()).createAcceptDialog(json); } catch (JSONException e) { e.printStackTrace(); } } }; BroadcastReceiver quit = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { JSONObject json; try { json = new JSONObject(intent.getExtras().getString("com.parse.Data")); if(SceneManager.getInstance().getGameScene() != null && resourcesManager.gameId.equals(json.getString("gameId"))) ((GameScene) SceneManager.getInstance().getGameScene()).quitDialog("Opponent has quit the game! You win!"); } catch(Exception e){ } } }; IntentFilter inviteFilter = new IntentFilter(); inviteFilter.addAction("com.testgame.INVITE"); IntentFilter denyFilter = new IntentFilter(); denyFilter.addAction("com.testgame.CANCEL"); IntentFilter acceptFilter = new IntentFilter(); acceptFilter.addAction("com.testgame.ACCEPT"); IntentFilter quitFilter = new IntentFilter(); quitFilter.addAction("com.testgame.QUIT"); turnIntent = new IntentFilter(); turnIntent.addAction("com.testgame.NEXT_TURN"); registerReceiver(newTurn, turnIntent); registerReceiver(invite, inviteFilter); registerReceiver(deny, denyFilter); registerReceiver(accept, acceptFilter); registerReceiver(quit, quitFilter); Parse.initialize(this, "QFJ1DxJol0sSIq068kUDgbE5IVDnADHO2tJbiRQH", "ARuOWkguSH0ndGjMVCDcDc39hBsNQ3J6g6X7slpY"); ParseFacebookUtils.initialize("248250035306788"); mCamera = new SmoothCamera(0, 0, mCameraWidth, mCameraHeight, 500, 500, 50.0f); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), this.mCamera); engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true); engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON); return engineOptions; }
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java index e532e8b79..d0ae64ed0 100644 --- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java +++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java @@ -1,104 +1,103 @@ package com.itmill.toolkit.terminal.gwt.client.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.Widget; import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection; import com.itmill.toolkit.terminal.gwt.client.CaptionWrapper; import com.itmill.toolkit.terminal.gwt.client.Container; import com.itmill.toolkit.terminal.gwt.client.Paintable; import com.itmill.toolkit.terminal.gwt.client.UIDL; public class IGridLayout extends FlexTable implements Paintable, Container { /** Widget to captionwrapper map */ private HashMap widgetToCaptionWrapper = new HashMap(); public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { if (client.updateComponent(this, uidl, false)) { return; } clear(); if (uidl.hasAttribute("caption")) { setTitle(uidl.getStringAttribute("caption")); } int row = 0, column = 0; ArrayList detachdedPaintables = new ArrayList(); for (Iterator i = uidl.getChildIterator(); i.hasNext();) { UIDL r = (UIDL) i.next(); if ("gr".equals(r.getTag())) { - row++; column = 0; for (Iterator j = r.getChildIterator(); j.hasNext();) { UIDL c = (UIDL) j.next(); if ("gc".equals(c.getTag())) { - column++; int w; if (c.hasAttribute("w")) { w = c.getIntAttribute("w"); } else { w = 1; } ((FlexCellFormatter) getCellFormatter()).setColSpan( row, column, w); UIDL u = c.getChildUIDL(0); if (u != null) { Widget child = client.getWidget(u); prepareCell(row, column); Widget oldChild = getWidget(row, column); if (child != oldChild) { if (oldChild != null) { CaptionWrapper cw = (CaptionWrapper) oldChild; detachdedPaintables.add(cw.getPaintable()); widgetToCaptionWrapper.remove(oldChild); } CaptionWrapper wrapper = new CaptionWrapper( (Paintable) child, client); setWidget(row, column, wrapper); widgetToCaptionWrapper.put(child, wrapper); } ((Paintable) child).updateFromUIDL(u, client); } - column += w - 1; + column += w; } } + row++; } } // for loop detached widgets and unregister them unless they are // attached (case of widget which is moved to another cell) for (Iterator it = detachdedPaintables.iterator(); it.hasNext();) { Widget w = (Widget) it.next(); if (!w.isAttached()) { client.unregisterPaintable((Paintable) w); } } } public boolean hasChildComponent(Widget component) { if (widgetToCaptionWrapper.containsKey(component)) { return true; } return false; } public void replaceChildComponent(Widget oldComponent, Widget newComponent) { // TODO Auto-generated method stub } public void updateCaption(Paintable component, UIDL uidl) { CaptionWrapper wrapper = (CaptionWrapper) widgetToCaptionWrapper .get(component); wrapper.updateCaption(uidl); } }
false
true
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { if (client.updateComponent(this, uidl, false)) { return; } clear(); if (uidl.hasAttribute("caption")) { setTitle(uidl.getStringAttribute("caption")); } int row = 0, column = 0; ArrayList detachdedPaintables = new ArrayList(); for (Iterator i = uidl.getChildIterator(); i.hasNext();) { UIDL r = (UIDL) i.next(); if ("gr".equals(r.getTag())) { row++; column = 0; for (Iterator j = r.getChildIterator(); j.hasNext();) { UIDL c = (UIDL) j.next(); if ("gc".equals(c.getTag())) { column++; int w; if (c.hasAttribute("w")) { w = c.getIntAttribute("w"); } else { w = 1; } ((FlexCellFormatter) getCellFormatter()).setColSpan( row, column, w); UIDL u = c.getChildUIDL(0); if (u != null) { Widget child = client.getWidget(u); prepareCell(row, column); Widget oldChild = getWidget(row, column); if (child != oldChild) { if (oldChild != null) { CaptionWrapper cw = (CaptionWrapper) oldChild; detachdedPaintables.add(cw.getPaintable()); widgetToCaptionWrapper.remove(oldChild); } CaptionWrapper wrapper = new CaptionWrapper( (Paintable) child, client); setWidget(row, column, wrapper); widgetToCaptionWrapper.put(child, wrapper); } ((Paintable) child).updateFromUIDL(u, client); } column += w - 1; } } } } // for loop detached widgets and unregister them unless they are // attached (case of widget which is moved to another cell) for (Iterator it = detachdedPaintables.iterator(); it.hasNext();) { Widget w = (Widget) it.next(); if (!w.isAttached()) { client.unregisterPaintable((Paintable) w); } } }
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { if (client.updateComponent(this, uidl, false)) { return; } clear(); if (uidl.hasAttribute("caption")) { setTitle(uidl.getStringAttribute("caption")); } int row = 0, column = 0; ArrayList detachdedPaintables = new ArrayList(); for (Iterator i = uidl.getChildIterator(); i.hasNext();) { UIDL r = (UIDL) i.next(); if ("gr".equals(r.getTag())) { column = 0; for (Iterator j = r.getChildIterator(); j.hasNext();) { UIDL c = (UIDL) j.next(); if ("gc".equals(c.getTag())) { int w; if (c.hasAttribute("w")) { w = c.getIntAttribute("w"); } else { w = 1; } ((FlexCellFormatter) getCellFormatter()).setColSpan( row, column, w); UIDL u = c.getChildUIDL(0); if (u != null) { Widget child = client.getWidget(u); prepareCell(row, column); Widget oldChild = getWidget(row, column); if (child != oldChild) { if (oldChild != null) { CaptionWrapper cw = (CaptionWrapper) oldChild; detachdedPaintables.add(cw.getPaintable()); widgetToCaptionWrapper.remove(oldChild); } CaptionWrapper wrapper = new CaptionWrapper( (Paintable) child, client); setWidget(row, column, wrapper); widgetToCaptionWrapper.put(child, wrapper); } ((Paintable) child).updateFromUIDL(u, client); } column += w; } } row++; } } // for loop detached widgets and unregister them unless they are // attached (case of widget which is moved to another cell) for (Iterator it = detachdedPaintables.iterator(); it.hasNext();) { Widget w = (Widget) it.next(); if (!w.isAttached()) { client.unregisterPaintable((Paintable) w); } } }
diff --git a/src/net/sf/gogui/thumbnail/Main.java b/src/net/sf/gogui/thumbnail/Main.java index 6c388b9f..6a468d14 100644 --- a/src/net/sf/gogui/thumbnail/Main.java +++ b/src/net/sf/gogui/thumbnail/Main.java @@ -1,79 +1,80 @@ //---------------------------------------------------------------------------- // $Id$ // $Source$ //---------------------------------------------------------------------------- package net.sf.gogui.thumbnail; import java.io.File; import java.io.OutputStream; import java.util.ArrayList; import net.sf.gogui.utils.Options; import net.sf.gogui.utils.StringUtils; import net.sf.gogui.version.Version; //---------------------------------------------------------------------------- /** SgfThumbnail main function. */ public final class Main { /** SgfThumbnail main function. */ public static void main(String[] args) { try { String options[] = { "help", "verbose", "version", }; Options opt = Options.parse(args, options); if (opt.isSet("help")) { printUsage(System.out); System.exit(0); } if (opt.isSet("version")) { System.out.println("SgfThumbnail " + Version.get()); System.exit(0); } boolean verbose = opt.isSet("verbose"); ArrayList arguments = opt.getArguments(); if (arguments.size() == 0 || arguments.size() > 2) { printUsage(System.err); System.exit(-1); } File input = new File((String)arguments.get(0)); File output = null; if (arguments.size() == 2) output = new File((String)arguments.get(1)); Thumbnail thumbnail = new Thumbnail(verbose); - thumbnail.create(input, output); + if (! thumbnail.create(input, output)) + System.exit(-1); } catch (Throwable t) { StringUtils.printException(t); System.exit(-1); } } /** Make constructor unavailable; class is for namespace only. */ private Main() { } private static void printUsage(OutputStream out) { String helpText = "Usage: java -jar sgfthumbnail.jar [options] input [output]\n" + "Options:\n" + "-help Print help and exit\n" + "-verbose Print logging messages to stderr\n" + "-version Print version and exit\n"; System.out.print(out); } } //----------------------------------------------------------------------------
true
true
public static void main(String[] args) { try { String options[] = { "help", "verbose", "version", }; Options opt = Options.parse(args, options); if (opt.isSet("help")) { printUsage(System.out); System.exit(0); } if (opt.isSet("version")) { System.out.println("SgfThumbnail " + Version.get()); System.exit(0); } boolean verbose = opt.isSet("verbose"); ArrayList arguments = opt.getArguments(); if (arguments.size() == 0 || arguments.size() > 2) { printUsage(System.err); System.exit(-1); } File input = new File((String)arguments.get(0)); File output = null; if (arguments.size() == 2) output = new File((String)arguments.get(1)); Thumbnail thumbnail = new Thumbnail(verbose); thumbnail.create(input, output); } catch (Throwable t) { StringUtils.printException(t); System.exit(-1); } }
public static void main(String[] args) { try { String options[] = { "help", "verbose", "version", }; Options opt = Options.parse(args, options); if (opt.isSet("help")) { printUsage(System.out); System.exit(0); } if (opt.isSet("version")) { System.out.println("SgfThumbnail " + Version.get()); System.exit(0); } boolean verbose = opt.isSet("verbose"); ArrayList arguments = opt.getArguments(); if (arguments.size() == 0 || arguments.size() > 2) { printUsage(System.err); System.exit(-1); } File input = new File((String)arguments.get(0)); File output = null; if (arguments.size() == 2) output = new File((String)arguments.get(1)); Thumbnail thumbnail = new Thumbnail(verbose); if (! thumbnail.create(input, output)) System.exit(-1); } catch (Throwable t) { StringUtils.printException(t); System.exit(-1); } }
diff --git a/tests/frontend/org/voltdb/compiler/TestVoltCompiler.java b/tests/frontend/org/voltdb/compiler/TestVoltCompiler.java index 7de88f77b..8f8aabdfe 100644 --- a/tests/frontend/org/voltdb/compiler/TestVoltCompiler.java +++ b/tests/frontend/org/voltdb/compiler/TestVoltCompiler.java @@ -1,2397 +1,2397 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2012 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb.compiler; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import junit.framework.TestCase; import org.apache.commons.lang3.StringUtils; import org.voltdb.ProcInfoData; import org.voltdb.VoltDB.Configuration; import org.voltdb.benchmark.tpcc.TPCCProjectBuilder; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Connector; import org.voltdb.catalog.Database; import org.voltdb.catalog.Group; import org.voltdb.catalog.GroupRef; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.SnapshotSchedule; import org.voltdb.catalog.Table; import org.voltdb.compiler.VoltCompiler.Feedback; import org.voltdb.types.IndexType; import org.voltdb.utils.BuildDirectoryUtils; import org.voltdb.utils.CatalogUtil; public class TestVoltCompiler extends TestCase { String nothing_jar; String testout_jar; @Override public void setUp() { nothing_jar = BuildDirectoryUtils.getBuildDirectoryPath() + File.pathSeparator + "nothing.jar"; testout_jar = BuildDirectoryUtils.getBuildDirectoryPath() + File.pathSeparator + "testout.jar"; } @Override public void tearDown() { File njar = new File(nothing_jar); njar.delete(); File tjar = new File(testout_jar); tjar.delete(); } public void testBrokenLineParsing() throws IOException { final String simpleSchema1 = "create table table1r_el (pkey integer, column2_integer integer, PRIMARY KEY(pkey));\n" + "create view v_table1r_el (column2_integer, num_rows) as\n" + "select column2_integer as column2_integer,\n" + "count(*) as num_rows\n" + "from table1r_el\n" + "group by column2_integer;\n" + "create view v_table1r_el2 (column2_integer, num_rows) as\n" + "select column2_integer as column2_integer,\n" + "count(*) as num_rows\n" + "from table1r_el\n" + "group by column2_integer\n;\n"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema1); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas>" + "<schema path='" + schemaPath + "' />" + "</schemas>" + "<procedures>" + "<procedure class='Foo'>" + "<sql>select * from table1r_el;</sql>" + "</procedure>" + "</procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); } public void testUTF8XMLFromHSQL() throws IOException { final String simpleSchema = "create table blah (pkey integer not null, strval varchar(200), PRIMARY KEY(pkey));\n"; VoltProjectBuilder pb = new VoltProjectBuilder(); pb.addLiteralSchema(simpleSchema); pb.addStmtProcedure("utf8insert", "insert into blah values(1, 'něco za nic')"); pb.addPartitionInfo("blah", "pkey"); boolean success = pb.compile(Configuration.getPathToCatalogForTest("utf8xml.jar")); assertTrue(success); } private boolean isFeedbackPresent(String expectedError, ArrayList<Feedback> fbs) { for (Feedback fb : fbs) { if (fb.getStandardFeedbackLine().contains(expectedError)) { return true; } } return false; } public void testMismatchedPartitionParams() throws IOException { String expectedError; ArrayList<Feedback> fbs; fbs = checkPartitionParam("CREATE TABLE PKEY_BIGINT ( PKEY BIGINT NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_BIGINT ON COLUMN PKEY;", "org.voltdb.compiler.procedures.PartitionParamBigint", "PKEY_BIGINT"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamBigint may cause overflow or loss of precision.\n" + "Partition column is type VoltType.BIGINT and partition parameter is type VoltType.STRING"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_BIGINT ( PKEY BIGINT NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_BIGINT ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.PartitionParamBigint;", "PKEY_BIGINT"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamBigint may cause overflow or loss of precision.\n" + "Partition column is type VoltType.BIGINT and partition parameter is type VoltType.STRING"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_BIGINT ( PKEY BIGINT NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_BIGINT ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamBigint;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamBigint ON TABLE PKEY_BIGINT COLUMN PKEY;", "PKEY_BIGINT"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamBigint may cause overflow or loss of precision.\n" + "Partition column is type VoltType.BIGINT and partition parameter is type VoltType.STRING"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;", "org.voltdb.compiler.procedures.PartitionParamInteger", "PKEY_INTEGER"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamInteger may cause overflow or loss of precision.\n" + "Partition column is type VoltType.INTEGER and partition parameter " + "is type VoltType.BIGINT"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.PartitionParamInteger;", "PKEY_INTEGER"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamInteger may cause overflow or loss of precision.\n" + "Partition column is type VoltType.INTEGER and partition parameter " + "is type VoltType.BIGINT"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;", "PKEY_INTEGER"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger may cause overflow or loss of precision.\n" + "Partition column is type VoltType.INTEGER and partition parameter " + "is type VoltType.BIGINT"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_SMALLINT ( PKEY SMALLINT NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_SMALLINT ON COLUMN PKEY;", "org.voltdb.compiler.procedures.PartitionParamSmallint", "PKEY_SMALLINT"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamSmallint may cause overflow or loss of precision.\n" + "Partition column is type VoltType.SMALLINT and partition parameter " + "is type VoltType.BIGINT"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_SMALLINT ( PKEY SMALLINT NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_SMALLINT ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.PartitionParamSmallint;", "PKEY_SMALLINT"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamSmallint may cause overflow or loss of precision.\n" + "Partition column is type VoltType.SMALLINT and partition parameter " + "is type VoltType.BIGINT"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_SMALLINT ( PKEY SMALLINT NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_SMALLINT ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamSmallint;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamSmallint ON TABLE PKEY_SMALLINT COLUMN PKEY;", "PKEY_SMALLINT"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamSmallint may cause overflow or loss of precision.\n" + "Partition column is type VoltType.SMALLINT and partition parameter " + "is type VoltType.BIGINT"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_TINYINT ( PKEY TINYINT NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_TINYINT ON COLUMN PKEY;", "org.voltdb.compiler.procedures.PartitionParamTinyint", "PKEY_TINYINT"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamTinyint may cause overflow or loss of precision.\n" + "Partition column is type VoltType.TINYINT and partition parameter " + "is type VoltType.SMALLINT"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_TINYINT ( PKEY TINYINT NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_TINYINT ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.PartitionParamTinyint;", "PKEY_TINYINT"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamTinyint may cause overflow or loss of precision.\n" + "Partition column is type VoltType.TINYINT and partition parameter " + "is type VoltType.SMALLINT"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_TINYINT ( PKEY TINYINT NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_TINYINT ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamTinyint;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamTinyint ON TABLE PKEY_TINYINT COLUMN PKEY;", "PKEY_TINYINT"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamTinyint may cause overflow or loss of precision.\n" + "Partition column is type VoltType.TINYINT and partition parameter " + "is type VoltType.SMALLINT"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_STRING ( PKEY VARCHAR(32) NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_STRING ON COLUMN PKEY;", "org.voltdb.compiler.procedures.PartitionParamString", "PKEY_STRING"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamString may cause overflow or loss of precision.\n" + "Partition column is type VoltType.STRING and partition parameter " + "is type VoltType.INTEGER"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_STRING ( PKEY VARCHAR(32) NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_STRING ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.PartitionParamString;", "PKEY_STRING"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.PartitionParamString may cause overflow or loss of precision.\n" + "Partition column is type VoltType.STRING and partition parameter " + "is type VoltType.INTEGER"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkPartitionParam("CREATE TABLE PKEY_STRING ( PKEY VARCHAR(32) NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_STRING ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamString;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamString ON TABLE PKEY_STRING COLUMN PKEY;", "PKEY_STRING"); expectedError = "Type mismatch between partition column and partition parameter for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamString may cause overflow or loss of precision.\n" + "Partition column is type VoltType.STRING and partition parameter " + "is type VoltType.INTEGER"; assertTrue(isFeedbackPresent(expectedError, fbs)); } private ArrayList<Feedback> checkPartitionParam(String ddl, String procedureClass, String table) { final File schemaFile = VoltProjectBuilder.writeStringToTempFile(ddl); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas>" + "<schema path='" + schemaPath + "' />" + "</schemas>" + "<procedures>" + "<procedure class='" + procedureClass + "' />" + "</procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); return compiler.m_errors; } private ArrayList<Feedback> checkPartitionParam(String ddl, String table) { final File schemaFile = VoltProjectBuilder.writeStringToTempFile(ddl); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas>" + "<schema path='" + schemaPath + "' />" + "</schemas>" + "<procedures/>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); return compiler.m_errors; } public void testSnapshotSettings() throws IOException { String schemaPath = ""; try { final URL url = TPCCProjectBuilder.class.getResource("tpcc-ddl.sql"); schemaPath = URLDecoder.decode(url.getPath(), "UTF-8"); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); System.exit(-1); } VoltProjectBuilder builder = new VoltProjectBuilder(); builder.addProcedures(org.voltdb.compiler.procedures.TPCCTestProc.class); builder.setSnapshotSettings("32m", 5, "/tmp", "woobar"); builder.addSchema(schemaPath); try { assertTrue(builder.compile("/tmp/snapshot_settings_test.jar")); final String catalogContents = VoltCompiler.readFileFromJarfile("/tmp/snapshot_settings_test.jar", "catalog.txt"); final Catalog cat = new Catalog(); cat.execute(catalogContents); CatalogUtil.compileDeploymentAndGetCRC(cat, builder.getPathToDeployment(), true); SnapshotSchedule schedule = cat.getClusters().get("cluster").getDatabases(). get("database").getSnapshotschedule().get("default"); assertEquals(32, schedule.getFrequencyvalue()); assertEquals("m", schedule.getFrequencyunit()); //Will be empty because the deployment file initialization is what sets this value assertEquals("/tmp", schedule.getPath()); assertEquals("woobar", schedule.getPrefix()); } finally { final File jar = new File("/tmp/snapshot_settings_test.jar"); jar.delete(); } } // TestExportSuite tests most of these options are tested end-to-end; however need to test // that a disabled connector is really disabled and that auth data is correct. public void testExportSetting() throws IOException { final VoltProjectBuilder project = new VoltProjectBuilder(); project.addSchema(getClass().getResource("ExportTester-ddl.sql")); project.addExport("org.voltdb.export.processors.RawProcessor", false, null); project.setTableAsExportOnly("A"); project.setTableAsExportOnly("B"); try { boolean success = project.compile("/tmp/exportsettingstest.jar"); assertTrue(success); final String catalogContents = VoltCompiler.readFileFromJarfile("/tmp/exportsettingstest.jar", "catalog.txt"); final Catalog cat = new Catalog(); cat.execute(catalogContents); Connector connector = cat.getClusters().get("cluster").getDatabases(). get("database").getConnectors().get("0"); assertFalse(connector.getEnabled()); } finally { final File jar = new File("/tmp/exportsettingstest.jar"); jar.delete(); } } // test that Export configuration is insensitive to the case of the table name public void testExportTableCase() throws IOException { final VoltProjectBuilder project = new VoltProjectBuilder(); project.addSchema(TestVoltCompiler.class.getResource("ExportTester-ddl.sql")); project.addStmtProcedure("Dummy", "insert into a values (?, ?, ?);", "a.a_id: 0"); project.addPartitionInfo("A", "A_ID"); project.addPartitionInfo("B", "B_ID"); project.addPartitionInfo("e", "e_id"); project.addPartitionInfo("f", "f_id"); project.addExport("org.voltdb.export.processors.RawProcessor", true, null); project.setTableAsExportOnly("A"); // uppercase DDL, uppercase export project.setTableAsExportOnly("b"); // uppercase DDL, lowercase export project.setTableAsExportOnly("E"); // lowercase DDL, uppercase export project.setTableAsExportOnly("f"); // lowercase DDL, lowercase export try { assertTrue(project.compile("/tmp/exportsettingstest.jar")); final String catalogContents = VoltCompiler.readFileFromJarfile("/tmp/exportsettingstest.jar", "catalog.txt"); final Catalog cat = new Catalog(); cat.execute(catalogContents); CatalogUtil.compileDeploymentAndGetCRC(cat, project.getPathToDeployment(), true); Connector connector = cat.getClusters().get("cluster").getDatabases(). get("database").getConnectors().get("0"); assertTrue(connector.getEnabled()); // Assert that all tables exist in the connector section of catalog assertNotNull(connector.getTableinfo().getIgnoreCase("a")); assertNotNull(connector.getTableinfo().getIgnoreCase("b")); assertNotNull(connector.getTableinfo().getIgnoreCase("e")); assertNotNull(connector.getTableinfo().getIgnoreCase("f")); } finally { final File jar = new File("/tmp/exportsettingstest.jar"); jar.delete(); } } // test that the source table for a view is not export only public void testViewSourceNotExportOnly() throws IOException { final VoltProjectBuilder project = new VoltProjectBuilder(); project.addSchema(TestVoltCompiler.class.getResource("ExportTesterWithView-ddl.sql")); project.addStmtProcedure("Dummy", "select * from v_table1r_el_only"); project.addExport("org.voltdb.export.processors.RawProcessor", true, null); project.setTableAsExportOnly("table1r_el_only"); try { assertFalse(project.compile("/tmp/exporttestview.jar")); } finally { final File jar = new File("/tmp/exporttestview.jar"); jar.delete(); } } // test that a view is not export only public void testViewNotExportOnly() throws IOException { final VoltProjectBuilder project = new VoltProjectBuilder(); project.addSchema(TestVoltCompiler.class.getResource("ExportTesterWithView-ddl.sql")); project.addStmtProcedure("Dummy", "select * from table1r_el_only"); project.addExport("org.voltdb.export.processors.RawProcessor", true, null); project.setTableAsExportOnly("v_table1r_el_only"); try { assertFalse(project.compile("/tmp/exporttestview.jar")); } finally { final File jar = new File("/tmp/exporttestview.jar"); jar.delete(); } } public void testBadPath() { final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile("invalidnonsense", nothing_jar); assertFalse(success); } public void testXSDSchemaOrdering() throws IOException { final File schemaFile = VoltProjectBuilder.writeStringToTempFile("create table T(ID INTEGER);"); final String schemaPath = schemaFile.getPath(); final String project = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database>" + "<schemas>" + "<schema path='" + schemaPath + "'/>" + "</schemas>" + "<procedures>" + "<procedure class='proc'><sql>select * from T</sql></procedure>" + "</procedures>" + "</database>" + "</project>"; final File xmlFile = VoltProjectBuilder.writeStringToTempFile(project); final String path = xmlFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); boolean success = compiler.compile(path, nothing_jar); assertTrue(success); } public void testXMLFileWithDeprecatedElements() { final File schemaFile = VoltProjectBuilder.writeStringToTempFile("create table T(ID INTEGER);"); final String schemaPath = schemaFile.getPath(); final String project = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database>" + "<schemas>" + "<schema path='" + schemaPath + "'/>" + "</schemas>" + "<procedures>" + "<procedure class='proc'><sql>select * from T</sql></procedure>" + "</procedures>" + "</database>" + "<security enabled='true'/>" + "</project>"; final File xmlFile = VoltProjectBuilder.writeStringToTempFile(project); final String path = xmlFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); boolean success = compiler.compile(path, nothing_jar); assertFalse(success); assertTrue( isFeedbackPresent("Found deprecated XML element \"security\"", compiler.m_errors) ); } public void testXMLFileWithInvalidSchemaReference() { final String simpleXML = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='my schema file.sql' /></schemas>" + "<procedures><procedure class='procedures/procs.jar' /></procedures>" + "</database>" + "</project>"; final File xmlFile = VoltProjectBuilder.writeStringToTempFile(simpleXML); final String path = xmlFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(path, nothing_jar); assertFalse(success); } public void testXMLFileWithSchemaError() { final File schemaFile = VoltProjectBuilder.writeStringToTempFile("create table T(ID INTEGER);"); final String simpleXML = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='baddbname'>" + "<schemas>" + "<schema path='" + schemaFile.getAbsolutePath() + "'/>" + "</schemas>" + // invalid project file: no procedures // "<procedures>" + // "<procedure class='proc'><sql>select * from T</sql></procedure>" + //"</procedures>" + "</database>" + "</project>"; final File xmlFile = VoltProjectBuilder.writeStringToTempFile(simpleXML); final String path = xmlFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(path, nothing_jar); assertFalse(success); } public void testXMLFileWithWrongDBName() { final File schemaFile = VoltProjectBuilder.writeStringToTempFile("create table T(ID INTEGER);"); final String simpleXML = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='baddbname'>" + "<schemas>" + "<schema path='" + schemaFile.getAbsolutePath() + "'/>" + "</schemas>" + "<procedures>" + "<procedure class='proc'><sql>select * from T</sql></procedure>" + "</procedures>" + "</database>" + "</project>"; final File xmlFile = VoltProjectBuilder.writeStringToTempFile(simpleXML); final String path = xmlFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(path, nothing_jar); assertFalse(success); } public void testXMLFileWithDefaultDBName() { final File schemaFile = VoltProjectBuilder.writeStringToTempFile("create table T(ID INTEGER);"); final String simpleXML = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database>" + "<schemas>" + "<schema path='" + schemaFile.getAbsolutePath() + "'/>" + "</schemas>" + "<procedures>" + "<procedure class='proc'><sql>select * from T</sql></procedure>" + "</procedures>" + "</database>" + "</project>"; final File xmlFile = VoltProjectBuilder.writeStringToTempFile(simpleXML); final String path = xmlFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(path, nothing_jar); assertTrue(success); assertTrue(compiler.m_catalog.getClusters().get("cluster").getDatabases().get("database") != null); } public void testBadClusterConfig() throws IOException { // check no hosts ClusterConfig cluster_config = new ClusterConfig(0, 1, 0); assertFalse(cluster_config.validate()); // check no sites-per-hosts cluster_config = new ClusterConfig(1, 0, 0); assertFalse(cluster_config.validate()); } public void testXMLFileWithDDL() throws IOException { final String simpleSchema1 = "create table books (cash integer default 23 NOT NULL, title varchar(3) default 'foo', PRIMARY KEY(cash)); " + "PARTITION TABLE books ON COLUMN cash;"; // newline inserted to test catalog friendliness final String simpleSchema2 = "create table books2\n (cash integer default 23 NOT NULL, title varchar(3) default 'foo', PRIMARY KEY(cash));"; final File schemaFile1 = VoltProjectBuilder.writeStringToTempFile(simpleSchema1); final String schemaPath1 = schemaFile1.getPath(); final File schemaFile2 = VoltProjectBuilder.writeStringToTempFile(simpleSchema2); final String schemaPath2 = schemaFile2.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<!-- xml comment check -->" + "<database name='database'>" + "<!-- xml comment check -->" + "<schemas>" + "<!-- xml comment check -->" + "<schema path='" + schemaPath1 + "' />" + "<schema path='" + schemaPath2 + "' />" + "<!-- xml comment check -->" + "</schemas>" + "<!-- xml comment check -->" + "<procedures>" + "<!-- xml comment check -->" + "<procedure class='org.voltdb.compiler.procedures.AddBook' />" + "<procedure class='Foo'>" + "<sql>select * from books;</sql>" + "</procedure>" + "</procedures>" + "<!-- xml comment check -->" + "</database>" + "<!-- xml comment check -->" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final Catalog c1 = compiler.getCatalog(); final String catalogContents = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); final Catalog c2 = new Catalog(); c2.execute(catalogContents); assertTrue(c2.serialize().equals(c1.serialize())); } public void testProcWithBoxedParam() throws IOException { final String simpleSchema = "create table books (cash integer default 23, title varchar(3) default 'foo', PRIMARY KEY(cash));"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas>" + "<schema path='" + schemaPath + "' />" + "</schemas>" + "<procedures>" + "<procedure class='org.voltdb.compiler.procedures.AddBookBoxed' />" + "</procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); } public void testDDLWithNoLengthString() throws IOException { // DO NOT COPY PASTE THIS INVALID EXAMPLE! final String simpleSchema1 = "create table books (cash integer default 23, title varchar default 'foo', PRIMARY KEY(cash));"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema1); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas>" + "<schema path='" + schemaPath + "' />" + "</schemas>" + "<procedures>" + "<procedure class='org.voltdb.compiler.procedures.AddBook' />" + "<procedure class='Foo'>" + "<sql>select * from books;</sql>" + "</procedure>" + "</procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); } public void testNullablePartitionColumn() throws IOException { final String simpleSchema = "create table books (cash integer default 23, title varchar(3) default 'foo', PRIMARY KEY(cash));" + "partition table books on column cash;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='org.voltdb.compiler.procedures.AddBook'/></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); boolean found = false; for (final VoltCompiler.Feedback fb : compiler.m_errors) { if (fb.message.indexOf("Partition column") > 0) found = true; } assertTrue(found); } public void testXMLFileWithBadDDL() throws IOException { final String simpleSchema = "create table books (id integer default 0, strval varchar(33000) default '', PRIMARY KEY(id));"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='org.voltdb.compiler.procedures.AddBook' /></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); } // NOTE: TPCCTest proc also tests whitespaces regressions in SQL literals public void testWithTPCCDDL() { String schemaPath = ""; try { final URL url = TPCCProjectBuilder.class.getResource("tpcc-ddl.sql"); schemaPath = URLDecoder.decode(url.getPath(), "UTF-8"); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); System.exit(-1); } final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='org.voltdb.compiler.procedures.TPCCTestProc' /></procedures>" + "</database>" + "</project>"; //System.out.println(simpleProject); final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); } public void testSeparateCatalogCompilation() throws IOException { String schemaPath = ""; try { final URL url = TPCCProjectBuilder.class.getResource("tpcc-ddl.sql"); schemaPath = URLDecoder.decode(url.getPath(), "UTF-8"); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); System.exit(-1); } final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='org.voltdb.compiler.procedures.TPCCTestProc' /></procedures>" + "</database>" + "</project>"; //System.out.println(simpleProject); final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler1 = new VoltCompiler(); final VoltCompiler compiler2 = new VoltCompiler(); final Catalog catalog = compiler1.compileCatalog(projectPath); final String cat1 = catalog.serialize(); final boolean success = compiler2.compile(projectPath, testout_jar); final String cat2 = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); assertTrue(success); assertTrue(cat1.compareTo(cat2) == 0); } public void testDDLTableTooManyColumns() throws IOException { String schemaPath = ""; try { final URL url = TestVoltCompiler.class.getResource("toowidetable-ddl.sql"); schemaPath = URLDecoder.decode(url.getPath(), "UTF-8"); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); System.exit(-1); } final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='org.voltdb.compiler.procedures.TPCCTestProc' /></procedures>" + "</database>" + "</project>"; //System.out.println(simpleProject); final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); boolean found = false; for (final VoltCompiler.Feedback fb : compiler.m_errors) { if (fb.message.startsWith("Table MANY_COLUMNS has")) found = true; } assertTrue(found); } public void testExtraFilesExist() throws IOException { String schemaPath = ""; try { final URL url = TPCCProjectBuilder.class.getResource("tpcc-ddl.sql"); schemaPath = URLDecoder.decode(url.getPath(), "UTF-8"); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); System.exit(-1); } final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='org.voltdb.compiler.procedures.TPCCTestProc' /></procedures>" + "</database>" + "</project>"; //System.out.println(simpleProject); final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final String sql = VoltCompiler.readFileFromJarfile(testout_jar, "tpcc-ddl.sql"); assertNotNull(sql); } public void testXMLFileWithELEnabled() throws IOException { final String simpleSchema = "create table books (cash integer default 23 NOT NULL, title varchar(3) default 'foo');"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + " <database name='database'>" + " <partitions><partition table='books' column='cash'/></partitions> " + " <schemas><schema path='" + schemaPath + "' /></schemas>" + " <procedures><procedure class='org.voltdb.compiler.procedures.AddBook' /></procedures>" + " <export>" + " <tables><table name='books'/></tables>" + " </export>" + " </database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final Catalog c1 = compiler.getCatalog(); //System.out.println("PRINTING Catalog 1"); //System.out.println(c1.serialize()); final String catalogContents = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); final Catalog c2 = new Catalog(); c2.execute(catalogContents); assertTrue(c2.serialize().equals(c1.serialize())); } public void testOverrideProcInfo() throws IOException { final String simpleSchema = "create table books (cash integer default 23 not null, title varchar(3) default 'foo', PRIMARY KEY(cash));" + "PARTITION TABLE books ON COLUMN cash;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='org.voltdb.compiler.procedures.AddBook' /></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final ProcInfoData info = new ProcInfoData(); info.singlePartition = true; info.partitionInfo = "BOOKS.CASH: 0"; final Map<String, ProcInfoData> overrideMap = new HashMap<String, ProcInfoData>(); overrideMap.put("AddBook", info); final VoltCompiler compiler = new VoltCompiler(); compiler.setProcInfoOverrides(overrideMap); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final String catalogContents = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); final Catalog c2 = new Catalog(); c2.execute(catalogContents); final Database db = c2.getClusters().get("cluster").getDatabases().get("database"); final Procedure addBook = db.getProcedures().get("AddBook"); assertEquals(true, addBook.getSinglepartition()); } public void testOverrideNonAnnotatedProcInfo() throws IOException { final String simpleSchema = "create table books (cash integer default 23 not null, title varchar(3) default 'foo', PRIMARY KEY(cash));" + "PARTITION TABLE books ON COLUMN cash;" + "create procedure from class org.voltdb.compiler.procedures.AddBook;" + "partition procedure AddBook ON TABLE books COLUMN cash;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures/>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final ProcInfoData info = new ProcInfoData(); info.singlePartition = true; info.partitionInfo = "BOOKS.CASH: 0"; final Map<String, ProcInfoData> overrideMap = new HashMap<String, ProcInfoData>(); overrideMap.put("AddBook", info); final VoltCompiler compiler = new VoltCompiler(); compiler.setProcInfoOverrides(overrideMap); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final String catalogContents = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); final Catalog c2 = new Catalog(); c2.execute(catalogContents); final Database db = c2.getClusters().get("cluster").getDatabases().get("database"); final Procedure addBook = db.getProcedures().get("AddBook"); assertEquals(true, addBook.getSinglepartition()); } public void testBadStmtProcName() throws IOException { final String simpleSchema = "create table books (cash integer default 23 not null, title varchar(10) default 'foo', PRIMARY KEY(cash));"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='@Foo'><sql>select * from books;</sql></procedure></procedures>" + "<partitions><partition table='BOOKS' column='CASH' /></partitions>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); } public void testBadDdlStmtProcName() throws IOException { final String simpleSchema = "create table books (cash integer default 23 not null, title varchar(10) default 'foo', PRIMARY KEY(cash));" + "create procedure @Foo as select * from books;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures/>" + "<partitions><partition table='BOOKS' column='CASH' /></partitions>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); } public void testGoodStmtProcName() throws IOException { final String simpleSchema = "create table books (cash integer default 23 not null, title varchar(3) default 'foo', PRIMARY KEY(cash));" + "PARTITION TABLE books ON COLUMN cash;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='Foo'><sql>select * from books;</sql></procedure></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); } public void testGoodDdlStmtProcName() throws IOException { final String simpleSchema = "create table books (cash integer default 23 not null, title varchar(3) default 'foo', PRIMARY KEY(cash));" + "PARTITION TABLE books ON COLUMN cash;" + "CREATE PROCEDURE Foo AS select * from books where cash = ?;" + "PARTITION PROCEDURE Foo ON TABLE BOOKS COLUMN CASH PARAMETER 0;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures/>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); } public void testMaterializedView() throws IOException { final String simpleSchema = "create table books (cash integer default 23 NOT NULL, title varchar(10) default 'foo', PRIMARY KEY(cash));\n" + "partition table books on column cash;\n" + "create view matt (title, cash, num, foo) as select title, cash, count(*), sum(cash) from books group by title, cash;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='org.voltdb.compiler.procedures.AddBook' /></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); // final ClusterConfig cluster_config = new ClusterConfig(1, 1, 0, "localhost"); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final Catalog c1 = compiler.getCatalog(); final String catalogContents = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); final Catalog c2 = new Catalog(); c2.execute(catalogContents); assertTrue(c2.serialize().equals(c1.serialize())); } public void testVarbinary() throws IOException { final String simpleSchema = "create table books (cash integer default 23 NOT NULL, title varbinary(10) default NULL, PRIMARY KEY(cash));" + "partition table books on column cash;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures>" + "<procedure class='get'><sql>select * from books;</sql></procedure>" + "<procedure class='i1'><sql>insert into books values(5, 'AA');</sql></procedure>" + "<procedure class='i2'><sql>insert into books values(5, ?);</sql></procedure>" + "<procedure class='s1'><sql>update books set title = 'bb';</sql></procedure>" + "</procedures>" + //"<procedures><procedure class='org.voltdb.compiler.procedures.AddBook' /></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); // final ClusterConfig cluster_config = new ClusterConfig(1, 1, 0, "localhost"); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final Catalog c1 = compiler.getCatalog(); final String catalogContents = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); final Catalog c2 = new Catalog(); c2.execute(catalogContents); assertTrue(c2.serialize().equals(c1.serialize())); } public void testDdlProcVarbinary() throws IOException { final String simpleSchema = "create table books (cash integer default 23 NOT NULL, title varbinary(10) default NULL, PRIMARY KEY(cash));" + "partition table books on column cash;" + "create procedure get as select * from books;" + "create procedure i1 as insert into books values(5, 'AA');" + "create procedure i2 as insert into books values(5, ?);" + "create procedure s1 as update books set title = 'bb';" + "create procedure i3 as insert into books values( ?, ?);" + "partition procedure i3 on table books column cash;" + "create procedure d1 as delete from books where title = ? and cash = ?;" + "partition procedure d1 on table books column cash parameter 1;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures/>" + //"<procedures><procedure class='org.voltdb.compiler.procedures.AddBook' /></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); // final ClusterConfig cluster_config = new ClusterConfig(1, 1, 0, "localhost"); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final Catalog c1 = compiler.getCatalog(); final String catalogContents = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); final Catalog c2 = new Catalog(); c2.execute(catalogContents); assertTrue(c2.serialize().equals(c1.serialize())); } // // There are DDL tests a number of places. TestDDLCompiler seems more about // verifying HSQL behaviour. Additionally, there are users of PlannerAideDeCamp // that verify plans for various DDL/SQL combinations. // // I'm going to add some DDL parsing validation tests here, as they seem to have // more to do with compiling a catalog.. and there are some related tests already // in this file. // private VoltCompiler compileForDDLTest(String schemaPath, boolean expectSuccess) { final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='sample'><sql>select * from t</sql></procedure></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); projectFile.deleteOnExit(); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertEquals(expectSuccess, success); return compiler; } private String getPathForSchema(String s) { final File schemaFile = VoltProjectBuilder.writeStringToTempFile(s); schemaFile.deleteOnExit(); return schemaFile.getPath(); } public void testDDLCompilerLeadingGarbage() throws IOException { final String s = "-- a valid comment\n" + "- an invalid comment\n" + "create table t(id integer);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), false); assertTrue(c.hasErrors()); } public void testDDLCompilerLeadingWhitespace() throws IOException { final String s = " \n" + "\n" + "create table t(id integer);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerLeadingComment() throws IOException { final String s = "-- this is a leading comment\n" + " -- with some leading whitespace\n" + " create table t(id integer);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerNoNewlines() throws IOException { final String s = "create table t(id integer); create table r(id integer);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 2); } public void testDDLCompilerSplitLines() throws IOException { final String s = "create\n" + "table\n" + "t(id\n" + "integer);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerTrailingComment1() throws IOException { final String s = "create table t(id integer) -- this is a trailing comment\n" + "-- and a line full of comments\n" + ";\n"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerTrailingComment2() throws IOException { final String s = "create table t(id integer) -- this is a trailing comment\n" + ";\n"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerTrailingComment3() throws IOException { final String s = "create table t(id integer) -- this is a trailing comment\n" + "-- and a line full of comments\n" + ";"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerTrailingComment4() throws IOException { final String s = "create table t(id integer) -- this is a trailing comment\n" + ";"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerTrailingComment5() throws IOException { final String s = "create table t(id integer) -- this is a trailing comment\n" + "-- and a line full of comments\n" + " ;\n"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerTrailingComment6() throws IOException { final String s = "create table t(id integer) -- this is a trailing comment\n" + "-- and a line full of comments\n" + " ;\n" + "-- ends with a comment\n"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerInvalidStatement() throws IOException { final String s = "create table t for justice -- with a comment\n"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), false); assertTrue(c.hasErrors()); } public void testDDLCompilerCommentThatLooksLikeStatement() throws IOException { final String s = "create table t(id integer); -- create table r(id integer);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); } public void testDDLCompilerLeadingSemicolon() throws IOException { final String s = "; create table t(id integer);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), false); assertTrue(c.hasErrors()); } public void testDDLCompilerMultipleStatementsOnMultipleLines() throws IOException { final String s = "create table t(id integer); create\n" + "table r(id integer); -- second table"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 2); } public void testDDLCompilerStringLiteral() throws IOException { final String s = "create table t(id varchar(3) default 'abc');"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); Table tbl = c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().getIgnoreCase("t"); String defaultvalue = tbl.getColumns().getIgnoreCase("id").getDefaultvalue(); assertTrue(defaultvalue.equalsIgnoreCase("abc")); } public void testDDLCompilerSemiColonInStringLiteral() throws IOException { final String s = "create table t(id varchar(5) default 'a;bc');"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); Table tbl = c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().getIgnoreCase("t"); String defaultvalue = tbl.getColumns().getIgnoreCase("id").getDefaultvalue(); assertTrue(defaultvalue.equalsIgnoreCase("a;bc")); } public void testDDLCompilerDashDashInStringLiteral() throws IOException { final String s = "create table t(id varchar(5) default 'a--bc');"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); Table tbl = c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().getIgnoreCase("t"); String defaultvalue = tbl.getColumns().getIgnoreCase("id").getDefaultvalue(); assertTrue(defaultvalue.equalsIgnoreCase("a--bc")); } public void testDDLCompilerNewlineInStringLiteral() throws IOException { final String s = "create table t(id varchar(5) default 'a\n" + "bc');"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); Table tbl = c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().getIgnoreCase("t"); String defaultvalue = tbl.getColumns().getIgnoreCase("id").getDefaultvalue(); // In the debugger, this looks valid at parse time but is mangled somewhere // later, perhaps in HSQL or in the catalog assembly? // ENG-681 System.out.println(defaultvalue); // assertTrue(defaultvalue.equalsIgnoreCase("a\nbc")); } public void testDDLCompilerEscapedStringLiterals() throws IOException { final String s = "create table t(id varchar(10) default 'a''b''''c');"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); assertTrue(c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().size() == 1); Table tbl = c.m_catalog.getClusters().get("cluster").getDatabases().get("database").getTables().getIgnoreCase("t"); String defaultvalue = tbl.getColumns().getIgnoreCase("id").getDefaultvalue(); assertTrue(defaultvalue.equalsIgnoreCase("a'b''c")); } // Test that DDLCompiler's index creation adheres to the rules implicit in // the EE's tableindexfactory. Currently (10/3/2010) these are: // All column types can be used in a tree array. Only int types can // be used in hash tables or array indexes String[] column_types = {"tinyint", "smallint", "integer", "bigint", "float", "varchar(10)", "timestamp", "decimal"}; IndexType[] default_index_types = {IndexType.BALANCED_TREE, IndexType.BALANCED_TREE, IndexType.BALANCED_TREE, IndexType.BALANCED_TREE, IndexType.BALANCED_TREE, IndexType.BALANCED_TREE, IndexType.BALANCED_TREE, IndexType.BALANCED_TREE}; boolean[] can_be_hash = {true, true, true, true, false, false, true, false}; boolean[] can_be_tree = {true, true, true, true, true, true, true, true}; public void testDDLCompilerIndexDefaultTypes() { for (int i = 0; i < column_types.length; i++) { String s = "create table t(id " + column_types[i] + " not null, num integer not null);\n" + "create index idx_t_id on t(id);\n" + "create index idx_t_idnum on t(id,num);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); Database d = c.m_catalog.getClusters().get("cluster").getDatabases().get("database"); assertEquals(default_index_types[i].getValue(), d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t_id").getType()); assertEquals(default_index_types[i].getValue(), d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t_idnum").getType()); } } public void testDDLCompilerHashIndexAllowed() { for (int i = 0; i < column_types.length; i++) { final String s = "create table t(id " + column_types[i] + " not null, num integer not null);\n" + "create index idx_t_id_hash on t(id);\n" + "create index idx_t_idnum_hash on t(id,num);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), can_be_hash[i]); if (can_be_hash[i]) { // do appropriate index exists checks assertFalse(c.hasErrors()); Database d = c.m_catalog.getClusters().get("cluster").getDatabases().get("database"); assertEquals(IndexType.HASH_TABLE.getValue(), d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t_id_hash").getType()); assertEquals(IndexType.HASH_TABLE.getValue(), d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t_idnum_hash").getType()); } else { assertTrue(c.hasErrors()); } } } public void testUniqueIndexAllowed() { final String s = "create table t(id integer not null, num integer not null);\n" + "create unique index idx_t_unique on t(id,num);\n" + "create index idx_t on t(num);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); Database d = c.m_catalog.getClusters().get("cluster").getDatabases().get("database"); assertTrue(d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t_unique").getUnique()); assertFalse(d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t").getUnique()); // also validate that simple column indexes don't trigger the generalized expression index handling String noExpressionFound = ""; assertEquals(noExpressionFound, d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t_unique").getExpressionsjson()); assertEquals(noExpressionFound, d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t").getExpressionsjson()); } public void testFunctionIndexAllowed() { final String s = "create table t(id integer not null, num integer not null);\n" + "create unique index idx_ft_unique on t(abs(id+num));\n" + "create index idx_ft on t(abs(num));"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), true); assertFalse(c.hasErrors()); Database d = c.m_catalog.getClusters().get("cluster").getDatabases().get("database"); assertTrue(d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_ft_unique").getUnique()); assertFalse(d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_ft").getUnique()); // Validate that general expression indexes get properly annotated with an expressionjson attribute String noExpressionFound = ""; assertNotSame(noExpressionFound, d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_ft_unique").getExpressionsjson()); assertNotSame(noExpressionFound, d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_ft").getExpressionsjson()); } public void testDDLCompilerVarcharTreeIndexAllowed() { for (int i = 0; i < column_types.length; i++) { final String s = "create table t(id " + column_types[i] + " not null, num integer not null);\n" + "create index idx_t_id_tree on t(id);\n" + "create index idx_t_idnum_tree on t(id,num);"; VoltCompiler c = compileForDDLTest(getPathForSchema(s), can_be_tree[i]); assertFalse(c.hasErrors()); Database d = c.m_catalog.getClusters().get("cluster").getDatabases().get("database"); assertEquals(IndexType.BALANCED_TREE.getValue(), d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t_id_tree").getType()); assertEquals(IndexType.BALANCED_TREE.getValue(), d.getTables().getIgnoreCase("t").getIndexes().getIgnoreCase("idx_t_idnum_tree").getType()); } } public void testPartitionOnBadType() { final String simpleSchema = "create table books (cash float default 0.0 NOT NULL, title varchar(10) default 'foo', PRIMARY KEY(cash));"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<partitions><partition table='books' column='cash'/></partitions> " + "<procedures><procedure class='org.voltdb.compiler.procedures.AddBook' /></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); } public void testOmittedProcedureList() { final String simpleSchema = "create table books (cash float default 0.0 NOT NULL, title varchar(10) default 'foo', PRIMARY KEY(cash));"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); } public void test3324MPPlan() throws IOException { final String simpleSchema = "create table blah (pkey integer not null, strval varchar(200), PRIMARY KEY(pkey));\n"; VoltProjectBuilder pb = new VoltProjectBuilder(); pb.enableDiagnostics(); pb.addLiteralSchema(simpleSchema); pb.addPartitionInfo("blah", "pkey"); pb.addStmtProcedure("undeclaredspquery1", "select strval UNDECLARED1 from blah where pkey = ?"); pb.addStmtProcedure("undeclaredspquery2", "select strval UNDECLARED2 from blah where pkey = 12"); pb.addStmtProcedure("declaredspquery1", "select strval SODECLARED1 from blah where pkey = ?", "blah.pkey:0"); // Currently no way to do this? // pb.addStmtProcedure("declaredspquery2", "select strval SODECLARED2 from blah where pkey = 12", "blah.pkey=12"); boolean success = pb.compile(Configuration.getPathToCatalogForTest("test3324.jar")); assertTrue(success); List<String> diagnostics = pb.harvestDiagnostics(); // This asserts that the undeclared SP plans don't mistakenly get SP treatment // -- they must each include a RECEIVE plan node. assertEquals(2, countStringsMatching(diagnostics, ".*\"UNDECLARED.\".*\"PLAN_NODE_TYPE\":\"RECEIVE\".*")); // This asserts that the methods used to prevent undeclared SP plans from getting SP treatment // don't over-reach to declared SP plans. assertEquals(0, countStringsMatching(diagnostics, ".*\"SODECLARED.\".*\"PLAN_NODE_TYPE\":\"RECEIVE\".*")); // System.out.println("test3324MPPlan"); // System.out.println(diagnostics); } public void testBadDDLErrorLineNumber() throws IOException { final String schema = "-- a comment\n" + // 1 "create table books (\n" + // 2 " id integer default 0,\n" + // 3 " strval varchar(33000) default '',\n" + // 4 " PRIMARY KEY(id)\n" + // 5 ");\n" + // 6 "\n" + // 7 "-- another comment\n" + // 8 "create view badview (\n" + // 9 * error reported here * " id,\n" + " COUNT(*),\n" + " total\n" + " as\n" + "select id, COUNT(*), SUM(cnt)\n" + " from books\n" + " group by id;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(schema); final String schemaPath = schemaFile.getPath(); final String project = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures><procedure class='org.voltdb.compiler.procedures.AddBook' /></procedures>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(project); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); for (Feedback error: compiler.m_errors) { assertEquals(9, error.lineNo); } } public void testInvalidCreateProcedureDDL() throws Exception { ArrayList<Feedback> fbs; String expectedError; fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NonExistentPartitionParamInteger;" + "PARTITION PROCEDURE NonExistentPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Cannot load class for procedure: org.voltdb.compiler.procedures.NonExistentPartitionParamInteger"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "PARTITION PROCEDURE NotDefinedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Partition in referencing an undefined procedure \"NotDefinedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.PartitionParamInteger;" + "PARTITION PROCEDURE PartitionParamInteger ON TABLE PKEY_WHAAAT COLUMN PKEY;" ); expectedError = "PartitionParamInteger has partition properties defined both in class " + "\"org.voltdb.compiler.procedures.PartitionParamInteger\" and in the schema defintion file(s)"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_WHAAAT COLUMN PKEY;" ); expectedError = "PartitionInfo for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger refers to a column " + "in schema which can't be found."; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PSURROGATE;" ); expectedError = "PartitionInfo for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger refers to a column " + "in schema which can't be found."; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 8;" ); expectedError = "PartitionInfo specifies invalid parameter index for procedure: " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM GLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad CREATE PROCEDURE DDL statement: " + "\"CREATE PROCEDURE FROM GLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger\"" + - ", expected syntax: \"CREATE PROCEDURE FROM CLASS <class-name>\""; + ", expected syntax: \"CREATE PROCEDURE"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger FOR TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger FOR TABLE PKEY_INTEGER COLUMN PKEY\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER CLUMN PKEY PARMTR 0;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER CLUMN PKEY PARMTR 0\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER hello;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER hello\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROGEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER hello;" ); expectedError = "Bad PARTITION DDL statement: " + "\"PARTITION PROGEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER " + "COLUMN PKEY PARAMETER hello\", expected syntax: \"PARTITION TABLE <table> " + "ON COLUMN <column>\" or \"PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE OUTOF CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 2;" ); expectedError = "Bad CREATE PROCEDURE DDL statement: " + "\"CREATE PROCEDURE OUTOF CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger\"" + - ", expected syntax: \"CREATE PROCEDURE FROM CLASS <class-name>\""; + ", expected syntax: \"CREATE PROCEDURE"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "MAKE PROCEDURE OUTOF CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 2;" ); expectedError = "DDL Error: \"unexpected token: MAKE\" in statement starting on lineno: 1"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE 1PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN;" ); expectedError = "Bad indentifier in DDL: \"PARTITION TABLE 1PKEY_INTEGER ON COLUMN PKEY\" " + "contains invalid identifier \"1PKEY_INTEGER\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN 2PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \"PARTITION TABLE PKEY_INTEGER ON COLUMN 2PKEY\" " + "contains invalid identifier \"2PKEY\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS 0rg.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE FROM CLASS 0rg.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger" + "\" contains invalid identifier \"0rg.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.3compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE FROM CLASS org.voltdb.3compiler.procedures.NotAnnotatedPartitionParamInteger" + "\" contains invalid identifier \"org.voltdb.3compiler.procedures.NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.4NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.4NotAnnotatedPartitionParamInteger" + "\" contains invalid identifier \"org.voltdb.compiler.procedures.4NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE 5NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "PARTITION PROCEDURE 5NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY" + "\" contains invalid identifier \"5NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE 6PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE 6PKEY_INTEGER COLUMN PKEY" + "\" contains invalid identifier \"6PKEY_INTEGER\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN 7PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN 7PKEY" + "\" contains invalid identifier \"7PKEY\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger TABLE PKEY_INTEGER ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger TABLE PKEY_INTEGER ON TABLE PKEY_INTEGER COLUMN PKEY\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); } public void testInvalidSingleStatementCreateProcedureDDL() throws Exception { ArrayList<Feedback> fbs; String expectedError; fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, DESCR VARCHAR(128), PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE Foo AS BANBALOO pkey FROM PKEY_INTEGER;" + "PARTITION PROCEDURE Foo ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad CREATE PROCEDURE DDL statement: " + "\"CREATE PROCEDURE Foo AS BANBALOO pkey FROM PKEY_INTEGER\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, DESCR VARCHAR(128), PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE Foo AS SELEC pkey FROM PKEY_INTEGER;" + "PARTITION PROCEDURE Foo ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 0;" ); expectedError = "Bad CREATE PROCEDURE DDL statement: " + "\"CREATE PROCEDURE Foo AS SELEC pkey FROM PKEY_INTEGER\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, DESCR VARCHAR(128), PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE Foo AS DELETE FROM PKEY_INTEGER WHERE PKEY = ?;" + "PARTITION PROCEDURE Foo ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 2;" ); expectedError = "PartitionInfo specifies invalid parameter index for procedure: Foo"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, DESCR VARCHAR(128), PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE Foo AS DELETE FROM PKEY_INTEGER;" + "PARTITION PROCEDURE Foo ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "PartitionInfo specifies invalid parameter index for procedure: Foo"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, DESCR VARCHAR(128), PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE org.kanamuri.Foo AS DELETE FROM PKEY_INTEGER;" + "PARTITION PROCEDURE Foo ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "PartitionInfo specifies invalid parameter index for procedure: org.kanamuri.Foo"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, DESCR VARCHAR(128), PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE 7Foo AS DELETE FROM PKEY_INTEGER WHERE PKEY = ?;" + "PARTITION PROCEDURE 7Foo ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE 7Foo AS DELETE FROM PKEY_INTEGER WHERE PKEY = ?" + "\" contains invalid identifier \"7Foo\""; assertTrue(isFeedbackPresent(expectedError, fbs)); } private ArrayList<Feedback> checkInvalidProcedureDDL(String ddl) { final File schemaFile = VoltProjectBuilder.writeStringToTempFile(ddl); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas>" + "<schema path='" + schemaPath + "' />" + "</schemas>" + "<procedures/>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertFalse(success); return compiler.m_errors; } public void testValidAnnotatedProcedureDLL() throws Exception { final String simpleSchema = "create table books (cash integer default 23 not null, title varchar(3) default 'foo', PRIMARY KEY(cash));" + "PARTITION TABLE books ON COLUMN cash;" + "creAte PrOcEdUrE FrOm CLasS org.voltdb.compiler.procedures.AddBook;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures/>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final String catalogContents = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); final Catalog c2 = new Catalog(); c2.execute(catalogContents); final Database db = c2.getClusters().get("cluster").getDatabases().get("database"); final Procedure addBook = db.getProcedures().get("AddBook"); assertEquals(true, addBook.getSinglepartition()); } public void testValidNonAnnotatedProcedureDDL() throws Exception { final String simpleSchema = "create table books (cash integer default 23 not null, title varchar(3) default 'foo', PRIMARY KEY(cash));" + "PARTITION TABLE books ON COLUMN cash;" + "create procedure from class org.voltdb.compiler.procedures.NotAnnotatedAddBook;" + "paRtItiOn prOcEdure NotAnnotatedAddBook On taBLe books coLUmN cash ParaMETer 0;"; final File schemaFile = VoltProjectBuilder.writeStringToTempFile(simpleSchema); final String schemaPath = schemaFile.getPath(); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "<procedures/>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); assertTrue(success); final String catalogContents = VoltCompiler.readFileFromJarfile(testout_jar, "catalog.txt"); final Catalog c2 = new Catalog(); c2.execute(catalogContents); final Database db = c2.getClusters().get("cluster").getDatabases().get("database"); final Procedure addBook = db.getProcedures().get("NotAnnotatedAddBook"); assertEquals(true, addBook.getSinglepartition()); } class TestRole { final String name; boolean adhoc = false; boolean sysproc = false; boolean defaultproc = false; public TestRole(String name) { this.name = name; } public TestRole(String name, boolean adhoc, boolean sysproc, boolean defaultproc) { this.name = name; this.adhoc = adhoc; this.sysproc = sysproc; this.defaultproc = defaultproc; } } private void checkRoleXMLAndDDL(String rolesElem, String ddl, String errorRegex, TestRole... roles) throws Exception { final File schemaFile = VoltProjectBuilder.writeStringToTempFile(ddl != null ? ddl : ""); final String schemaPath = schemaFile.getPath(); String rolesBlock = (rolesElem != null ? String.format("<roles>%s</roles>", rolesElem) : ""); final String simpleProject = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas>" + "<schema path='" + schemaPath + "' />" + "</schemas>" + rolesBlock + "<procedures/>" + "</database>" + "</project>"; final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject); final String projectPath = projectFile.getPath(); final VoltCompiler compiler = new VoltCompiler(); final boolean success = compiler.compile(projectPath, testout_jar); String error = (success || compiler.m_errors.size() == 0 ? "" : compiler.m_errors.get(compiler.m_errors.size()-1).message); if (errorRegex == null) { assertTrue(String.format("Expected success\nXML: %s\nDDL: %s\nERR: %s", rolesElem, ddl, error), success); Catalog cat = compiler.getCatalog(); CatalogMap<Group> groups = cat.getClusters().get("cluster").getDatabases().get("database").getGroups(); assertNotNull(groups); assertEquals(roles.length, groups.size()); for (TestRole role : roles) { Group group = groups.get(role.name); assertNotNull(String.format("Missing role \"%s\"", role.name), group); assertEquals(String.format("Role \"%s\" adhoc flag mismatch:", role.name), role.adhoc, group.getAdhoc()); assertEquals(String.format("Role \"%s\" sysproc flag mismatch:", role.name), role.sysproc, group.getSysproc()); assertEquals(String.format("Role \"%s\" defaultproc flag mismatch:", role.name), role.defaultproc, group.getDefaultproc()); } } else { assertFalse(String.format("Expected error (\"%s\")\nXML: %s\nDDL: %s", errorRegex, rolesElem, ddl), success); assertFalse("Expected at least one error message.", error.isEmpty()); Matcher m = Pattern.compile(errorRegex).matcher(error); assertTrue(String.format("%s\nEXPECTED: %s", error, errorRegex), m.matches()); } } private void goodRoleDDL(String ddl, TestRole... roles) throws Exception { checkRoleXMLAndDDL(null, ddl, null, roles); } private void badRoleDDL(String ddl, String errorRegex) throws Exception { checkRoleXMLAndDDL(null, ddl, errorRegex); } public void testRoleXML() throws Exception { checkRoleXMLAndDDL("<role name='r1'/>", null, null, new TestRole("r1")); } public void testBadRoleXML() throws Exception { checkRoleXMLAndDDL("<rolex name='r1'/>", null, ".*rolex.*[{]role[}].*expected.*"); checkRoleXMLAndDDL("<role name='r1'/>", "create role r1;", ".*already exists.*"); } public void testRoleDDL() throws Exception { goodRoleDDL("create role r1;", new TestRole("r1")); goodRoleDDL("create role r1;create role r2;", new TestRole("r1"), new TestRole("r2")); goodRoleDDL("create role r1 with adhoc;", new TestRole("r1", true, false, false)); goodRoleDDL("create role r1 with sysproc;", new TestRole("r1", false, true, false)); goodRoleDDL("create role r1 with defaultproc;", new TestRole("r1", false, false, true)); goodRoleDDL("create role r1 with adhoc,sysproc,defaultproc;", new TestRole("r1", true, true, true)); goodRoleDDL("create role r1 with adhoc ,sysproc, defaultproc;", new TestRole("r1", true, true, true)); goodRoleDDL("create role r1 with adhoc,sysproc,sysproc;", new TestRole("r1", true, true, false)); goodRoleDDL("create role r1 with AdHoc,SysProc,DefaultProc;", new TestRole("r1", true, true, true)); } public void testBadRoleDDL() throws Exception { badRoleDDL("create role r1", ".*no semicolon.*"); badRoleDDL("create role r1;create role r1;", ".*already exists.*"); badRoleDDL("create role r1 with ;", ".*unexpected token.*"); badRoleDDL("create role r1 with blah;", ".*Bad flag \"blah\".*"); badRoleDDL("create role r1 with adhoc sysproc;", ".*unexpected token.*"); badRoleDDL("create role r1 with adhoc, blah;", ".*Bad flag \"blah\".*"); } private Database checkDDLAgainstSimpleSchema(String errorRegex, String... ddl) throws Exception { String schemaDDL = "create table books (cash integer default 23 NOT NULL, title varbinary(10) default NULL, PRIMARY KEY(cash)); " + "partition table books on column cash;" + StringUtils.join(ddl, " "); File schemaFile = VoltProjectBuilder.writeStringToTempFile(schemaDDL.toString()); String schemaPath = schemaFile.getPath(); String projectXML = "<?xml version=\"1.0\"?>\n" + "<project>" + "<database name='database'>" + "<schemas><schema path='" + schemaPath + "' /></schemas>" + "</database>" + "</project>"; File projectFile = VoltProjectBuilder.writeStringToTempFile(projectXML); String projectPath = projectFile.getPath(); VoltCompiler compiler = new VoltCompiler(); boolean success = compiler.compile(projectPath, testout_jar); String error = (success || compiler.m_errors.size() == 0 ? "" : compiler.m_errors.get(compiler.m_errors.size()-1).message); if (errorRegex == null) { assertTrue(String.format("Expected success\nDDL: %s\n%s", ddl, error), success); Catalog cat = compiler.getCatalog(); return cat.getClusters().get("cluster").getDatabases().get("database"); } else { assertFalse(String.format("Expected error (\"%s\")\nDDL: %s", errorRegex, ddl), success); assertFalse("Expected at least one error message.", error.isEmpty()); Matcher m = Pattern.compile(errorRegex).matcher(error); assertTrue(String.format("%s\nEXPECTED: %s", error, errorRegex), m.matches()); return null; } } private Database goodDDLAgainstSimpleSchema(String... ddl) throws Exception { return checkDDLAgainstSimpleSchema(null, ddl); } private void badDDLAgainstSimpleSchema(String errorRegex, String... ddl) throws Exception { checkDDLAgainstSimpleSchema(errorRegex, ddl); } public void testGoodCreateProcedureWithAllow() throws Exception { Database db = goodDDLAgainstSimpleSchema( "create role r1;", "create procedure p1 allow r1 as select * from books;"); Procedure proc = db.getProcedures().get("p1"); assertNotNull(proc); CatalogMap<GroupRef> groups = proc.getAuthgroups(); assertEquals(1, groups.size()); assertNotNull(groups.get("r1")); db = goodDDLAgainstSimpleSchema( "create role r1;", "create role r2;", "create procedure p1 allow r1, r2 as select * from books;"); proc = db.getProcedures().get("p1"); assertNotNull(proc); groups = proc.getAuthgroups(); assertEquals(2, groups.size()); assertNotNull(groups.get("r1")); assertNotNull(groups.get("r2")); db = goodDDLAgainstSimpleSchema( "create role r1;", "create procedure allow r1 from class org.voltdb.compiler.procedures.AddBook;"); proc = db.getProcedures().get("AddBook"); assertNotNull(proc); groups = proc.getAuthgroups(); assertEquals(1, groups.size()); assertNotNull(groups.get("r1")); db = goodDDLAgainstSimpleSchema( "create role r1;", "create role r2;", "create procedure allow r1,r2 from class org.voltdb.compiler.procedures.AddBook;"); proc = db.getProcedures().get("AddBook"); assertNotNull(proc); groups = proc.getAuthgroups(); assertEquals(2, groups.size()); assertNotNull(groups.get("r1")); assertNotNull(groups.get("r2")); } public void testBadCreateProcedureWithAllow() throws Exception { badDDLAgainstSimpleSchema(".*expected syntax.*", "create procedure p1 allow as select * from books;"); badDDLAgainstSimpleSchema(".*expected syntax.*", "create procedure p1 allow a b as select * from books;"); badDDLAgainstSimpleSchema(".*group rx that does not exist.*", "create procedure p1 allow rx as select * from books;"); badDDLAgainstSimpleSchema(".*group rx that does not exist.*", "create role r1;", "create procedure p1 allow r1, rx as select * from books;"); } private int countStringsMatching(List<String> diagnostics, String pattern) { int count = 0; for (String string : diagnostics) { if (string.matches(pattern)) { ++count; } } return count; } }
false
true
public void testInvalidCreateProcedureDDL() throws Exception { ArrayList<Feedback> fbs; String expectedError; fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NonExistentPartitionParamInteger;" + "PARTITION PROCEDURE NonExistentPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Cannot load class for procedure: org.voltdb.compiler.procedures.NonExistentPartitionParamInteger"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "PARTITION PROCEDURE NotDefinedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Partition in referencing an undefined procedure \"NotDefinedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.PartitionParamInteger;" + "PARTITION PROCEDURE PartitionParamInteger ON TABLE PKEY_WHAAAT COLUMN PKEY;" ); expectedError = "PartitionParamInteger has partition properties defined both in class " + "\"org.voltdb.compiler.procedures.PartitionParamInteger\" and in the schema defintion file(s)"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_WHAAAT COLUMN PKEY;" ); expectedError = "PartitionInfo for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger refers to a column " + "in schema which can't be found."; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PSURROGATE;" ); expectedError = "PartitionInfo for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger refers to a column " + "in schema which can't be found."; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 8;" ); expectedError = "PartitionInfo specifies invalid parameter index for procedure: " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM GLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad CREATE PROCEDURE DDL statement: " + "\"CREATE PROCEDURE FROM GLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger\"" + ", expected syntax: \"CREATE PROCEDURE FROM CLASS <class-name>\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger FOR TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger FOR TABLE PKEY_INTEGER COLUMN PKEY\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER CLUMN PKEY PARMTR 0;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER CLUMN PKEY PARMTR 0\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER hello;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER hello\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROGEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER hello;" ); expectedError = "Bad PARTITION DDL statement: " + "\"PARTITION PROGEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER " + "COLUMN PKEY PARAMETER hello\", expected syntax: \"PARTITION TABLE <table> " + "ON COLUMN <column>\" or \"PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE OUTOF CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 2;" ); expectedError = "Bad CREATE PROCEDURE DDL statement: " + "\"CREATE PROCEDURE OUTOF CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger\"" + ", expected syntax: \"CREATE PROCEDURE FROM CLASS <class-name>\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "MAKE PROCEDURE OUTOF CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 2;" ); expectedError = "DDL Error: \"unexpected token: MAKE\" in statement starting on lineno: 1"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE 1PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN;" ); expectedError = "Bad indentifier in DDL: \"PARTITION TABLE 1PKEY_INTEGER ON COLUMN PKEY\" " + "contains invalid identifier \"1PKEY_INTEGER\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN 2PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \"PARTITION TABLE PKEY_INTEGER ON COLUMN 2PKEY\" " + "contains invalid identifier \"2PKEY\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS 0rg.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE FROM CLASS 0rg.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger" + "\" contains invalid identifier \"0rg.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.3compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE FROM CLASS org.voltdb.3compiler.procedures.NotAnnotatedPartitionParamInteger" + "\" contains invalid identifier \"org.voltdb.3compiler.procedures.NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.4NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.4NotAnnotatedPartitionParamInteger" + "\" contains invalid identifier \"org.voltdb.compiler.procedures.4NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE 5NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "PARTITION PROCEDURE 5NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY" + "\" contains invalid identifier \"5NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE 6PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE 6PKEY_INTEGER COLUMN PKEY" + "\" contains invalid identifier \"6PKEY_INTEGER\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN 7PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN 7PKEY" + "\" contains invalid identifier \"7PKEY\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger TABLE PKEY_INTEGER ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger TABLE PKEY_INTEGER ON TABLE PKEY_INTEGER COLUMN PKEY\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); }
public void testInvalidCreateProcedureDDL() throws Exception { ArrayList<Feedback> fbs; String expectedError; fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NonExistentPartitionParamInteger;" + "PARTITION PROCEDURE NonExistentPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Cannot load class for procedure: org.voltdb.compiler.procedures.NonExistentPartitionParamInteger"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "PARTITION PROCEDURE NotDefinedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Partition in referencing an undefined procedure \"NotDefinedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.PartitionParamInteger;" + "PARTITION PROCEDURE PartitionParamInteger ON TABLE PKEY_WHAAAT COLUMN PKEY;" ); expectedError = "PartitionParamInteger has partition properties defined both in class " + "\"org.voltdb.compiler.procedures.PartitionParamInteger\" and in the schema defintion file(s)"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_WHAAAT COLUMN PKEY;" ); expectedError = "PartitionInfo for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger refers to a column " + "in schema which can't be found."; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PSURROGATE;" ); expectedError = "PartitionInfo for procedure " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger refers to a column " + "in schema which can't be found."; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 8;" ); expectedError = "PartitionInfo specifies invalid parameter index for procedure: " + "org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM GLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad CREATE PROCEDURE DDL statement: " + "\"CREATE PROCEDURE FROM GLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger\"" + ", expected syntax: \"CREATE PROCEDURE"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger FOR TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger FOR TABLE PKEY_INTEGER COLUMN PKEY\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER CLUMN PKEY PARMTR 0;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER CLUMN PKEY PARMTR 0\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER hello;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER hello\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROGEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER hello;" ); expectedError = "Bad PARTITION DDL statement: " + "\"PARTITION PROGEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER " + "COLUMN PKEY PARAMETER hello\", expected syntax: \"PARTITION TABLE <table> " + "ON COLUMN <column>\" or \"PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE OUTOF CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 2;" ); expectedError = "Bad CREATE PROCEDURE DDL statement: " + "\"CREATE PROCEDURE OUTOF CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger\"" + ", expected syntax: \"CREATE PROCEDURE"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "MAKE PROCEDURE OUTOF CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY PARAMETER 2;" ); expectedError = "DDL Error: \"unexpected token: MAKE\" in statement starting on lineno: 1"; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE 1PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN;" ); expectedError = "Bad indentifier in DDL: \"PARTITION TABLE 1PKEY_INTEGER ON COLUMN PKEY\" " + "contains invalid identifier \"1PKEY_INTEGER\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN 2PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \"PARTITION TABLE PKEY_INTEGER ON COLUMN 2PKEY\" " + "contains invalid identifier \"2PKEY\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS 0rg.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE FROM CLASS 0rg.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger" + "\" contains invalid identifier \"0rg.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.3compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE FROM CLASS org.voltdb.3compiler.procedures.NotAnnotatedPartitionParamInteger" + "\" contains invalid identifier \"org.voltdb.3compiler.procedures.NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.4NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.4NotAnnotatedPartitionParamInteger" + "\" contains invalid identifier \"org.voltdb.compiler.procedures.4NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE 5NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "PARTITION PROCEDURE 5NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN PKEY" + "\" contains invalid identifier \"5NotAnnotatedPartitionParamInteger\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE 6PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE 6PKEY_INTEGER COLUMN PKEY" + "\" contains invalid identifier \"6PKEY_INTEGER\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN 7PKEY;" ); expectedError = "Bad indentifier in DDL: \""+ "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger ON TABLE PKEY_INTEGER COLUMN 7PKEY" + "\" contains invalid identifier \"7PKEY\""; assertTrue(isFeedbackPresent(expectedError, fbs)); fbs = checkInvalidProcedureDDL( "CREATE TABLE PKEY_INTEGER ( PKEY INTEGER NOT NULL, PRIMARY KEY (PKEY) );" + "PARTITION TABLE PKEY_INTEGER ON COLUMN PKEY;" + "CREATE PROCEDURE FROM CLASS org.voltdb.compiler.procedures.NotAnnotatedPartitionParamInteger;" + "PARTITION PROCEDURE NotAnnotatedPartitionParamInteger TABLE PKEY_INTEGER ON TABLE PKEY_INTEGER COLUMN PKEY;" ); expectedError = "Bad PARTITION DDL statement: \"PARTITION PROCEDURE " + "NotAnnotatedPartitionParamInteger TABLE PKEY_INTEGER ON TABLE PKEY_INTEGER COLUMN PKEY\", " + "expected syntax: PARTITION PROCEDURE <procedure> ON " + "TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]"; assertTrue(isFeedbackPresent(expectedError, fbs)); }
diff --git a/WoT.java b/WoT.java index 7ff9d0d2..c3fa91b6 100644 --- a/WoT.java +++ b/WoT.java @@ -1,894 +1,894 @@ /** * This code is part of WoT, a plugin for Freenet. It is distributed * under the GNU General Public License, version 2 (or at your option * any later version). See http://www.gnu.org/ for details of the GPL. */ package plugins.WoT; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.UUID; import java.util.Map.Entry; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import plugins.WoT.exceptions.DuplicateIdentityException; import plugins.WoT.exceptions.DuplicateScoreException; import plugins.WoT.exceptions.DuplicateTrustException; import plugins.WoT.exceptions.InvalidParameterException; import plugins.WoT.exceptions.NotInTrustTreeException; import plugins.WoT.exceptions.NotTrustedException; import plugins.WoT.exceptions.UnknownIdentityException; import plugins.WoT.introduction.IntroductionClient; import plugins.WoT.introduction.IntroductionPuzzle; import plugins.WoT.introduction.IntroductionServer; import plugins.WoT.ui.web.HomePage; import plugins.WoT.ui.web.IntroduceIdentityPage; import plugins.WoT.ui.web.KnownIdentitiesPage; import plugins.WoT.ui.web.OwnIdentitiesPage; import plugins.WoT.ui.web.WebPage; import plugins.WoT.ui.web.ConfigurationPage; import plugins.WoT.ui.web.TrustersPage; import plugins.WoT.ui.web.TrusteesPage; import plugins.WoT.ui.web.CreateIdentityPage; import plugins.WoT.ui.web.WebPageImpl; import com.db4o.Db4o; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.config.Configuration; import com.db4o.ext.DatabaseClosedException; import com.db4o.ext.Db4oIOException; import com.db4o.query.Query; import freenet.client.FetchException; import freenet.client.HighLevelSimpleClient; import freenet.client.InsertException; import freenet.clients.http.PageMaker; import freenet.keys.FreenetURI; import freenet.l10n.L10n.LANGUAGE; import freenet.pluginmanager.FredPlugin; import freenet.pluginmanager.FredPluginFCP; import freenet.pluginmanager.FredPluginHTTP; import freenet.pluginmanager.FredPluginL10n; import freenet.pluginmanager.FredPluginThreadless; import freenet.pluginmanager.FredPluginVersioned; import freenet.pluginmanager.PluginHTTPException; import freenet.pluginmanager.PluginReplySender; import freenet.pluginmanager.PluginRespirator; import freenet.support.Logger; import freenet.support.SimpleFieldSet; import freenet.support.api.Bucket; import freenet.support.api.HTTPRequest; /** * @author Julien Cornuwel ([email protected]) */ public class WoT implements FredPlugin, FredPluginHTTP, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginL10n { /* References from the node */ private PluginRespirator pr; private HighLevelSimpleClient client; private PageMaker pm; /* References from the plugin itself */ private ObjectContainer db; private WebInterface web; private IdentityInserter inserter; private IdentityFetcher fetcher; private IntroductionServer introductionServer; private IntroductionClient introductionClient; private String seedURI = "USK@MF2Vc6FRgeFMZJ0s2l9hOop87EYWAydUZakJzL0OfV8,fQeN-RMQZsUrDha2LCJWOMFk1-EiXZxfTnBT8NEgY00,AQACAAE/WoT/1"; private Identity seed = null; private Config config; public static final String SELF_URI = "/plugins/plugins.WoT.WoT"; public static final String WOT_CONTEXT = "WoT"; public void runPlugin(PluginRespirator pr) { Logger.debug(this, "Start"); /* Catpcha generation needs headless mode on linux */ System.setProperty("java.awt.headless", "true"); this.db = initDB(); this.pr = pr; client = pr.getHLSimpleClient(); config = initConfig(); seed = getSeedIdentity(); pm = pr.getPageMaker(); /* FIXME: i cannot get this to work, it does not print any objects although there are definitely IntroductionPuzzle objects in my db. HashSet<Class> WoTclasses = new HashSet<Class>(Arrays.asList(new Class[]{ Identity.class, OwnIdentity.class, Trust.class, Score.class })); Logger.debug(this, "Non-WoT objects in WoT database: "); Query q = db.query(); for(Class c : WoTclasses) q.constrain(c).not(); ObjectSet<Object> objects = q.execute(); for(Object o : objects) { Logger.debug(this, o.toString()); } */ // Should disappear soon. web = new WebInterface(pr, db, config, client, SELF_URI); // Create a default OwnIdentity if none exists. Should speed up plugin usability for newbies if(OwnIdentity.getNbOwnIdentities(db) == 0) { try { createIdentity("Anonymous", true, "freetalk"); } catch (Exception e) { Logger.error(this, "Error creating default identity : ", e); } } // Start the inserter thread inserter = new IdentityInserter(db, client, pr.getNode().clientCore.tempBucketFactory); pr.getNode().executor.execute(inserter, "WoTinserter"); // Create the fetcher fetcher = new IdentityFetcher(db, client); fetcher.fetch(seed, false); try { ObjectSet<OwnIdentity> oids = db.queryByExample(OwnIdentity.class); for(OwnIdentity oid : oids) oid.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT, db); } catch(InvalidParameterException e) {} introductionServer = new IntroductionServer(db, client, pr.getNode().clientCore.tempBucketFactory, fetcher); pr.getNode().executor.execute(introductionServer, "WoT introduction server"); introductionClient = new IntroductionClient(db, client, pr.getNode().clientCore.tempBucketFactory); pr.getNode().executor.execute(introductionClient, "WoT introduction client"); // Try to fetch all known identities ObjectSet<Identity> identities = Identity.getAllIdentities(db); while (identities.hasNext()) { fetcher.fetch(identities.next(), true); } } public void terminate() { Logger.debug(this, "WoT plugin terminating ..."); if(inserter != null) inserter.stop(); if(introductionServer != null) introductionServer.terminate(); if(introductionClient != null) introductionClient.terminate(); if(fetcher != null) fetcher.stop(); if(db != null) { db.commit(); db.close(); } Logger.debug(this, "WoT plugin terminated."); } public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException { WebPage page; if(request.isParameterSet("ownidentities")) page = new OwnIdentitiesPage(this, request); else if(request.isParameterSet("knownidentities")) page = new KnownIdentitiesPage(this, request); else if(request.isParameterSet("configuration")) page = new ConfigurationPage(this, request); // TODO Handle these two in KnownIdentitiesPage else if(request.isParameterSet("getTrusters")) page = new TrustersPage(this, request); else if(request.isParameterSet("getTrustees")) page = new TrusteesPage(this, request); else if(request.isParameterSet("puzzle")) { IntroductionPuzzle p = IntroductionPuzzle.getByID(db, UUID.fromString(request.getParam("id"))); if(p != null) { byte[] data = p.getData(); } /* FIXME: The current PluginManager implementation allows plugins only to send HTML replies. * Implement general replying with any mime type and return the jpeg. */ return ""; } else page = new HomePage(this, request); page.make(); return page.toHTML(); } public String handleHTTPPost(HTTPRequest request) throws PluginHTTPException { WebPage page; String pass = request.getPartAsString("formPassword", 32); if ((pass.length() == 0) || !pass.equals(pr.getNode().clientCore.formPassword)) { return "Buh! Invalid form password"; } // TODO: finish refactoring to "page = new ..." try { String pageTitle = request.getPartAsString("page",50); if(pageTitle.equals("createIdentity")) page = new CreateIdentityPage(this, request); else if(pageTitle.equals("createIdentity2")) { createIdentity(request); page = new OwnIdentitiesPage(this, request); } else if(pageTitle.equals("addIdentity")) { addIdentity(request); page = new KnownIdentitiesPage(this, request); } else if(pageTitle.equals("viewTree")) { page = new KnownIdentitiesPage(this, request); } else if(pageTitle.equals("setTrust")) { setTrust(request); return web.makeKnownIdentitiesPage(request.getPartAsString("truster", 1024)); } else if(pageTitle.equals("editIdentity")) { return web.makeEditIdentityPage(request.getPartAsString("id", 1024)); } else if(pageTitle.equals("introduceIdentity")) { page = new IntroduceIdentityPage(this, request, introductionClient, OwnIdentity.getById(db, request.getPartAsString("identity", 128))); } else if(pageTitle.equals("restoreIdentity")) { restoreIdentity(request.getPartAsString("requestURI", 1024), request.getPartAsString("insertURI", 1024)); page = new OwnIdentitiesPage(this, request); } else if(pageTitle.equals("deleteIdentity")) { return web.makeDeleteIdentityPage(request.getPartAsString("id", 1024)); } else if(pageTitle.equals("deleteIdentity2")) { deleteIdentity(request.getPartAsString("id", 1024)); page = new OwnIdentitiesPage(this, request); } else { page = new HomePage(this, request); } page.make(); return page.toHTML(); } catch (Exception e) { e.printStackTrace(); return e.getLocalizedMessage(); } } public String handleHTTPPut(HTTPRequest request) throws PluginHTTPException { return "Go to hell"; } private void deleteIdentity(String id) throws DuplicateIdentityException, UnknownIdentityException, DuplicateScoreException, DuplicateTrustException { Identity identity = Identity.getById(db, id); // Remove all scores ObjectSet<Score> scores = identity.getScores(db); while (scores.hasNext()) db.delete(scores.next()); // Remove all received trusts ObjectSet<Trust> receivedTrusts = identity.getReceivedTrusts(db); while (receivedTrusts.hasNext()) db.delete(receivedTrusts.next()); // Remove all given trusts and update trustees' scores ObjectSet<Trust> givenTrusts = identity.getGivenTrusts(db); while (givenTrusts.hasNext()) { Trust givenTrust = givenTrusts.next(); db.delete(givenTrust); givenTrust.getTrustee().updateScore(db); } db.delete(identity); } private void restoreIdentity(String requestURI, String insertURI) throws InvalidParameterException, MalformedURLException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, DuplicateTrustException { OwnIdentity id; try { Identity old = Identity.getByURI(db, requestURI); // We already have fetched this identity as a stranger's one. We need to update the database. id = new OwnIdentity(new FreenetURI(insertURI), new FreenetURI(requestURI), old.getNickName(), old.doesPublishTrustList()); id.setEdition(old.getEdition()); Iterator<String> i1 = old.getContexts(); while (i1.hasNext()) id.addContext(i1.next(), db); Iterator<Entry<String, String>> i2 = old.getProps(); while (i2.hasNext()) { Entry<String, String> prop = i2.next(); id.setProp(prop.getKey(), prop.getValue(), db); } // Update all received trusts ObjectSet<Trust> receivedTrusts = old.getReceivedTrusts(db); while(receivedTrusts.hasNext()) { Trust receivedTrust = receivedTrusts.next(); Trust newReceivedTrust = new Trust(receivedTrust.getTruster(), id, receivedTrust.getValue(), receivedTrust.getComment()); db.delete(receivedTrust); db.store(newReceivedTrust); } // Update all received scores ObjectSet<Score> scores = old.getScores(db); while(scores.hasNext()) { Score score = scores.next(); Score newScore = new Score(score.getTreeOwner(), id, score.getScore(), score.getRank(), score.getCapacity()); db.delete(score); db.store(newScore); } // Store the new identity db.store(id); id.initTrustTree(db); // Update all given trusts ObjectSet<Trust> givenTrusts = old.getGivenTrusts(db); while(givenTrusts.hasNext()) { Trust givenTrust = givenTrusts.next(); id.setTrust(db, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); db.delete(givenTrust); } // Remove the old identity db.delete(old); Logger.debug(this, "Successfully restored an already known identity from Freenet (" + id.getNickName() + ")"); } catch (UnknownIdentityException e) { - id = new OwnIdentity(new FreenetURI(insertURI), new FreenetURI(requestURI), "Restore in progress...", false); + id = new OwnIdentity(new FreenetURI(insertURI), new FreenetURI(requestURI), null, false); // Store the new identity db.store(id); id.initTrustTree(db); // Fetch the identity from freenet fetcher.fetch(id); Logger.debug(this, "Trying to restore a not-yet-known identity from Freenet (" + id.getRequestURI() + ")"); } db.commit(); } private void setTrust(HTTPRequest request) throws NumberFormatException, TransformerConfigurationException, FileNotFoundException, InvalidParameterException, UnknownIdentityException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { setTrust( request.getPartAsString("truster", 1024), request.getPartAsString("trustee", 1024), request.getPartAsString("value", 4), request.getPartAsString("comment", 256)); } private void setTrust(String truster, String trustee, String value, String comment) throws InvalidParameterException, UnknownIdentityException, NumberFormatException, TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { OwnIdentity trusterId = OwnIdentity.getByURI(db, truster); Identity trusteeId = Identity.getByURI(db, trustee); setTrust((OwnIdentity)trusterId, trusteeId, Byte.parseByte(value), comment); } private void setTrust(OwnIdentity truster, Identity trustee, byte value, String comment) throws TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, InvalidParameterException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { truster.setTrust(db, trustee, value, comment); truster.updated(); db.store(truster); db.commit(); } private void addIdentity(HTTPRequest request) throws MalformedURLException, InvalidParameterException, FetchException, DuplicateIdentityException { addIdentity(request.getPartAsString("identityURI", 1024).trim()); } private Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException, FetchException, DuplicateIdentityException { Identity identity = null; try { identity = Identity.getByURI(db, requestURI); Logger.error(this, "Tried to manually add an identity we already know, ignored."); throw new InvalidParameterException("We already have this identity"); } catch (UnknownIdentityException e) { identity = new Identity(new FreenetURI(requestURI), null, false); db.store(identity); db.commit(); Logger.debug(this, "Trying to fetch manually added identity (" + identity.getRequestURI() + ")"); fetcher.fetch(identity); } return identity; } private OwnIdentity createIdentity(HTTPRequest request) throws TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { return createIdentity( request.getPartAsString("insertURI",1024), request.getPartAsString("requestURI",1024), request.getPartAsString("nickName", 1024), request.getPartAsString("publishTrustList", 5).equals("true"), "freetalk"); } private OwnIdentity createIdentity(String nickName, boolean publishTrustList, String context) throws TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { FreenetURI[] keypair = client.generateKeyPair("WoT"); return createIdentity(keypair[0].toString(), keypair[1].toString(), nickName, publishTrustList, context); } private OwnIdentity createIdentity(String insertURI, String requestURI, String nickName, boolean publishTrustList, String context) throws InvalidParameterException, TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { OwnIdentity identity = new OwnIdentity(new FreenetURI(insertURI), new FreenetURI(requestURI), nickName, publishTrustList); identity.addContext(context, db); identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT, db); /* fixme: make configureable */ db.store(identity); identity.initTrustTree(db); // This identity trusts the seed identity identity.setTrust(db, seed, (byte)100, "I trust the WoT plugin"); db.commit(); inserter.wakeUp(); Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickName() + ")"); return identity; } private void addContext(String identity, String context) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { Identity id = OwnIdentity.getByURI(db, identity); id.addContext(context, db); db.store(id); Logger.debug(this, "Added context '" + context + "' to identity '" + id.getNickName() + "'"); } private void removeContext(String identity, String context) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { Identity id = OwnIdentity.getByURI(db, identity); id.removeContext(context, db); db.store(id); Logger.debug(this, "Removed context '" + context + "' from identity '" + id.getNickName() + "'"); } private void setProperty(String identity, String property, String value) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { Identity id = OwnIdentity.getByURI(db, identity); id.setProp(property, value, db); db.store(id); Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + id.getNickName() + "'"); } private String getProperty(String identity, String property) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { return Identity.getByURI(db, identity).getProp(property); } private void removeProperty(String identity, String property) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { Identity id = OwnIdentity.getByURI(db, identity); id.removeProp(property, db); db.store(id); Logger.debug(this, "Removed property '" + property + "' from identity '" + id.getNickName() + "'"); } public String getVersion() { return "0.3.1 r"+Version.getSvnRevision(); } public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { try { if(params.get("Message").equals("CreateIdentity")) { replysender.send(handleCreateIdentity(params), data); } else if(params.get("Message").equals("SetTrust")) { replysender.send(handleSetTrust(params), data); } else if(params.get("Message").equals("AddIdentity")) { replysender.send(handleAddIdentity(params), data); } else if(params.get("Message").equals("GetIdentity")) { replysender.send(handleGetIdentity(params), data); } else if(params.get("Message").equals("GetOwnIdentities")) { replysender.send(handleGetOwnIdentities(params), data); } else if(params.get("Message").equals("GetIdentitiesByScore")) { replysender.send(handleGetIdentitiesByScore(params), data); } else if(params.get("Message").equals("GetTrusters")) { replysender.send(handleGetTrusters(params), data); } else if(params.get("Message").equals("GetTrustees")) { replysender.send(handleGetTrustees(params), data); } else if(params.get("Message").equals("AddContext")) { replysender.send(handleAddContext(params), data); } else if(params.get("Message").equals("RemoveContext")) { replysender.send(handleRemoveContext(params), data); } else if(params.get("Message").equals("SetProperty")) { replysender.send(handleSetProperty(params), data); } else if(params.get("Message").equals("GetProperty")) { replysender.send(handleGetProperty(params), data); } else if(params.get("Message").equals("RemoveProperty")) { replysender.send(handleRemoveProperty(params), data); } else { throw new Exception("Unknown message (" + params.get("Message") + ")"); } } catch (Exception e) { Logger.error(this, e.toString()); replysender.send(errorMessageFCP(e), data); } } private SimpleFieldSet handleCreateIdentity(SimpleFieldSet params) throws TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, NotTrustedException, DuplicateTrustException { SimpleFieldSet sfs = new SimpleFieldSet(true); OwnIdentity identity; if(params.get("NickName")==null || params.get("PublishTrustList")==null || params.get("Context")==null) throw new InvalidParameterException("Missing mandatory parameter"); if(params.get("RequestURI")==null || params.get("InsertURI")==null) { identity = createIdentity(params.get("NickName"), params.get("PublishTrustList").equals("true"), params.get("Context")); } else { identity = createIdentity( params.get("InsertURI"), params.get("RequestURI"), params.get("NickName"), params.get("PublishTrustList").equals("true"), params.get("Context")); } sfs.putAppend("Message", "IdentityCreated"); sfs.putAppend("InsertURI", identity.getInsertURI().toString()); sfs.putAppend("RequestURI", identity.getRequestURI().toString()); return sfs; } private SimpleFieldSet handleSetTrust(SimpleFieldSet params) throws NumberFormatException, TransformerConfigurationException, FileNotFoundException, InvalidParameterException, ParserConfigurationException, TransformerException, IOException, InsertException, UnknownIdentityException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, NotTrustedException, DuplicateTrustException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("Truster") == null || params.get("Trustee") == null || params.get("Value") == null || params.get("Comment") == null) throw new InvalidParameterException("Missing mandatory parameter"); setTrust(params.get("Truster"), params.get("Trustee"), params.get("Value"), params.get("Comment")); sfs.putAppend("Message", "TrustSet"); return sfs; } private SimpleFieldSet handleAddIdentity(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, FetchException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("RequestURI") == null) throw new InvalidParameterException("Missing mandatory parameter"); Identity identity = addIdentity(params.get("RequestURI").trim()); sfs.putAppend("Message", "IdentityAdded"); sfs.putAppend("RequestURI", identity.getRequestURI().toString()); return sfs; } private SimpleFieldSet handleGetIdentity(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, FetchException, UnknownIdentityException, DuplicateScoreException, DuplicateIdentityException, DuplicateTrustException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("TreeOwner") == null || params.get("Identity") == null) throw new InvalidParameterException("Missing mandatory parameter"); sfs.putAppend("Message", "Identity"); OwnIdentity treeOwner = OwnIdentity.getByURI(db, params.get("TreeOwner")); Identity identity = Identity.getByURI(db, params.get("Identity")); try { Trust trust = identity.getReceivedTrust(treeOwner, db); sfs.putAppend("Trust", String.valueOf(trust.getValue())); } catch (NotTrustedException e1) { sfs.putAppend("Trust", "null"); } Score score; try { score = identity.getScore(treeOwner, db); sfs.putAppend("Score", String.valueOf(score.getScore())); sfs.putAppend("Rank", String.valueOf(score.getRank())); } catch (NotInTrustTreeException e) { sfs.putAppend("Score", "null"); sfs.putAppend("Rank", "null"); } Iterator<String> contexts = identity.getContexts(); for(int i = 1 ; contexts.hasNext() ; i++) sfs.putAppend("Context"+i, contexts.next()); return sfs; } /* would only be needed if we connect the client plugins directly via object references which will probably not happen public List<Identity> getIdentitiesByScore(OwnIdentity treeOwner, int select, String context) throws InvalidParameterException { ObjectSet<Score> result = Score.getIdentitiesByScore(db, treeOwner, select); // TODO: decide whether the tradeoff of using too much memory for the ArrayList is worth the speedup of not having a linked // list which allocates lots of pieces of memory for its nodes. trimToSize() is not an option because the List usually will be // used only temporarily. ArrayList<Identity> identities = new ArrayList<Identity>(result.size()); boolean getAll = context.equals("all"); while(result.hasNext()) { Identity identity = result.next().getTarget(); // TODO: Maybe there is a way to do this through SODA if(getAll || identity.hasContext(context)) identities.add(identity); } return identities; } */ private SimpleFieldSet handleGetOwnIdentities(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); sfs.putAppend("Message", "OwnIdentities"); ObjectSet<OwnIdentity> result = OwnIdentity.getAllOwnIdentities(db); for(int idx = 1 ; result.hasNext() ; idx++) { OwnIdentity oid = result.next(); /* FIXME: Isn't append slower than replace? Figure this out */ sfs.putAppend("Identity"+idx, oid.getId()); sfs.putAppend("RequestURI"+idx, oid.getRequestURI().toString()); sfs.putAppend("InsertURI"+idx, oid.getInsertURI().toString()); sfs.putAppend("Nickname"+idx, oid.getNickName()); /* FIXME: Allow the client to select what data he wants */ } return sfs; } private SimpleFieldSet handleGetIdentitiesByScore(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("Select") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); sfs.putAppend("Message", "Identities"); OwnIdentity treeOwner = params.get("TreeOwner")!=null ? OwnIdentity.getByURI(db, params.get("TreeOwner")) : null; String selectString = params.get("Select").trim(); int select = 0; // TODO: decide about the default value if(selectString.equals("+")) select = 1; else if(selectString.equals("-")) select = -1; else if(selectString.equals("0")) select = 0; else throw new InvalidParameterException("Unhandled select value ("+select+")"); ObjectSet<Score> result = Score.getIdentitiesByScore(db, treeOwner, select); String context = params.get("Context"); boolean getAll = context.equals("all"); for(int idx = 1 ; result.hasNext() ; idx++) { Score score = result.next(); // TODO: Maybe there is a way to do this through SODA if(getAll || score.getTarget().hasContext(context)) { Identity id = score.getTarget(); /* FIXME: Isn't append slower than replace? Figure this out */ sfs.putAppend("Identity"+idx, id.getId()); sfs.putAppend("RequestURI"+idx, id.getRequestURI().toString()); sfs.putAppend("Nickname"+idx, id.getNickName()); /* FIXME: Allow the client to select what data he wants */ } } return sfs; } private SimpleFieldSet handleGetTrusters(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, Db4oIOException, DatabaseClosedException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); sfs.putAppend("Message", "Identities"); ObjectSet<Trust> result = Identity.getByURI(db, params.get("Identity")).getReceivedTrusts(db); for(int i = 1 ; result.hasNext() ; i++) { Trust trust = result.next(); // Maybe there is a way to do this through SODA if(trust.getTruster().hasContext(params.get("Context")) || params.get("Context").equals("all")) { sfs.putAppend("Identity"+i, trust.getTruster().getRequestURI().toString()); sfs.putAppend("Value"+i, String.valueOf(trust.getValue())); sfs.putAppend("Comment"+i, trust.getComment()); } } return sfs; } private SimpleFieldSet handleGetTrustees(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, Db4oIOException, DatabaseClosedException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); sfs.putAppend("Message", "Identities"); ObjectSet<Trust> result = Identity.getByURI(db, params.get("Identity")).getGivenTrusts(db); for(int i = 1 ; result.hasNext() ; i++) { Trust trust = result.next(); // Maybe there is a way to do this through SODA if(trust.getTrustee().hasContext(params.get("Context")) || params.get("Context").equals("all")) { sfs.putAppend("Identity"+i, trust.getTrustee().getRequestURI().toString()); sfs.putAppend("Value"+i, String.valueOf(trust.getValue())); sfs.putAppend("Comment"+i, trust.getComment()); } } return sfs; } private SimpleFieldSet handleAddContext(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); addContext(params.get("Identity"), params.get("Context")); sfs.putAppend("Message", "ContextAdded"); return sfs; } private SimpleFieldSet handleRemoveContext(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("Identity") == null || params.get("Context") == null) throw new InvalidParameterException("Missing mandatory parameter"); removeContext(params.get("Identity"), params.get("Context")); sfs.putAppend("Message", "ContextRemoved"); return sfs; } private SimpleFieldSet handleSetProperty(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("Identity") == null || params.get("Property") == null || params.get("Value") == null) throw new InvalidParameterException("Missing mandatory parameter"); setProperty(params.get("Identity"), params.get("Property"), params.get("Value")); sfs.putAppend("Message", "PropertyAdded"); return sfs; } private SimpleFieldSet handleGetProperty(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("Identity") == null || params.get("Property") == null) throw new InvalidParameterException("Missing mandatory parameter"); sfs.putAppend("Message", "PropertyValue"); sfs.putAppend("Property", getProperty(params.get("Identity"), params.get("Property"))); return sfs; } private SimpleFieldSet handleRemoveProperty(SimpleFieldSet params) throws InvalidParameterException, MalformedURLException, UnknownIdentityException, DuplicateIdentityException { SimpleFieldSet sfs = new SimpleFieldSet(true); if(params.get("Identity") == null || params.get("Property") == null) throw new InvalidParameterException("Missing mandatory parameter"); removeProperty(params.get("Identity"), params.get("Property")); sfs.putAppend("Message", "PropertyRemoved"); return sfs; } private SimpleFieldSet errorMessageFCP (Exception e) { SimpleFieldSet sfs = new SimpleFieldSet(true); sfs.putAppend("Message", "Error"); sfs.putAppend("Description", (e.getLocalizedMessage() == null) ? "null" : e.getLocalizedMessage()); e.printStackTrace(); return sfs; } public String getString(String key) { return key; } public void setLanguage(LANGUAGE newLanguage) { } /** * Initializes the connection to DB4O. * * @return db4o's connector */ private ObjectContainer initDB() { // Set indexes on fields we query on Configuration cfg = Db4o.newConfiguration(); cfg.objectClass(Identity.class).objectField("id").indexed(true); cfg.objectClass(OwnIdentity.class).objectField("id").indexed(true); cfg.objectClass(Trust.class).objectField("truster").indexed(true); cfg.objectClass(Trust.class).objectField("trustee").indexed(true); cfg.objectClass(Score.class).objectField("treeOwner").indexed(true); cfg.objectClass(Score.class).objectField("target").indexed(true); for(String field : IntroductionPuzzle.getIndexedFields()) cfg.objectClass(IntroductionPuzzle.class).objectField(field).indexed(true); cfg.objectClass(IntroductionPuzzle.class).cascadeOnUpdate(true); /* FIXME: verify if this does not break anything */ // This will make db4o store any complex objects which are referenced by a Config object. cfg.objectClass(Config.class).cascadeOnUpdate(true); return Db4o.openFile(cfg, "WoT.db4o"); } /** * Loads the config of the plugin, or creates it with default values if it doesn't exist. * * @return config of the plugin */ private Config initConfig() { ObjectSet<Config> result = db.queryByExample(Config.class); if(result.size() == 0) { Logger.debug(this, "Created new config"); config = new Config(); db.store(config); } else { Logger.debug(this, "Loaded config"); config = result.next(); config.initDefault(false); } return config; } public Identity getSeedIdentity() { if(seed == null) { // The seed identity hasn't been initialized yet try { // Try to load it from database seed = Identity.getByURI(db, seedURI); } catch (UnknownIdentityException e) { // Create it. try { // Create the seed identity seed = new Identity(new FreenetURI(seedURI), null, true); seed.setEdition(seed.getRequestURI().getSuggestedEdition()); } catch (Exception e1) { // Should never happen Logger.error(this, "Seed identity creation error", e1); return null; } db.store(seed); db.commit(); } catch (Exception e) { // Should never happen Logger.error(this, "Seed identity loading error", e); return null; } } return seed; } public PageMaker getPageMaker() { return pm; } public ObjectContainer getDB() { return db; } public PluginRespirator getPR() { return pr; } public HighLevelSimpleClient getClient() { return client; } }
true
true
private void restoreIdentity(String requestURI, String insertURI) throws InvalidParameterException, MalformedURLException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, DuplicateTrustException { OwnIdentity id; try { Identity old = Identity.getByURI(db, requestURI); // We already have fetched this identity as a stranger's one. We need to update the database. id = new OwnIdentity(new FreenetURI(insertURI), new FreenetURI(requestURI), old.getNickName(), old.doesPublishTrustList()); id.setEdition(old.getEdition()); Iterator<String> i1 = old.getContexts(); while (i1.hasNext()) id.addContext(i1.next(), db); Iterator<Entry<String, String>> i2 = old.getProps(); while (i2.hasNext()) { Entry<String, String> prop = i2.next(); id.setProp(prop.getKey(), prop.getValue(), db); } // Update all received trusts ObjectSet<Trust> receivedTrusts = old.getReceivedTrusts(db); while(receivedTrusts.hasNext()) { Trust receivedTrust = receivedTrusts.next(); Trust newReceivedTrust = new Trust(receivedTrust.getTruster(), id, receivedTrust.getValue(), receivedTrust.getComment()); db.delete(receivedTrust); db.store(newReceivedTrust); } // Update all received scores ObjectSet<Score> scores = old.getScores(db); while(scores.hasNext()) { Score score = scores.next(); Score newScore = new Score(score.getTreeOwner(), id, score.getScore(), score.getRank(), score.getCapacity()); db.delete(score); db.store(newScore); } // Store the new identity db.store(id); id.initTrustTree(db); // Update all given trusts ObjectSet<Trust> givenTrusts = old.getGivenTrusts(db); while(givenTrusts.hasNext()) { Trust givenTrust = givenTrusts.next(); id.setTrust(db, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); db.delete(givenTrust); } // Remove the old identity db.delete(old); Logger.debug(this, "Successfully restored an already known identity from Freenet (" + id.getNickName() + ")"); } catch (UnknownIdentityException e) { id = new OwnIdentity(new FreenetURI(insertURI), new FreenetURI(requestURI), "Restore in progress...", false); // Store the new identity db.store(id); id.initTrustTree(db); // Fetch the identity from freenet fetcher.fetch(id); Logger.debug(this, "Trying to restore a not-yet-known identity from Freenet (" + id.getRequestURI() + ")"); } db.commit(); }
private void restoreIdentity(String requestURI, String insertURI) throws InvalidParameterException, MalformedURLException, Db4oIOException, DatabaseClosedException, DuplicateScoreException, DuplicateIdentityException, DuplicateTrustException { OwnIdentity id; try { Identity old = Identity.getByURI(db, requestURI); // We already have fetched this identity as a stranger's one. We need to update the database. id = new OwnIdentity(new FreenetURI(insertURI), new FreenetURI(requestURI), old.getNickName(), old.doesPublishTrustList()); id.setEdition(old.getEdition()); Iterator<String> i1 = old.getContexts(); while (i1.hasNext()) id.addContext(i1.next(), db); Iterator<Entry<String, String>> i2 = old.getProps(); while (i2.hasNext()) { Entry<String, String> prop = i2.next(); id.setProp(prop.getKey(), prop.getValue(), db); } // Update all received trusts ObjectSet<Trust> receivedTrusts = old.getReceivedTrusts(db); while(receivedTrusts.hasNext()) { Trust receivedTrust = receivedTrusts.next(); Trust newReceivedTrust = new Trust(receivedTrust.getTruster(), id, receivedTrust.getValue(), receivedTrust.getComment()); db.delete(receivedTrust); db.store(newReceivedTrust); } // Update all received scores ObjectSet<Score> scores = old.getScores(db); while(scores.hasNext()) { Score score = scores.next(); Score newScore = new Score(score.getTreeOwner(), id, score.getScore(), score.getRank(), score.getCapacity()); db.delete(score); db.store(newScore); } // Store the new identity db.store(id); id.initTrustTree(db); // Update all given trusts ObjectSet<Trust> givenTrusts = old.getGivenTrusts(db); while(givenTrusts.hasNext()) { Trust givenTrust = givenTrusts.next(); id.setTrust(db, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); db.delete(givenTrust); } // Remove the old identity db.delete(old); Logger.debug(this, "Successfully restored an already known identity from Freenet (" + id.getNickName() + ")"); } catch (UnknownIdentityException e) { id = new OwnIdentity(new FreenetURI(insertURI), new FreenetURI(requestURI), null, false); // Store the new identity db.store(id); id.initTrustTree(db); // Fetch the identity from freenet fetcher.fetch(id); Logger.debug(this, "Trying to restore a not-yet-known identity from Freenet (" + id.getRequestURI() + ")"); } db.commit(); }
diff --git a/appengine/c2dm/com/browsertophone/c2dm/server/C2DMConfigLoader.java b/appengine/c2dm/com/browsertophone/c2dm/server/C2DMConfigLoader.java index 6c9400f..e853a15 100644 --- a/appengine/c2dm/com/browsertophone/c2dm/server/C2DMConfigLoader.java +++ b/appengine/c2dm/com/browsertophone/c2dm/server/C2DMConfigLoader.java @@ -1,129 +1,129 @@ /* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.browsertophone.c2dm.server; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; /** * Stores config information related to data messaging. * */ class C2DMConfigLoader { private final PersistenceManagerFactory PMF; private static final Logger log = Logger.getLogger(C2DMConfigLoader.class.getName()); String currentToken; String c2dmUrl; C2DMConfigLoader(PersistenceManagerFactory pmf) { this.PMF = pmf; } /** * Update the token. * * Called on "Update-Client-Auth" or when admins set a new token. * @param token */ public void updateToken(String token) { if (token != null) { currentToken = token; PersistenceManager pm = PMF.getPersistenceManager(); try { getDataMessagingConfig(pm).setAuthToken(token); } finally { pm.close(); } } } /** * Token expired */ public void invalidateCachedToken() { currentToken = null; } /** * Return the auth token from the database. Should be called * only if the old token expired. * * @return */ public String getToken() { if (currentToken == null) { currentToken = getDataMessagingConfig().getAuthToken(); } return currentToken; } public String getC2DMUrl() { if (c2dmUrl == null) { c2dmUrl = getDataMessagingConfig().getC2DMUrl(); } return c2dmUrl; } public C2DMConfig getDataMessagingConfig() { PersistenceManager pm = PMF.getPersistenceManager(); try { C2DMConfig dynamicConfig = getDataMessagingConfig(pm); return dynamicConfig; } finally { pm.close(); } } private C2DMConfig getDataMessagingConfig(PersistenceManager pm) { Key key = KeyFactory.createKey(C2DMConfig.class.getSimpleName(), 1); C2DMConfig dmConfig = null; try { dmConfig = pm.getObjectById(C2DMConfig.class, key); } catch (JDOObjectNotFoundException e) { // Create a new JDO object dmConfig = new C2DMConfig(); dmConfig.setKey(key); // Must be in classpath, before sending. Do not checkin ! try { - InputStream is = this.getClass().getClassLoader().getResourceAsStream("/dataMessagingToken.txt"); + InputStream is = this.getClass().getClassLoader().getResourceAsStream("dataMessagingToken.txt"); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String token = reader.readLine(); dmConfig.setAuthToken(token); } } catch (Throwable t) { log.log(Level.SEVERE, "Can't load initial token, use admin console", t); } pm.makePersistent(dmConfig); } return dmConfig; } }
true
true
private C2DMConfig getDataMessagingConfig(PersistenceManager pm) { Key key = KeyFactory.createKey(C2DMConfig.class.getSimpleName(), 1); C2DMConfig dmConfig = null; try { dmConfig = pm.getObjectById(C2DMConfig.class, key); } catch (JDOObjectNotFoundException e) { // Create a new JDO object dmConfig = new C2DMConfig(); dmConfig.setKey(key); // Must be in classpath, before sending. Do not checkin ! try { InputStream is = this.getClass().getClassLoader().getResourceAsStream("/dataMessagingToken.txt"); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String token = reader.readLine(); dmConfig.setAuthToken(token); } } catch (Throwable t) { log.log(Level.SEVERE, "Can't load initial token, use admin console", t); } pm.makePersistent(dmConfig); } return dmConfig; }
private C2DMConfig getDataMessagingConfig(PersistenceManager pm) { Key key = KeyFactory.createKey(C2DMConfig.class.getSimpleName(), 1); C2DMConfig dmConfig = null; try { dmConfig = pm.getObjectById(C2DMConfig.class, key); } catch (JDOObjectNotFoundException e) { // Create a new JDO object dmConfig = new C2DMConfig(); dmConfig.setKey(key); // Must be in classpath, before sending. Do not checkin ! try { InputStream is = this.getClass().getClassLoader().getResourceAsStream("dataMessagingToken.txt"); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String token = reader.readLine(); dmConfig.setAuthToken(token); } } catch (Throwable t) { log.log(Level.SEVERE, "Can't load initial token, use admin console", t); } pm.makePersistent(dmConfig); } return dmConfig; }
diff --git a/service-api/src/main/java/com/korwe/thecore/service/CoreServices.java b/service-api/src/main/java/com/korwe/thecore/service/CoreServices.java index 0862a49..50f6ae0 100644 --- a/service-api/src/main/java/com/korwe/thecore/service/CoreServices.java +++ b/service-api/src/main/java/com/korwe/thecore/service/CoreServices.java @@ -1,104 +1,104 @@ /* * Copyright (c) 2011. Korwe Software * * This file is part of TheCore. * * TheCore is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * TheCore is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with TheCore. If not, see <http://www.gnu.org/licenses/>. */ package com.korwe.thecore.service; import com.google.common.util.concurrent.Service; import com.google.inject.servlet.GuiceFilter; import com.korwe.thecore.api.CoreConfig; import com.korwe.thecore.service.ping.CorePingService; import com.korwe.thecore.service.ping.PingServiceImpl; import com.korwe.thecore.service.syndication.CoreSyndicationService; import com.korwe.thecore.service.syndication.SyndicationServiceImpl; import com.korwe.thecore.session.SessionManager; import com.korwe.thecore.webcore.listener.WebCoreListener; import com.korwe.thecore.webcore.servlet.GuiceServletConfig; import org.apache.log4j.Logger; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.util.thread.ExecutorThreadPool; import java.util.HashSet; import java.util.Set; /** * @author <a href="mailto:[email protected]>Nithia Govender</a> */ public class CoreServices { private static final Logger LOG = Logger.getLogger(CoreServices.class); private static Set<Service> services = new HashSet<Service>(5); public static void main(String[] args) { CoreConfig.initialize(CoreServices.class.getResourceAsStream("/coreconfig.xml")); final Server servletServer = configureServer(); - services.add(new CorePingService()); - services.add(new CoreSyndicationService()); + services.add(new CorePingService(10)); + services.add(new CoreSyndicationService(new SyndicationServiceImpl(),10)); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { //sessionManager.stop(); // webCoreListener.stop(); for (Service service: services) { service.stop(); } try { servletServer.stop(); } catch (Exception e) { LOG.error(e); } } }); //sessionManager.start(); // webCoreListener.start(); for (Service service : services) { service.start(); } try { servletServer.start(); servletServer.join(); } catch (Exception e) { LOG.error(e); } } private static Server configureServer() { Server server = new Server(); Connector connector = new SelectChannelConnector(); connector.setHost("0.0.0.0"); connector.setPort(8090); server.setConnectors(new Connector[] {connector}); ServletContextHandler contextHandler = new ServletContextHandler(server, "/", ServletContextHandler.NO_SESSIONS); contextHandler.addFilter(GuiceFilter.class, "/*", 0); contextHandler.addEventListener(new GuiceServletConfig()); contextHandler.addServlet(DefaultServlet.class, "/"); server.setThreadPool(new ExecutorThreadPool()); return server; } }
true
true
public static void main(String[] args) { CoreConfig.initialize(CoreServices.class.getResourceAsStream("/coreconfig.xml")); final Server servletServer = configureServer(); services.add(new CorePingService()); services.add(new CoreSyndicationService()); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { //sessionManager.stop(); // webCoreListener.stop(); for (Service service: services) { service.stop(); } try { servletServer.stop(); } catch (Exception e) { LOG.error(e); } } }); //sessionManager.start(); // webCoreListener.start(); for (Service service : services) { service.start(); } try { servletServer.start(); servletServer.join(); } catch (Exception e) { LOG.error(e); } }
public static void main(String[] args) { CoreConfig.initialize(CoreServices.class.getResourceAsStream("/coreconfig.xml")); final Server servletServer = configureServer(); services.add(new CorePingService(10)); services.add(new CoreSyndicationService(new SyndicationServiceImpl(),10)); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { //sessionManager.stop(); // webCoreListener.stop(); for (Service service: services) { service.stop(); } try { servletServer.stop(); } catch (Exception e) { LOG.error(e); } } }); //sessionManager.start(); // webCoreListener.start(); for (Service service : services) { service.start(); } try { servletServer.start(); servletServer.join(); } catch (Exception e) { LOG.error(e); } }
diff --git a/src/greedGame/GreedGameController.java b/src/greedGame/GreedGameController.java index 1c46f36..354811b 100644 --- a/src/greedGame/GreedGameController.java +++ b/src/greedGame/GreedGameController.java @@ -1,158 +1,158 @@ package greedGame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.JCheckBox; import greedGame.model.Dice; import greedGame.model.GreedGameModel; import greedGame.model.player.Player; import greedGame.model.player.PlayerFactory; /** * A controller class for GreedGameGUI and GreedGameModel. When created, it ties * the view and the model together by setting what action to pass to the model * for every action generated by the GUI. */ public class GreedGameController { /** * Pairing of a check box to a dice. Used so that the controller knows what * dice to select for each time a check box is selected. */ private class CheckBoxDicePair { public JCheckBox checkBox; public Dice dice; /** * Constructor. * * @param checkBox * The check box in the pair * @param dice * The dice in the pair */ public CheckBoxDicePair(JCheckBox checkBox, Dice dice) { this.checkBox = checkBox; this.dice = dice; } } // Store the model and view for the sake of the action events private GreedGameModel model; private GreedGameGUI view; // Mapping between check boxes and dice private List<CheckBoxDicePair> checkBoxDiceMap; // Creates different players to use private PlayerFactory playerFactory; /** * Constructor. * * @param greedGameModel * The model to bind together with a view. Must not be null. * @param greedGameView * The view to bind together with a model. Must not be null. */ public GreedGameController(GreedGameModel greedGameModel, GreedGameGUI greedGameView) { model = greedGameModel; view = greedGameView; checkBoxDiceMap = new ArrayList<CheckBoxDicePair>(6); playerFactory = new PlayerFactory(model); // Iterate through all check boxes and dice and create as many pairs as // possible Iterator<JCheckBox> boxIt = view.getDiceCheckBoxes().iterator(); Iterator<Dice> diceIt = model.getDice().iterator(); while (boxIt.hasNext() && diceIt.hasNext()) { checkBoxDiceMap.add(new CheckBoxDicePair(boxIt.next(), diceIt .next())); } // Add listener to the check boxes view.addAllDiceCheckBoxActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Iterate through the pairs, and if a matching check box is // found, select or unselect the corresponding dice for (CheckBoxDicePair pair : checkBoxDiceMap) { if (pair.checkBox == e.getSource()) { if (pair.checkBox.isSelected()) model.selectDice(pair.dice); else model.unselectDice(pair.dice); } } } }); // Add listener for remove player button press view.addRemoveCurrentPlayerActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward the request to the model model.removeCurrentPlayer(); } }); // Add listener for bank button press view.addBankActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward the request to the model - model.bank(); + model.tryBank(); } }); // Add listener for roll button press view.addRollActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward request to the model model.tryRollDice(); } }); // Add listener for add player button press view.addAddPlayerActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward request to the model model.startAddPlayer(); } }); // Add listener for create player button press view.addCreatePlayerActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the selected player type from the view String playerType = view.getSelectedPlayerType(); // Pass the player type to the player factory and see if // recognizes it Player newPlayer = playerFactory.createPlayer(playerType); // See if a player was created, and if so, ask the model to add // the player to the game if (newPlayer != null) model.addPlayer(newPlayer); } }); // Add listener for return from add player button press view.addReturnActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward request to the model model.stopAddPlayer(); } }); // Get the player types supported by the player factory and pass them to // the view view.setPlayerTypes(playerFactory.getPlayerTypes()); } }
true
true
public GreedGameController(GreedGameModel greedGameModel, GreedGameGUI greedGameView) { model = greedGameModel; view = greedGameView; checkBoxDiceMap = new ArrayList<CheckBoxDicePair>(6); playerFactory = new PlayerFactory(model); // Iterate through all check boxes and dice and create as many pairs as // possible Iterator<JCheckBox> boxIt = view.getDiceCheckBoxes().iterator(); Iterator<Dice> diceIt = model.getDice().iterator(); while (boxIt.hasNext() && diceIt.hasNext()) { checkBoxDiceMap.add(new CheckBoxDicePair(boxIt.next(), diceIt .next())); } // Add listener to the check boxes view.addAllDiceCheckBoxActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Iterate through the pairs, and if a matching check box is // found, select or unselect the corresponding dice for (CheckBoxDicePair pair : checkBoxDiceMap) { if (pair.checkBox == e.getSource()) { if (pair.checkBox.isSelected()) model.selectDice(pair.dice); else model.unselectDice(pair.dice); } } } }); // Add listener for remove player button press view.addRemoveCurrentPlayerActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward the request to the model model.removeCurrentPlayer(); } }); // Add listener for bank button press view.addBankActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward the request to the model model.bank(); } }); // Add listener for roll button press view.addRollActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward request to the model model.tryRollDice(); } }); // Add listener for add player button press view.addAddPlayerActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward request to the model model.startAddPlayer(); } }); // Add listener for create player button press view.addCreatePlayerActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the selected player type from the view String playerType = view.getSelectedPlayerType(); // Pass the player type to the player factory and see if // recognizes it Player newPlayer = playerFactory.createPlayer(playerType); // See if a player was created, and if so, ask the model to add // the player to the game if (newPlayer != null) model.addPlayer(newPlayer); } }); // Add listener for return from add player button press view.addReturnActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward request to the model model.stopAddPlayer(); } }); // Get the player types supported by the player factory and pass them to // the view view.setPlayerTypes(playerFactory.getPlayerTypes()); }
public GreedGameController(GreedGameModel greedGameModel, GreedGameGUI greedGameView) { model = greedGameModel; view = greedGameView; checkBoxDiceMap = new ArrayList<CheckBoxDicePair>(6); playerFactory = new PlayerFactory(model); // Iterate through all check boxes and dice and create as many pairs as // possible Iterator<JCheckBox> boxIt = view.getDiceCheckBoxes().iterator(); Iterator<Dice> diceIt = model.getDice().iterator(); while (boxIt.hasNext() && diceIt.hasNext()) { checkBoxDiceMap.add(new CheckBoxDicePair(boxIt.next(), diceIt .next())); } // Add listener to the check boxes view.addAllDiceCheckBoxActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Iterate through the pairs, and if a matching check box is // found, select or unselect the corresponding dice for (CheckBoxDicePair pair : checkBoxDiceMap) { if (pair.checkBox == e.getSource()) { if (pair.checkBox.isSelected()) model.selectDice(pair.dice); else model.unselectDice(pair.dice); } } } }); // Add listener for remove player button press view.addRemoveCurrentPlayerActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward the request to the model model.removeCurrentPlayer(); } }); // Add listener for bank button press view.addBankActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward the request to the model model.tryBank(); } }); // Add listener for roll button press view.addRollActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward request to the model model.tryRollDice(); } }); // Add listener for add player button press view.addAddPlayerActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward request to the model model.startAddPlayer(); } }); // Add listener for create player button press view.addCreatePlayerActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the selected player type from the view String playerType = view.getSelectedPlayerType(); // Pass the player type to the player factory and see if // recognizes it Player newPlayer = playerFactory.createPlayer(playerType); // See if a player was created, and if so, ask the model to add // the player to the game if (newPlayer != null) model.addPlayer(newPlayer); } }); // Add listener for return from add player button press view.addReturnActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Forward request to the model model.stopAddPlayer(); } }); // Get the player types supported by the player factory and pass them to // the view view.setPlayerTypes(playerFactory.getPlayerTypes()); }
diff --git a/core/src/main/java/com/meltmedia/cadmium/core/git/DelayedGitServiceInitializer.java b/core/src/main/java/com/meltmedia/cadmium/core/git/DelayedGitServiceInitializer.java index 3109d087..82577436 100644 --- a/core/src/main/java/com/meltmedia/cadmium/core/git/DelayedGitServiceInitializer.java +++ b/core/src/main/java/com/meltmedia/cadmium/core/git/DelayedGitServiceInitializer.java @@ -1,167 +1,165 @@ /** * Copyright 2012 meltmedia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meltmedia.cadmium.core.git; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Manages delayed initialization of a common {@link GitService} reference, as well as switching of repositories.</p> * * @author John McEntire * */ public class DelayedGitServiceInitializer implements Closeable { private final Logger logger = LoggerFactory.getLogger(getClass()); /** * The class member variable to hold the common reference. */ protected GitService git; /** * Enforces the delayed initialization of the common {@link GitService} by causing Threads to wait for the GitService to be initialized. */ private CountDownLatch latch; /** * The Object that manages all read/write locks used by an instance of this class. */ private final ReentrantReadWriteLock locker = new ReentrantReadWriteLock(); private final ReadLock readLock = locker.readLock(); private final WriteLock writeLock = locker.writeLock(); /** * Basic constructor that creates a CountDownLatch with a count of 1. */ public DelayedGitServiceInitializer() { latch = new CountDownLatch(1); } /** * <p>Retrieves the common reference to a GitService.</p> * <p>If the reference has not been set yet, any calling threads will block until the reference is set or the thread is interrupted.</p> * * @return The common reference to {@link GitService}. * @throws Exception Thrown if the current thread has been interrupted while waiting for the GitService to initialize. */ public GitService getGitService() throws Exception { logger.debug("Getting git service."); latch.await(); readLock.lock(); return git; } /** * <p>Switches the current reference to point to a new remote git repository.</p> * <p>This method will block if the common reference has not been set or there are any threads currently using the referenced git service.</p> * * @param uri The uri to the remote repository. * @throws Exception */ public synchronized void switchRepository(String uri) throws Exception { - String branch = null; - String revision = null; - String oldRepoUri = null; + File oldRepo = null; File gitDir = null; try { writeLock.lock(); latch.await(); if(!git.getRemoteRepository().equalsIgnoreCase(uri)) { logger.debug("Switching repo from {} to {}", git.getRemoteRepository(), uri); - branch = git.getBranchName(); - revision = git.getCurrentRevision(); - oldRepoUri = git.getRemoteRepository(); gitDir = new File(git.getBaseDirectory()); IOUtils.closeQuietly(git); git = null; + oldRepo = new File(gitDir.getParentFile(), "old-git-checkout"); + FileUtils.deleteQuietly(oldRepo); + FileUtils.copyDirectory(gitDir, oldRepo); FileUtils.deleteDirectory(gitDir); git = GitService.cloneRepo(uri, gitDir.getAbsolutePath()); } } catch(InterruptedException ie){ logger.warn("Thread interrupted, must be shutting down!", ie); throw ie; } catch(Exception e) { logger.warn("Failed to switch repository. Rolling back!"); if(git != null) { IOUtils.closeQuietly(git); git = null; } FileUtils.deleteQuietly(gitDir); - git = GitService.cloneRepo(oldRepoUri, gitDir.getAbsolutePath()); - git.switchBranch(branch); - git.resetToRev(revision); + FileUtils.copyDirectory(oldRepo, gitDir); + git = GitService.createGitService(gitDir.getAbsolutePath()); throw e; } finally { + FileUtils.deleteQuietly(oldRepo); writeLock.unlock(); } } /** * Releases the read lock on this class and must be called from the same thread that called the {@link DelayedGitServiceInitializer.getGitService()}. */ public void releaseGitService() { readLock.unlock(); } /** * Sets the common reference an releases any threads waiting for the reference to be set. * * @param git */ public void setGitService(GitService git) { if(git != null) { logger.debug("Setting git service"); this.git = git; latch.countDown(); } } /** * Releases any used resources and waiting threads. * * @throws IOException */ @Override public void close() throws IOException { if(git != null) { IOUtils.closeQuietly(git); git = null; } try { latch.notifyAll(); } catch(Exception e) { logger.debug("Failed to notifyAll", e); } try { locker.notifyAll(); } catch(Exception e) { logger.debug("Failed to notifyAll", e); } } }
false
true
public synchronized void switchRepository(String uri) throws Exception { String branch = null; String revision = null; String oldRepoUri = null; File gitDir = null; try { writeLock.lock(); latch.await(); if(!git.getRemoteRepository().equalsIgnoreCase(uri)) { logger.debug("Switching repo from {} to {}", git.getRemoteRepository(), uri); branch = git.getBranchName(); revision = git.getCurrentRevision(); oldRepoUri = git.getRemoteRepository(); gitDir = new File(git.getBaseDirectory()); IOUtils.closeQuietly(git); git = null; FileUtils.deleteDirectory(gitDir); git = GitService.cloneRepo(uri, gitDir.getAbsolutePath()); } } catch(InterruptedException ie){ logger.warn("Thread interrupted, must be shutting down!", ie); throw ie; } catch(Exception e) { logger.warn("Failed to switch repository. Rolling back!"); if(git != null) { IOUtils.closeQuietly(git); git = null; } FileUtils.deleteQuietly(gitDir); git = GitService.cloneRepo(oldRepoUri, gitDir.getAbsolutePath()); git.switchBranch(branch); git.resetToRev(revision); throw e; } finally { writeLock.unlock(); } }
public synchronized void switchRepository(String uri) throws Exception { File oldRepo = null; File gitDir = null; try { writeLock.lock(); latch.await(); if(!git.getRemoteRepository().equalsIgnoreCase(uri)) { logger.debug("Switching repo from {} to {}", git.getRemoteRepository(), uri); gitDir = new File(git.getBaseDirectory()); IOUtils.closeQuietly(git); git = null; oldRepo = new File(gitDir.getParentFile(), "old-git-checkout"); FileUtils.deleteQuietly(oldRepo); FileUtils.copyDirectory(gitDir, oldRepo); FileUtils.deleteDirectory(gitDir); git = GitService.cloneRepo(uri, gitDir.getAbsolutePath()); } } catch(InterruptedException ie){ logger.warn("Thread interrupted, must be shutting down!", ie); throw ie; } catch(Exception e) { logger.warn("Failed to switch repository. Rolling back!"); if(git != null) { IOUtils.closeQuietly(git); git = null; } FileUtils.deleteQuietly(gitDir); FileUtils.copyDirectory(oldRepo, gitDir); git = GitService.createGitService(gitDir.getAbsolutePath()); throw e; } finally { FileUtils.deleteQuietly(oldRepo); writeLock.unlock(); } }
diff --git a/src/com/google/caliper/CaliperRc.java b/src/com/google/caliper/CaliperRc.java index d376431..963df15 100644 --- a/src/com/google/caliper/CaliperRc.java +++ b/src/com/google/caliper/CaliperRc.java @@ -1,53 +1,56 @@ /* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.caliper; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; /** * Created by IntelliJ IDEA. User: kevinb Date: Jan 20, 2010 Time: 9:37:37 AM To change this * template use File | Settings | File Templates. */ public class CaliperRc { public static final CaliperRc INSTANCE = new CaliperRc(); private final Properties properties = new Properties(); private CaliperRc() { try { - File dotCaliperRc = new File(System.getProperty("user.home"), ".caliperrc"); - if (dotCaliperRc.exists()) { - properties.load(new FileInputStream(dotCaliperRc)); + String caliperRcEnvVar = System.getenv("CALIPERRC"); + File caliperRcFile = (caliperRcEnvVar == null) + ? new File(System.getProperty("user.home"), ".caliperrc") + : new File(caliperRcEnvVar); + if (caliperRcFile.exists()) { + properties.load(new FileInputStream(caliperRcFile)); } else { // create it with a template } } catch (IOException e) { throw new RuntimeException(e); } } public String getApiKey() { return properties.getProperty("apiKey"); } public String getPostUrl() { return properties.getProperty("postUrl"); } }
true
true
private CaliperRc() { try { File dotCaliperRc = new File(System.getProperty("user.home"), ".caliperrc"); if (dotCaliperRc.exists()) { properties.load(new FileInputStream(dotCaliperRc)); } else { // create it with a template } } catch (IOException e) { throw new RuntimeException(e); } }
private CaliperRc() { try { String caliperRcEnvVar = System.getenv("CALIPERRC"); File caliperRcFile = (caliperRcEnvVar == null) ? new File(System.getProperty("user.home"), ".caliperrc") : new File(caliperRcEnvVar); if (caliperRcFile.exists()) { properties.load(new FileInputStream(caliperRcFile)); } else { // create it with a template } } catch (IOException e) { throw new RuntimeException(e); } }
diff --git a/src/replicated_calculator/ClientNonRobust.java b/src/replicated_calculator/ClientNonRobust.java index 5564d49..99538c8 100755 --- a/src/replicated_calculator/ClientNonRobust.java +++ b/src/replicated_calculator/ClientNonRobust.java @@ -1,177 +1,179 @@ package replicated_calculator; import point_to_point_queue.*; import java.math.BigInteger; import java.net.InetSocketAddress; import java.net.InetAddress; import java.io.*; import java.util.HashMap; import week6.ClientEventConnectDenied; /** * A simple, non-robust client for connecting to DistributedCalculator. * It sends the events to the calculator and receives back the events as * acknowledgements. Only the acknowledgements of read events are used * for anything, as they carry the value which was read. This value is * reported back to the caller of the SimpleClient using a callback. * * A fuller implementation could, e.g., handle detection of when a server * is down and report back to the user which commands were carried out. * If the server crashes the client could try to shift to another * server in the server group. * * A fuller implementation could also make the client robust such that * it can handle to crash and then restart. * * A fuller implementation could also be extended to handle a client-centric * semantics such as read-your-writes in case the client disconnects from one * server and then connects to another server. * * @author Jesper Buus Nielsen, Aarhus University, 2012. * */ public class ClientNonRobust extends Thread implements Client { /* * The name of this client. */ protected String clientName; /* * Point-to-point message for sending messages to the server. * Used for sending ClientEvents to the server. */ protected PointToPointQueueSenderEndNonRobust<ClientEvent> toServer; /* * Point-to-point message queue for receiving messages from the server. * Used for getting back client events sent on toServer. When an * event comes back it means that the server has handled the event. */ protected PointToPointQueueReceiverEndNonRobust<ClientEvent> fromServer; /* * The event identifier of the next event to be sent to the server. */ protected long eventID = 0; /* * Used for storing the callbacks which are used to report back the values * of reads. */ private final HashMap<Long,Callback<BigInteger>> callbacks = new HashMap<Long,Callback<BigInteger>>(); /* * Used to signal that the SimpleClient has been disconnected. When set * to true, the SimpleClient will close down immediately. */ private boolean shutdown = false; /** * Send an addition command to the server. */ synchronized public void add(String left, String right, String res) { toServer.put(new ClientEventAdd(clientName,eventID++,left,right,res)); } /** * Send an assignment event to the server. */ synchronized public void assign(String var, BigInteger val) { toServer.put(new ClientEventAssign(clientName,eventID++,var,val)); } /** * Send a beginAtomic event to the server. */ synchronized public void beginAtomic() { toServer.put(new ClientEventBeginAtomic(clientName,eventID++)); } /** * Sends a compare event to the server. */ synchronized public void compare(String left, String right, String res) { toServer.put(new ClientEventCompare(clientName,eventID++,left,right,res)); } /** * Connects to the server and sends a connect event to the server. * Opens a point-to-point queue for receiving acknowledgements from the server. * Then starts a thread (this) which polls the acknowledgements and treats them. */ synchronized public boolean connect(String addressOfServer, String clientName) { this.clientName = clientName; this.toServer = new PointToPointQueueSenderEndNonRobust<ClientEvent>(); this.toServer.setReceiver(new InetSocketAddress(addressOfServer,Parameters.serverPortForClients)); try { final String myAddress = InetAddress.getLocalHost().getCanonicalHostName(); this.fromServer = new PointToPointQueueReceiverEndNonRobust<ClientEvent>(); this.fromServer.listenOnPort(Parameters.clientPortForServer); toServer.put(new ClientEventConnect(clientName,eventID++,new InetSocketAddress(myAddress,Parameters.clientPortForServer))); } catch (IOException e) { return false; } this.start(); return true; } /** * Sends a disconnect event to the server. Will shut down immediately. * Should only be called when all events have been sent and acknowledged. */ synchronized public void disconnect() { toServer.put(new ClientEventDisconnect(clientName,eventID++)); toServer.shutdown(); fromServer.shutdown(); shutdown = true; } /** * Sends an endAtomic event to the server. */ synchronized public void endAtomic() { toServer.put(new ClientEventEndAtomic(clientName,eventID++)); } /** * Sends a multiplication event to the server. */ synchronized public void mult(String left, String right, String res) { toServer.put(new ClientEventMult(clientName,eventID++,left,right,res)); } /** * Sends a read event to the server. It stores the callback under * the event identifier so it can be called when an acknowledgement returns. */ synchronized public void read(String var, Callback<BigInteger> callback) { final long eid = eventID++; toServer.put(new ClientEventRead(clientName,eid,var)); synchronized (callbacks) { callbacks.put(new Long(eid), callback); } } /** * Keeps getting the next acknowledgement from the server. If the * acknowledgement is a read event, then the value of the event is * reported back to the creater of the read event using a callback. */ public void run() { while (!shutdown) { final ClientEvent nextACK = fromServer.get(); if (nextACK instanceof ClientEventRead) { ClientEventRead eventRead = (ClientEventRead)nextACK; Callback<BigInteger> callback; synchronized (callbacks) { callback = callbacks.get(new Long(eventRead.eventID)); } callback.result(eventRead.getVal()); }else if(nextACK instanceof ClientEventConnectDenied){ System.out.println("Username already connected..."); - disconnect(); + toServer.shutdown(); + fromServer.shutdown(); + shutdown = true; } } toServer.shutdown(); } }
true
true
public void run() { while (!shutdown) { final ClientEvent nextACK = fromServer.get(); if (nextACK instanceof ClientEventRead) { ClientEventRead eventRead = (ClientEventRead)nextACK; Callback<BigInteger> callback; synchronized (callbacks) { callback = callbacks.get(new Long(eventRead.eventID)); } callback.result(eventRead.getVal()); }else if(nextACK instanceof ClientEventConnectDenied){ System.out.println("Username already connected..."); disconnect(); } } toServer.shutdown(); }
public void run() { while (!shutdown) { final ClientEvent nextACK = fromServer.get(); if (nextACK instanceof ClientEventRead) { ClientEventRead eventRead = (ClientEventRead)nextACK; Callback<BigInteger> callback; synchronized (callbacks) { callback = callbacks.get(new Long(eventRead.eventID)); } callback.result(eventRead.getVal()); }else if(nextACK instanceof ClientEventConnectDenied){ System.out.println("Username already connected..."); toServer.shutdown(); fromServer.shutdown(); shutdown = true; } } toServer.shutdown(); }
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/BrowseFilteredListener.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/BrowseFilteredListener.java index 0ed6fc3cc..b95f9abb3 100644 --- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/BrowseFilteredListener.java +++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/BrowseFilteredListener.java @@ -1,168 +1,172 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.context.ui; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.mylyn.context.ui.InterestFilter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.navigator.CommonViewer; /** * @author Mik Kersten */ public class BrowseFilteredListener implements MouseListener, KeyListener { private StructuredViewer viewer; public BrowseFilteredListener(StructuredViewer viewer) { this.viewer = viewer; } /** * @param treeViewer * cannot be null * @param targetSelection * cannot be null */ public void unfilterSelection(TreeViewer treeViewer, IStructuredSelection targetSelection) { InterestFilter filter = getInterestFilter(treeViewer); Object targetObject = targetSelection.getFirstElement(); if (targetObject != null) { filter.setTemporarilyUnfiltered(targetObject); if (targetObject instanceof Tree) { treeViewer.refresh(); } else { treeViewer.refresh(targetObject, true); treeViewer.expandToLevel(targetObject, 1); } } } private void unfilter(final InterestFilter filter, final TreeViewer treeViewer, Object targetObject) { if (targetObject != null) { filter.setTemporarilyUnfiltered(targetObject); if (targetObject instanceof Tree) { treeViewer.refresh(); } else { treeViewer.refresh(targetObject, true); treeViewer.expandToLevel(targetObject, 1); } } } public void keyPressed(KeyEvent event) { // ignore } public void keyReleased(KeyEvent event) { InterestFilter filter = getInterestFilter(viewer); if (event.keyCode == SWT.ARROW_RIGHT) { if (filter == null || !(viewer instanceof TreeViewer)) { return; } final TreeViewer treeViewer = (TreeViewer) viewer; ISelection selection = treeViewer.getSelection(); if (selection instanceof IStructuredSelection) { Object targetObject = ((IStructuredSelection) selection).getFirstElement(); unfilter(filter, treeViewer, targetObject); } } } public void mouseDown(MouseEvent event) { final InterestFilter filter = getInterestFilter(viewer); if (filter == null || !(viewer instanceof TreeViewer)) { return; } TreeViewer treeViewer = (TreeViewer) viewer; Object selectedObject = null; Object clickedObject = getClickedItem(event); if (clickedObject != null) { selectedObject = clickedObject; } else { selectedObject = treeViewer.getTree(); } if (isUnfilterEvent(event)) { if (treeViewer instanceof CommonViewer) { CommonViewer commonViewer = (CommonViewer) treeViewer; commonViewer.setSelection(new StructuredSelection(selectedObject), true); } unfilter(filter, treeViewer, selectedObject); } else { if (event.button == 1) { - Object unfiltered = filter.getTemporarilyUnfiltered(); - if (unfiltered != null) { - filter.resetTemporarilyUnfiltered(); - // NOTE: need to set selection otherwise it will be missed + if ((event.stateMask & SWT.CTRL) != 0) { viewer.setSelection(new StructuredSelection(selectedObject)); - viewer.refresh(unfiltered); + } else { + Object unfiltered = filter.getTemporarilyUnfiltered(); + if (unfiltered != null) { + filter.resetTemporarilyUnfiltered(); + // NOTE: need to set selection otherwise it will be missed + viewer.setSelection(new StructuredSelection(selectedObject)); + viewer.refresh(unfiltered); + } } } } } private Object getClickedItem(MouseEvent event) { if (event.getSource() instanceof Table) { TableItem item = ((Table) event.getSource()).getItem(new Point(event.x, event.y)); if (item != null) { return item.getData(); } else { return null; } } else if (event.getSource() instanceof Tree) { TreeItem item = ((Tree) event.getSource()).getItem(new Point(event.x, event.y)); if (item != null) { return item.getData(); } else { return null; } } return null; } public static boolean isUnfilterEvent(MouseEvent event) { return (event.stateMask & SWT.ALT) != 0; } private InterestFilter getInterestFilter(StructuredViewer structuredViewer) { ViewerFilter[] filters = structuredViewer.getFilters(); for (int i = 0; i < filters.length; i++) { if (filters[i] instanceof InterestFilter) return (InterestFilter) filters[i]; } return null; } public void mouseUp(MouseEvent e) { // ignore } public void mouseDoubleClick(MouseEvent e) { } }
false
true
public void mouseDown(MouseEvent event) { final InterestFilter filter = getInterestFilter(viewer); if (filter == null || !(viewer instanceof TreeViewer)) { return; } TreeViewer treeViewer = (TreeViewer) viewer; Object selectedObject = null; Object clickedObject = getClickedItem(event); if (clickedObject != null) { selectedObject = clickedObject; } else { selectedObject = treeViewer.getTree(); } if (isUnfilterEvent(event)) { if (treeViewer instanceof CommonViewer) { CommonViewer commonViewer = (CommonViewer) treeViewer; commonViewer.setSelection(new StructuredSelection(selectedObject), true); } unfilter(filter, treeViewer, selectedObject); } else { if (event.button == 1) { Object unfiltered = filter.getTemporarilyUnfiltered(); if (unfiltered != null) { filter.resetTemporarilyUnfiltered(); // NOTE: need to set selection otherwise it will be missed viewer.setSelection(new StructuredSelection(selectedObject)); viewer.refresh(unfiltered); } } } }
public void mouseDown(MouseEvent event) { final InterestFilter filter = getInterestFilter(viewer); if (filter == null || !(viewer instanceof TreeViewer)) { return; } TreeViewer treeViewer = (TreeViewer) viewer; Object selectedObject = null; Object clickedObject = getClickedItem(event); if (clickedObject != null) { selectedObject = clickedObject; } else { selectedObject = treeViewer.getTree(); } if (isUnfilterEvent(event)) { if (treeViewer instanceof CommonViewer) { CommonViewer commonViewer = (CommonViewer) treeViewer; commonViewer.setSelection(new StructuredSelection(selectedObject), true); } unfilter(filter, treeViewer, selectedObject); } else { if (event.button == 1) { if ((event.stateMask & SWT.CTRL) != 0) { viewer.setSelection(new StructuredSelection(selectedObject)); } else { Object unfiltered = filter.getTemporarilyUnfiltered(); if (unfiltered != null) { filter.resetTemporarilyUnfiltered(); // NOTE: need to set selection otherwise it will be missed viewer.setSelection(new StructuredSelection(selectedObject)); viewer.refresh(unfiltered); } } } } }
diff --git a/src/lib/com/izforge/izpack/util/IsPortValidator.java b/src/lib/com/izforge/izpack/util/IsPortValidator.java index 31cc3bfa..023e0bd8 100644 --- a/src/lib/com/izforge/izpack/util/IsPortValidator.java +++ b/src/lib/com/izforge/izpack/util/IsPortValidator.java @@ -1,60 +1,60 @@ /* * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2004 Thorsten Kamann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.izforge.izpack.util; import com.izforge.izpack.panels.ProcessingClient; import com.izforge.izpack.panels.Validator; /** * A validator to check whether the field content is a port . * * @author thorque */ public class IsPortValidator implements Validator { public boolean validate(ProcessingClient client) { int port = 0; if ("".equals(client.getFieldContents(0))) { return false; } try { port = Integer.parseInt(client.getFieldContents(0)); - if (port > 0 && port < Integer.MAX_VALUE) + if (port > 0 && port < 65535) { return true; } } catch (Exception ex) { return false; } return false; } }
true
true
public boolean validate(ProcessingClient client) { int port = 0; if ("".equals(client.getFieldContents(0))) { return false; } try { port = Integer.parseInt(client.getFieldContents(0)); if (port > 0 && port < Integer.MAX_VALUE) { return true; } } catch (Exception ex) { return false; } return false; }
public boolean validate(ProcessingClient client) { int port = 0; if ("".equals(client.getFieldContents(0))) { return false; } try { port = Integer.parseInt(client.getFieldContents(0)); if (port > 0 && port < 65535) { return true; } } catch (Exception ex) { return false; } return false; }
diff --git a/src/net/sozinsoft/tokenlab/PathfinderToken.java b/src/net/sozinsoft/tokenlab/PathfinderToken.java index 3208db3..9d03762 100755 --- a/src/net/sozinsoft/tokenlab/PathfinderToken.java +++ b/src/net/sozinsoft/tokenlab/PathfinderToken.java @@ -1,963 +1,966 @@ package net.sozinsoft.tokenlab; import com.google.gson.*; import net.rptools.maptool.model.*; import net.sozinsoft.tokenlab.dtd.*; import net.sozinsoft.tokenlab.dtd.Character; import net.sozinsoft.tokenlab.dtd.Weapon; import org.xml.sax.SAXException; import java.io.IOException; import java.util.*; public class PathfinderToken implements ICharacter, ITokenizable { private static final String SIZE_MOD = "SizeMod"; private static final String AC_TEMP_BONUS = "ACTempBonus"; private static final String AC_MISC_BONUS_2 = "ACMiscBonus2"; private static final String AC_MISC_BONUS_1 = "ACMiscBonus1"; private static final String AC_FROM_DEFLECT = "ACDeflectBonus"; private static final String AC_FROM_DODGE = "ACDodgeBonus"; private static final String AC_SHIELD_BONUS = "ACShieldBonus"; private static final String AC_ARMOR_BONUS = "ACArmorBonus"; public static final String AC_FROM_NATURAL = "ACNaturalBonus"; private static final String ARMOR_MAX_DEX_BONUS = "ArmorMaxDexBonus"; private static final String ARMOR_CHECK_PENALTY = "ArmorCheckPenalty"; private static final String MISC_BONUS = "MiscBonus"; private static final String DAMAGE = "damage"; private static final String ENHANCEMENT = "Enhancement"; private static final String CLASS_BONUS = "ClassBonus"; private static final String RESIST_BONUS = "ResistBonus"; private static final String CLASS_SKILL = "ClassSkill"; private static final String PATHFINDER = "Pathfinder"; private static final String INIT_MOD = "InitMod"; private static MacroDigester macroDigester = null; public static final String VALUE = "value"; public static final String VALUE_MODIFIER = "valueModifier"; public static final String BONUS = "bonus"; public static final String BONUS_MODIFIER = "bonusModifier"; public static final String TEMP_MODIFIER = "tempModifier"; public static final String PROFESSION = "Profession"; public static final String YES = "yes"; public static final String RANKS = "Ranks"; public static final String WEAPON_JSON = "WeaponJSON"; public static final String SPELLS_JSON = "SpellJSON"; public static final String FEATS_JSON = "FeatJSON"; public static final String SPELLBOOK = "Spellbook"; public static final String MEMORIZED = "Memorized"; public static final String SPONTANEOUS = "Spontaneous"; public static final String SPECIAL_ABILITIES_JSON = "SpecialAbilitiesJSON"; public static final String SENSES = "Senses"; public static final String AURAS = "Auras"; public static final String HEALTH = "Health"; public static final String DAMAGE_REDUCTION = "Damage Reduction"; public static final String DEFENSIVE = "Defensive"; public static final String IMMUNITIES = "Immunities"; public static final String WEAKNESSES = "Weaknesses"; public static final String MOVEMENT = "Movement"; public static final String SKILL_ABILITIES = "Skill Abilities"; public static final String ATTACK = "Attack"; public static final String SPELL_LIKE = "Spell-like"; public static final String OTHER = "Other"; public static final String TRAITS_JSON = "TraitsJSON"; public static final String SKILLS_JSON = "SkillsJSON"; public static final String RESOURCES_JSON = "ResourcesJSON"; public static final String SPONTANEOUS_RESOURCES_JSON = "SpontaneousResourcesJSON"; public static final String MEMORIZED_RESOURCES_JSON = "MemorizedResourcesJSON"; public static final String YELLOW = "yellow"; public static final String DARKGRAY = "darkgray"; public static final String BEGIN_ROLL = "[r:"; public static final String END_ROLL = "]"; public static final String SPELL_REFERENCE_MACRO_NAME = "Spell Reference"; public static final String SPONTANEOUS_SPELL_RESOURCES_MACRO_NAME = "Spontaneous Spell Resources"; public static final String NPC = "npc"; public static final String STANDARD_ATTACK_MACRO_NAME = "Standard Attack"; public static final String ATTACK_FULL = "Attack - Full"; private Character _character; private TokenLabToken _token; private HashMap<String, Object> _propertyMap = new HashMap<String, Object>(); public PathfinderToken(Character character ) throws Exception { _token = new TokenLabToken(); _character = character; _token.setCommonProperties( this, _propertyMap ); setAbilities(); setSavingThrows(); setArmorClass(); setSkills(); setWeapons(); setSpells(); setFeats(); setSpecialAbilities(); setVision(); setInitiative(); setTrackedResources(); setSpellResources(); } private HashMap<String, HashMap<String, Object >> _trackedResources = new HashMap<String, HashMap<String, Object>>(); private void setTrackedResources() { for( Trackedresource tr : _character.getTrackedresources().getTrackedresource() ) { String trName = StringUtils.removeCommas(tr.getName()); int min = Integer.parseInt( tr.getMin() ); int max = Integer.parseInt( tr.getMax() ); int used = Integer.parseInt( tr.getUsed() ); HashMap<String, Object> trMap = new HashMap<String, Object>(); trMap.put( "min", min); trMap.put( "max", max ); trMap.put( "used", used ); _trackedResources.put( trName, trMap ); } } private HashMap<String, WeaponImpl> _weapons = new HashMap<String, WeaponImpl>(); public HashMap<String, WeaponImpl> getWeapons() { return _weapons; } private void setWeapons() throws Exception { for( Weapon weapon: this._character.getMelee().getWeapon() ) { if ( _weapons.containsKey( weapon.getName() )) { weapon.setName( weapon.getName() + " (" + weapon.getEquipped() + ")"); } WeaponImpl wimpl = new WeaponImpl(weapon.getName(), weapon.getDamage(), weapon.getCategorytext(), weapon.getCrit(), weapon.getAttack(), weapon.getEquipped(), weapon.getCategorytext(), weapon.getDescription()); _weapons.put( wimpl.name, wimpl); } for( Weapon weapon: this._character.getRanged().getWeapon() ) { if ( _weapons.containsKey( weapon.getName() )) { weapon.setName( weapon.getName() + "(" + weapon.getEquipped() + ")"); } WeaponImpl wimpl = new WeaponImpl(weapon.getName(), weapon.getDamage(), weapon.getCategorytext(), weapon.getCrit(), weapon.getAttack(), weapon.getEquipped(), weapon.getCategorytext(), weapon.getDescription()); _weapons.put( wimpl.name, wimpl); } } public HashMap<String, PFSRDSpell> getSpellsByClass( String className) { ClassSpells cs = _spells.get(className); HashMap<String, PFSRDSpell > ret = cs.getAllSpells(); return ret; } public SortedMap< Integer, HashMap<String, PFSRDSpell>> getSpellsByClassAndLevel( String className ) { ClassSpells cs = _spells.get(className); SortedMap<Integer, HashMap<String, PFSRDSpell >> ret = cs.getAllSpellsByLevel(); return ret; } private HashMap< String, Feat > _feats = new HashMap<String, Feat>(); private HashMap< String, Trait> _traits = new HashMap<String, Trait>(); public HashMap< String, Feat > getFeats() { return _feats; } public void setFeats() { for( Feat f : _character.getFeats().getFeat() ) { //replace newlines with html breaks for nicer printing _feats.put(f.getName().replaceAll(",", ""), f); } for ( Trait t : _character.getTraits().getTrait()) { _traits.put( t.getName().replaceAll(",", ""), t ); } } private SortedMap< String, TreeMap<String, Special >> _specials = new TreeMap<String, TreeMap<String, Special>>(); public SortedMap< String, TreeMap<String, Special >> getSpecialAbilities() { return _specials; } public void setSpecial( String specialName, Special special ) { TreeMap< String, Special > smap = _specials.get( specialName ); if ( smap == null ) { smap = new TreeMap<String, Special>(); _specials.put( specialName, smap ); } smap.put( special.getName(), special ); } private String _vision; public void setVision() { Vision v = new Vision( _character.getSenses().getSpecial() ); _vision = v.getVision(); } private String _initMod; public void setInitiative() { String total = StringUtils.replacePlus(_character.getInitiative().getTotal()); String fromAttr = StringUtils.replacePlus(_character.getInitiative().getAttrtext()); int iTotal = Integer.parseInt(total); int iFromAttr = Integer.parseInt(fromAttr); int iMod = iTotal - iFromAttr; _initMod = Integer.toString(iMod); } public void setSpecialAbilities() { for ( Special s: _character.getSenses().getSpecial() ) { setSpecial(SENSES, s ); } for( Special s: _character.getAuras().getSpecial() ) { setSpecial(AURAS, s ); } for( Special s: _character.getHealth().getSpecial() ) { setSpecial(HEALTH, s ); } for( Special s: _character.getDamagereduction().getSpecial()) { setSpecial(DAMAGE_REDUCTION, s ); } for( Special s: _character.getDefensive().getSpecial()) { setSpecial(DEFENSIVE, s ); } for( Special s: _character.getImmunities().getSpecial() ) { setSpecial(IMMUNITIES, s ); } for( Special s: _character.getWeaknesses().getSpecial() ) { setSpecial(WEAKNESSES, s ); } for( Special s: _character.getMovement().getSpecial()) { setSpecial(MOVEMENT, s ); } for( Special s: _character.getSkillabilities().getSpecial()) { setSpecial(SKILL_ABILITIES, s ); } for( Special s: _character.getAttack().getSpecial() ) { setSpecial(ATTACK, s ); } for( Special s: _character.getSpelllike().getSpecial() ) { setSpecial(SPELL_LIKE, s ); } for( Special s: _character.getOtherspecials().getSpecial()) { setSpecial(OTHER, s ); } } private void setSpellResources() { for ( Spellclass sc : _character.getSpellclasses().getSpellclass() ) { if ( sc.getSpells().equals("Spontaneous")) { setSpontaneousSpellResources( sc ); } } setMemorizedResources(); } private SortedMap<Integer, LinkedList<HashMap<String, Object>>> _memorizedSpellResources = new TreeMap<Integer, LinkedList<HashMap<String, Object>>>() ; private void setMemorizedResources() { if ( _character.getSpellsmemorized().getSpell().size() > 0 ) { buildSpellResource(_memorizedSpellResources, _character.getSpellsmemorized().getSpell() ); } } private void buildSpellResource( SortedMap<Integer, LinkedList<HashMap<String, Object>>> spellResourceCollection, List<Spell> spells ) { for( Spell s : spells ) { String name = s.getName(); int numRepeats = StringUtils.isXN( name ); if ( numRepeats > 0 ) { name = StringUtils.removeXN( name ); } else { numRepeats = 1; } for( int i = 0; i < numRepeats; i++ ) { boolean unlimited = s.getUnlimited() != null && s.getUnlimited().equals("yes"); int level = Integer.parseInt( s.getLevel() ); int dc = Integer.parseInt( s.getDc() ); String className = s.getClazz() == null || s.getClazz().length() == 0? _spellToClassMap.get(name) : s.getClazz(); LinkedList<HashMap<String, Object>> spellsAtLevel = spellResourceCollection.get( level ); if ( spellsAtLevel == null ) { spellsAtLevel = new LinkedList<HashMap<String, Object>>(); spellResourceCollection.put( level, spellsAtLevel); } HashMap<String,Object> spellAtLevel = new HashMap<String, Object>(); spellAtLevel.put( "name", name ); spellAtLevel.put( "unlimited", unlimited? 1: 0 ); spellAtLevel.put( "level", level ); spellAtLevel.put( "className", className); spellAtLevel.put( "dc", dc ); spellAtLevel.put( "used", 0 ); spellsAtLevel.add( spellAtLevel ); } } } private SortedMap<Integer, LinkedList<HashMap<String, Object>>> _spontaneousSpellResources = new TreeMap<Integer, LinkedList<HashMap<String, Object>>>(); private void setSpontaneousSpellResources( Spellclass spellClass ) { String spellClassName = spellClass.getName(); for( Spelllevel spellLevel : spellClass.getSpelllevel() ) { int spellLevelInt = Integer.parseInt( spellLevel.getLevel() ); boolean unlimited = spellLevel.getUnlimited() != null && spellLevel.getUnlimited().equals("yes"); if ( unlimited ) { //don't bother with unlimited resources continue; } int maxCasts = Integer.parseInt(spellLevel.getMaxcasts()); int used = Integer.parseInt( spellLevel.getUsed()); HashMap<String, Object> hmap = new HashMap<String, Object>(); hmap.put( "spellLevel", spellLevelInt ); hmap.put( "maxCasts", maxCasts ); hmap.put( "used", used ); hmap.put( "spellClassName", spellClassName ); Integer hkey = spellLevelInt; LinkedList<HashMap<String, Object>> spellResourcesByClass; if( _spontaneousSpellResources.containsKey(hkey)) { spellResourcesByClass = _spontaneousSpellResources.get( hkey ); } else { spellResourcesByClass = new LinkedList<HashMap<String, Object>>(); _spontaneousSpellResources.put( hkey, spellResourcesByClass ); } spellResourcesByClass.push( hmap ); } } private HashMap<String, ClassSpells > _spells= new HashMap<String, ClassSpells>(); private HashMap<String, HashMap<String, Object>> _trackedSpells = new HashMap<String, HashMap<String, Object>>(); public void setSpells() { for(Spellclass sc : _character.getSpellclasses().getSpellclass() ) { ClassSpells cs = null; if ( _spells.containsKey(sc.getName())) { cs = _spells.get(sc.getName()); } else { cs = new ClassSpells(sc.getName()); _spells.put( sc.getName(), cs ); } if ( sc.getSpells().equals(SPELLBOOK) ) { addClassSpell( _character.getSpellbook().getSpell(), cs ); } else if ( sc.getSpells().equals(MEMORIZED)) { addClassSpell( _character.getSpellsmemorized().getSpell(), cs ); } else if ( sc.getSpells().equals(SPONTANEOUS)) { addClassSpell( _character.getSpellsknown().getSpell(), cs ); } else { System.out.println("Unknown spell class " + sc.getSpells() ); } } } private HashMap<String, String> _spellToClassMap = new HashMap<String, String>(); private void addClassSpell(List<Spell> spells, ClassSpells cs) { for( Spell s: spells ) { cs.addSpell(s); if ( ! _spellToClassMap.containsKey(s.getName() ) ) { _spellToClassMap.put( s.getName(), cs.getClassName() ); } } } private static HashMap<IAttribute, IAttributeAbbreviated > attributeAbbreviations = new HashMap<IAttribute, IAttributeAbbreviated>(); static { attributeAbbreviations.put( IAttribute.Strength, IAttributeAbbreviated.STR ); attributeAbbreviations.put( IAttribute.Dexterity, IAttributeAbbreviated.DEX ); attributeAbbreviations.put( IAttribute.Constitution, IAttributeAbbreviated.CON ); attributeAbbreviations.put( IAttribute.Wisdom, IAttributeAbbreviated.WIS ); attributeAbbreviations.put( IAttribute.Intelligence, IAttributeAbbreviated.INT ); } private static IAttributeAbbreviated getAbbreviatedAttribute( IAttribute ia ) { return attributeAbbreviations.get(ia); } private HashMap< IAttribute, HashMap<String, Object> > _attributes = new HashMap<IAttribute, HashMap<String, Object>>(); private void setAbilities() { for( Attribute attribute : _character.getAttributes().getAttribute() ) { HashMap<String, Object> attribJSON = new HashMap<String, Object>(); _attributes.put( IAttribute.valueOf( attribute.getName() ), attribJSON ); //_propertyMap.put( attribute.getName(), Integer.parseInt( attribute.getAttrvalue().getBase()) ); attribJSON.put(VALUE, Integer.parseInt( attribute.getAttrvalue().getBase() ) ); attribJSON.put(VALUE_MODIFIER, Integer.parseInt( StringUtils.replacePlus(attribute.getAttrbonus().getBase() ) ) ); int attrBonusModified = Integer.parseInt( StringUtils.replacePlus( attribute.getAttrvalue().getModified() ) ); int attrBonusBase = Integer.parseInt( StringUtils.replacePlus( attribute.getAttrbonus().getModified() ) ); if ( attrBonusModified == attrBonusBase ) { attribJSON.put(BONUS, new Integer( 0 ) ); attribJSON.put(BONUS_MODIFIER, new Integer( 0 ) ); // _propertyMap.put( getAbbreviatedEnhancementBonusName(attribute), // new Integer( 0 ) ); } else { attribJSON.put( BONUS, new Integer( attrBonusModified ) ); attribJSON.put( BONUS_MODIFIER, new Integer( StringUtils.replacePlus( attribute.getAttrbonus().getModified())) ); //_propertyMap.put( getAbbreviatedEnhancementBonusName(attribute), // new Integer( attrBonusModified ) ); } //_propertyMap.put(getAttributeDamageKeyName(attribute), new Integer(damage) ); attribJSON.put( DAMAGE, new Integer( 0 ) ); attribJSON.put(TEMP_MODIFIER, new Integer( 0 ) ); } } public Integer getBaseAbilityScore(IAttribute iattribute) { //return (Integer)getTokenProperties(attribute.name() ); HashMap<String, Object> attribute = _attributes.get( iattribute ); return (Integer)attribute.get(VALUE); } public Integer getBaseAbilityModifier(IAttribute iattribute) { //return (Integer)getTokenProperties(attribute.name() ); HashMap<String, Object> attribute = _attributes.get( iattribute ); return (Integer)attribute.get(VALUE_MODIFIER); } public Integer getBonusAbilityScore(IAttribute iattribute) { HashMap<String, Object> attribute = _attributes.get( iattribute ); return (Integer)attribute.get(BONUS); } public Integer getBonusAbilityModifier(IAttribute iattribute) { HashMap<String, Object> attribute = _attributes.get( iattribute ); return (Integer)attribute.get(BONUS_MODIFIER); } public Integer getAbilityDamage(IAttribute iattribute ) { HashMap<String, Object> attribute = _attributes.get( iattribute ); return (Integer)attribute.get(DAMAGE); } private void setArmorClass() { Armorclass ac = _character.getArmorclass(); _propertyMap.put( AC_ARMOR_BONUS, ac.getFromarmor().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( ac.getFromarmor() ) ) : new Integer( 0 ) ); _propertyMap.put( AC_SHIELD_BONUS, ac.getFromshield().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( ac.getFromshield() ) ) : new Integer( 0 ) ); _propertyMap.put( AC_FROM_DEFLECT, ac.getFromdeflect().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( ac.getFromdeflect() ) ) : new Integer( 0 ) ); _propertyMap.put( AC_FROM_DODGE, ac.getFromdodge().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( ac.getFromdodge() ) ) : new Integer( 0 ) ); _propertyMap.put( AC_FROM_NATURAL, ac.getFromnatural().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( ac.getFromnatural() ) ) : new Integer( 0 ) ); _propertyMap.put( SIZE_MOD, ac.getFromsize().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( ac.getFromsize() ) ) : new Integer( 0 ) ); _propertyMap.put( AC_MISC_BONUS_1, ac.getFrommisc().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( ac.getFrommisc() ) ) : new Integer( 0 ) ); _propertyMap.put( AC_MISC_BONUS_2, new Integer( 0 ) ); _propertyMap.put( AC_TEMP_BONUS, new Integer( 0 ) ); _propertyMap.put( ARMOR_MAX_DEX_BONUS, new Integer( 9999 ) ); for ( Penalty p : _character.getPenalties().getPenalty() ) { if (p.getName().equals( "Armor Check Penalty") ) { _propertyMap.put( ARMOR_CHECK_PENALTY, Integer.parseInt( p.getValue() ) ); } else if ( p.getName().equals( "Max Dex Bonus") ) { _propertyMap.put( ARMOR_MAX_DEX_BONUS, Integer.parseInt(p.getValue()) ); } } } private void setSavingThrows() { for(Save s : _character.getSaves().getSave() ) { _propertyMap.put( s.getAbbr() + CLASS_BONUS, s.getBase().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( s.getBase() ) ) : new Integer( 0 ) ); _propertyMap.put( s.getAbbr() + RESIST_BONUS, s.getFromresist().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( s.getFromresist() ) ) : new Integer( 0 ) ); _propertyMap.put( s.getAbbr() + MISC_BONUS, s.getFrommisc().length() > 0 ? Integer.parseInt( StringUtils.replacePlus( s.getFrommisc() ) ) : new Integer( 0 ) ); } } //ICharacter methods public String getName() { return _character.getName(); } public String getPlayer() { return _character.getPlayername(); } public String getRace() { return _character.getRace().getName(); } public String getAlignment() { return _character.getAlignment().getName(); } public String getDeity() { return _character.getDeity().getName(); } public String getGender() { return _character.getPersonal().getGender(); } public Integer getAge() { return Integer.parseInt(_character.getPersonal().getAge()); } public String getHeight() { return _character.getPersonal().getCharheight().getText(); //bug in herolabs output here - it has the weight as the value } public String getWeight() { return _character.getPersonal().getCharweight().getText(); } public Integer getSpeed() { return Integer.parseInt(_character.getMovement().getSpeed().getValue()); } public Integer getLevel() { return Integer.parseInt( _character.getClasses().getLevel() ) ; } public String getClassAbbreviation() { return _character.getClasses().getSummaryabbr(); } public String getSize() { return _character.getSize().getName(); } public Integer getClassHitpoints() { return Integer.parseInt( _character.getHealth().getHitpoints() ); } public Integer getSavingThrowClassBonus(ISavingThrow ist) { return (Integer)_propertyMap.get( ist.toString() + CLASS_BONUS ); } public Integer getMiscellaneousSavingThrowBonus(ISavingThrow ist) { return (Integer)_propertyMap.get( ist.toString() + MISC_BONUS ); } public Integer getResistanceSavingThrowBonus(ISavingThrow ist) { return (Integer)_propertyMap.get( ist.toString() + RESIST_BONUS ); } public Integer getACArmorBonus() { return (Integer)_propertyMap.get( AC_ARMOR_BONUS ); } public Integer getACFromShield() { return (Integer)_propertyMap.get( AC_SHIELD_BONUS ); } public Integer getACFromDeflect() { return (Integer)_propertyMap.get( AC_FROM_DEFLECT ); } public Integer getACFromDodge() { return (Integer)_propertyMap.get( AC_FROM_DODGE ); } public Integer getACFromnNatural() { return (Integer)_propertyMap.get( AC_FROM_NATURAL ); } public Integer getACFromSize() { return (Integer)_propertyMap.get( SIZE_MOD ); } public Integer getACMisc() { return (Integer)_propertyMap.get( AC_MISC_BONUS_1 ); } public Integer getBaseAttackBonus() { return Integer.parseInt( StringUtils.replacePlus( _character.getAttack().getBaseattack() ) ); } public String getVision() { return _vision; //To change body of implemented methods use File | Settings | File Templates. } private Object getTokenProperties( String key ) { return _propertyMap.get(key); } private class IntegerSerializer implements JsonSerializer<Integer> { public JsonElement serialize(Integer integer, java.lang.reflect.Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(integer.toString() ); } } private class SpellSerializer implements JsonSerializer<PFSRDSpell> { public JsonElement serialize(PFSRDSpell spell, java.lang.reflect.Type type, JsonSerializationContext jsonSerializationContext) { return spell.jsonFields(); } } public Token asToken( Config.ConfigEntry configEntry ) throws Exception { _token.createToken( this, configEntry ); _token.setCommonProperties( (ICharacter)this, _propertyMap ); loadMacros(_token.getToken()); //set all the token properties. _token.getToken().setPropertyType(PATHFINDER); //PC or NPC if ( _character.getRole().equals("npc") ) { _token.getToken().setType(Token.Type.NPC); } else { _token.getToken().setType(Token.Type.PC); } //do the attributes GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter( Integer.class, new IntegerSerializer() ) ; gson.registerTypeAdapter( PFSRDSpell.class, new SpellSerializer()); Gson gjson = gson.create(); for( IAttribute ia : IAttribute.values() ) { String json = gjson.toJson(_attributes.get(ia) ); _token.getToken().setProperty(ia.toString(), json); } for( String propKey : _propertyMap.keySet() ) { - _token.getToken().setProperty(propKey, _propertyMap.get(propKey).toString()); + Object propertyValue = _propertyMap.get(propKey); + if ( propertyValue != null ) { + _token.getToken().setProperty(propKey, propertyValue.toString()); + } } _token.getToken().setProperty(FEATS_JSON, gjson.toJson(_feats)); _token.getToken().setProperty(TRAITS_JSON, gjson.toJson(_traits)); _token.getToken().setProperty(WEAPON_JSON, gjson.toJson( _weapons )); _token.getToken().setProperty(SKILLS_JSON, gjson.toJson(_skills)); _token.getToken().setProperty(RESOURCES_JSON, gjson.toJson(_trackedResources )); //this is a bit tortured, because you can't use triply nested for loops in maptool macros //but it is what it is LinkedList<HashMap<String, Object>> spontaneousSpellResources = new LinkedList<HashMap<String,Object>>(); for( Integer level : _spontaneousSpellResources.keySet()) { LinkedList<HashMap<String, Object>> spellsByLevel = _spontaneousSpellResources.get( level ); for( HashMap<String, Object> spellByLevel : spellsByLevel ) { spontaneousSpellResources.add( spellByLevel ); } } _token.getToken().setProperty(SPONTANEOUS_RESOURCES_JSON, gjson.toJson( spontaneousSpellResources)); _token.getToken().setProperty(MEMORIZED_RESOURCES_JSON, gjson.toJson( _memorizedSpellResources)); //set the spells. this needs to basically happen by class. HashMap< String, SortedMap< Integer, HashMap<String, PFSRDSpell>>> characterSpells = new HashMap<String, SortedMap<Integer, HashMap<String, PFSRDSpell>>>(); for(Spellclass sc : _character.getSpellclasses().getSpellclass() ) { SortedMap< Integer, HashMap<String, PFSRDSpell>> spellsByLevel = this.getSpellsByClassAndLevel( sc.getName() ); characterSpells.put( sc.getName(), spellsByLevel ); } _token.getToken().setProperty(SPELLS_JSON, gjson.toJson(characterSpells)); _token.getToken().setProperty(SPECIAL_ABILITIES_JSON, gjson.toJson(_specials)); //init mod _token.getToken().setProperty(INIT_MOD, _initMod); //vision _token.getToken().setHasSight(true); _token.getToken().setSightType(_vision); //resources return _token.getToken(); } private HashMap<String, HashMap<String, String >> _skills = new HashMap<String, HashMap<String, String>>() ; private void setSkills() { for( Skill s : _character.getSkills().getSkill() ) { String mungedSkillName = mungeSkillName( s.getName() ); HashMap<String, String> skillMap = new HashMap<String, String>(); skillMap.put( "value", s.getValue()); skillMap.put( "ranks", s.getRanks() ); skillMap.put( "description", s.getDescription()); skillMap.put( "skillBonus", "0" ); skillMap.put( "attrBonus", s.getAttrbonus()); skillMap.put( "attrName", s.getAttrname()); skillMap.put( "classSkill", s.getClassskill() != null && s.getClassskill().equals(YES) ? "1" : "0"); skillMap.put( "armorCheckPenalty", s.getArmorcheck() != null && s.getArmorcheck().equals(YES) ? "1" : "0"); skillMap.put( "useTrainedOnly", s.getTrainedonly() != null && s.getTrainedonly().equals(YES) ? "1" : "0" ); skillMap.put( "usable", s.getUsable() != null && s.getUsable().equals(YES) ? "1" : "0" ); skillMap.put( "tools", s.getTools() != null && s.getTools().equals(YES) ? "1" : "0" ); _skills.put( mungedSkillName, skillMap ); } } private static boolean isClassSkill(Skill s) { return s.getClassskill() != null && s.getClassskill().equals( YES ) == true; } private void loadMacros(Token t) throws IOException, SAXException { if ( macroDigester == null ) { macroDigester = new MacroDigester( ResourceManager.getMacroConfigFile().getAbsolutePath() ); macroDigester.parseConfigFile(); } List<MacroButtonProperties> macroButtonSet = new ArrayList<MacroButtonProperties>(); //do the generic macros first. int index = 1; index = buildGenericMacros(macroButtonSet, index); index = buildWeaponMacros(macroButtonSet, index); index = buildSpecialAbilityMacros(macroButtonSet, index); index = buildSkillMacros(macroButtonSet, index); index = buildMemorizedMacros( macroButtonSet, index ); buildSubMacros( macroButtonSet, index ); t.getMacroNextIndex(); //TODO: this is a hack to create the underlying macroPropertiesMap hash table t.replaceMacroList(macroButtonSet); } private int buildMemorizedMacros( List<MacroButtonProperties> macroButtonSet, int index) throws IOException { if ( _memorizedSpellResources.size() == 0 ) { return index; } HashMap<String, MacroDigester.MacroEntry > memorizedMacroSet = macroDigester.getGroup( "Special Abilities - Memorized Spells"); MacroDigester.MacroEntry resetEntry = (MacroDigester.MacroEntry) memorizedMacroSet.values().toArray()[1]; IMacroReplacer defaultReplacer = new DefaultReplacer(); MacroButtonProperties defaultProperties = resetEntry.getMacroButtonProperties( index++, defaultReplacer ); macroButtonSet.add( defaultProperties ); MacroDigester.MacroEntry macroEntry = (MacroDigester.MacroEntry) memorizedMacroSet.values().toArray()[0]; for( Integer level : _memorizedSpellResources.keySet() ) { IMacroReplacer memorizedReplacer = new MemorizedSpellReplacer( level ); MacroButtonProperties properties = macroEntry.getMacroButtonProperties( index++, memorizedReplacer ); properties.setLabel( level.toString() ); macroButtonSet.add( properties ); } return index; } private int buildSubMacros(List<MacroButtonProperties> macroButtonSet, int index) throws IOException { HashMap<String, MacroDigester.MacroEntry > submacros = macroDigester.getGroup( "SUBMACROS"); IMacroReplacer defaultReplacer = new DefaultReplacer(); for( MacroDigester.MacroEntry macroEntry : submacros.values()) { //this is kind of a hack. if ( macroEntry.name.indexOf("spell") == 0 ) { if (isSpellCaster()) { continue; } } MacroButtonProperties properties = macroEntry.getMacroButtonProperties( index++, defaultReplacer ); macroButtonSet.add( properties ); } return index ; } private String mungeSkillName( String skillName ) { return skillName.replaceAll( "\\s|\\(|\\)", ""); } private int buildSkillMacros(List<MacroButtonProperties> macroButtonSet, int index) throws IOException { HashMap<String, MacroDigester.MacroEntry > skillMacros = macroDigester.getGroup( "Skills"); for ( Skill s : _character.getSkills().getSkill() ) { String skillName = s.getName(); String mungedSkillName = mungeSkillName( skillName); String attributeName = s.getAttrname(); String attribShortName = CharacterAttribute.getShortName( attributeName ); SkillReplacer replacer = new SkillReplacer( mungedSkillName, attribShortName ); MacroDigester.MacroEntry macroEntry = skillMacros.get("Skill Check"); boolean disableButton = false; if ( isClassSkill(s) ) { macroEntry.buttonColor = YELLOW; } else if ( s.getTrainedonly().equals(YES ) ) { macroEntry.buttonColor = DARKGRAY; if ( s.getRanks().length() == 0 || s.getRanks().equals("0")) { disableButton = true; } } else { macroEntry.buttonColor = "white"; } //todo: refactor the below into the replacer interface if I ever do it somewhere else. if ( ! disableButton ) { macroEntry.toolTip = BEGIN_ROLL + s.getRanks() + END_ROLL; macroEntry.name = skillName; MacroButtonProperties properties = macroEntry.getMacroButtonProperties( index++, replacer ); macroButtonSet.add( properties ); } } return index; } private int buildGenericMacros(List<MacroButtonProperties> macroButtonSet, int index) throws IOException { index = buildMacros(macroButtonSet, "Basic", index); return index; } private int buildSpecialAbilityMacros(List<MacroButtonProperties> macroButtonSet, int index) throws IOException { index = buildMacros(macroButtonSet, "Special Abilities", index); return index; } private int buildMacros(List<MacroButtonProperties> macroButtonSet, String groupName, int index) throws IOException { HashMap<String, MacroDigester.MacroEntry > genericMacros = macroDigester.getGroup( groupName ); IMacroReplacer defaultReplacer = new DefaultReplacer(); for( MacroDigester.MacroEntry macroEntry : genericMacros.values()) { //kind of a small hack, special for spells //if the character doesn't have spells, don't bother creating a spell button //TODO: probably a smoother way to do this if ( macroEntry.name.equals(SPELL_REFERENCE_MACRO_NAME) ) { if (isSpellCaster()) { continue; } } if ( macroEntry.name.equals(SPONTANEOUS_SPELL_RESOURCES_MACRO_NAME) ) { //same for the above :-) if (_spontaneousSpellResources.size() == 0 ) { continue; } } MacroButtonProperties properties = macroEntry.getMacroButtonProperties( index++, defaultReplacer ); macroButtonSet.add( properties ); } return index; } private boolean isSpellCaster() { return _character.getSpellclasses().getSpellclass().size() == 0; } private boolean isNPC() { return _character.getRole().equals(NPC); } private int buildWeaponMacros(List<MacroButtonProperties> macroButtonSet, int index) throws IOException { //next do the power macros int sortPrefix = 0; HashMap<String, MacroDigester.MacroEntry > powerMacros = macroDigester.getGroup("Fight"); for( WeaponImpl wimpl : _weapons.values()) { MacroDigester.MacroEntry macroEntry = powerMacros.get(STANDARD_ATTACK_MACRO_NAME); if ( sortPrefix == 0 ) { sortPrefix = Integer.parseInt(macroEntry.sortPrefix); //bootstrap the sortPrefix } else { ++sortPrefix; macroEntry.sortPrefix = new Integer( sortPrefix ).toString(); } macroEntry.name = wimpl.name; MacroButtonProperties properties = macroEntry.getMacroButtonProperties( index++, new WeaponNameReplacer( isNPC(), wimpl.name, new Integer(1) ) ); macroButtonSet.add( properties ); //and set all the full attack stuff if ( wimpl.numFullAttacks > 1 ) { for ( Integer attackCount : wimpl.sortedAttacks() ) { MacroDigester.MacroEntry fullAttackMacroEntry = powerMacros.get(ATTACK_FULL); ++sortPrefix; fullAttackMacroEntry.sortPrefix = new Integer( sortPrefix ).toString(); fullAttackMacroEntry.name = attackCount.toString(); MacroButtonProperties faProperties = fullAttackMacroEntry.getMacroButtonProperties( index++, new WeaponNameReplacer( isNPC(), wimpl.name, attackCount ) ); macroButtonSet.add( faProperties ); } } } return index; } }
true
true
public Token asToken( Config.ConfigEntry configEntry ) throws Exception { _token.createToken( this, configEntry ); _token.setCommonProperties( (ICharacter)this, _propertyMap ); loadMacros(_token.getToken()); //set all the token properties. _token.getToken().setPropertyType(PATHFINDER); //PC or NPC if ( _character.getRole().equals("npc") ) { _token.getToken().setType(Token.Type.NPC); } else { _token.getToken().setType(Token.Type.PC); } //do the attributes GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter( Integer.class, new IntegerSerializer() ) ; gson.registerTypeAdapter( PFSRDSpell.class, new SpellSerializer()); Gson gjson = gson.create(); for( IAttribute ia : IAttribute.values() ) { String json = gjson.toJson(_attributes.get(ia) ); _token.getToken().setProperty(ia.toString(), json); } for( String propKey : _propertyMap.keySet() ) { _token.getToken().setProperty(propKey, _propertyMap.get(propKey).toString()); } _token.getToken().setProperty(FEATS_JSON, gjson.toJson(_feats)); _token.getToken().setProperty(TRAITS_JSON, gjson.toJson(_traits)); _token.getToken().setProperty(WEAPON_JSON, gjson.toJson( _weapons )); _token.getToken().setProperty(SKILLS_JSON, gjson.toJson(_skills)); _token.getToken().setProperty(RESOURCES_JSON, gjson.toJson(_trackedResources )); //this is a bit tortured, because you can't use triply nested for loops in maptool macros //but it is what it is LinkedList<HashMap<String, Object>> spontaneousSpellResources = new LinkedList<HashMap<String,Object>>(); for( Integer level : _spontaneousSpellResources.keySet()) { LinkedList<HashMap<String, Object>> spellsByLevel = _spontaneousSpellResources.get( level ); for( HashMap<String, Object> spellByLevel : spellsByLevel ) { spontaneousSpellResources.add( spellByLevel ); } } _token.getToken().setProperty(SPONTANEOUS_RESOURCES_JSON, gjson.toJson( spontaneousSpellResources)); _token.getToken().setProperty(MEMORIZED_RESOURCES_JSON, gjson.toJson( _memorizedSpellResources)); //set the spells. this needs to basically happen by class. HashMap< String, SortedMap< Integer, HashMap<String, PFSRDSpell>>> characterSpells = new HashMap<String, SortedMap<Integer, HashMap<String, PFSRDSpell>>>(); for(Spellclass sc : _character.getSpellclasses().getSpellclass() ) { SortedMap< Integer, HashMap<String, PFSRDSpell>> spellsByLevel = this.getSpellsByClassAndLevel( sc.getName() ); characterSpells.put( sc.getName(), spellsByLevel ); } _token.getToken().setProperty(SPELLS_JSON, gjson.toJson(characterSpells)); _token.getToken().setProperty(SPECIAL_ABILITIES_JSON, gjson.toJson(_specials)); //init mod _token.getToken().setProperty(INIT_MOD, _initMod); //vision _token.getToken().setHasSight(true); _token.getToken().setSightType(_vision); //resources return _token.getToken(); }
public Token asToken( Config.ConfigEntry configEntry ) throws Exception { _token.createToken( this, configEntry ); _token.setCommonProperties( (ICharacter)this, _propertyMap ); loadMacros(_token.getToken()); //set all the token properties. _token.getToken().setPropertyType(PATHFINDER); //PC or NPC if ( _character.getRole().equals("npc") ) { _token.getToken().setType(Token.Type.NPC); } else { _token.getToken().setType(Token.Type.PC); } //do the attributes GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter( Integer.class, new IntegerSerializer() ) ; gson.registerTypeAdapter( PFSRDSpell.class, new SpellSerializer()); Gson gjson = gson.create(); for( IAttribute ia : IAttribute.values() ) { String json = gjson.toJson(_attributes.get(ia) ); _token.getToken().setProperty(ia.toString(), json); } for( String propKey : _propertyMap.keySet() ) { Object propertyValue = _propertyMap.get(propKey); if ( propertyValue != null ) { _token.getToken().setProperty(propKey, propertyValue.toString()); } } _token.getToken().setProperty(FEATS_JSON, gjson.toJson(_feats)); _token.getToken().setProperty(TRAITS_JSON, gjson.toJson(_traits)); _token.getToken().setProperty(WEAPON_JSON, gjson.toJson( _weapons )); _token.getToken().setProperty(SKILLS_JSON, gjson.toJson(_skills)); _token.getToken().setProperty(RESOURCES_JSON, gjson.toJson(_trackedResources )); //this is a bit tortured, because you can't use triply nested for loops in maptool macros //but it is what it is LinkedList<HashMap<String, Object>> spontaneousSpellResources = new LinkedList<HashMap<String,Object>>(); for( Integer level : _spontaneousSpellResources.keySet()) { LinkedList<HashMap<String, Object>> spellsByLevel = _spontaneousSpellResources.get( level ); for( HashMap<String, Object> spellByLevel : spellsByLevel ) { spontaneousSpellResources.add( spellByLevel ); } } _token.getToken().setProperty(SPONTANEOUS_RESOURCES_JSON, gjson.toJson( spontaneousSpellResources)); _token.getToken().setProperty(MEMORIZED_RESOURCES_JSON, gjson.toJson( _memorizedSpellResources)); //set the spells. this needs to basically happen by class. HashMap< String, SortedMap< Integer, HashMap<String, PFSRDSpell>>> characterSpells = new HashMap<String, SortedMap<Integer, HashMap<String, PFSRDSpell>>>(); for(Spellclass sc : _character.getSpellclasses().getSpellclass() ) { SortedMap< Integer, HashMap<String, PFSRDSpell>> spellsByLevel = this.getSpellsByClassAndLevel( sc.getName() ); characterSpells.put( sc.getName(), spellsByLevel ); } _token.getToken().setProperty(SPELLS_JSON, gjson.toJson(characterSpells)); _token.getToken().setProperty(SPECIAL_ABILITIES_JSON, gjson.toJson(_specials)); //init mod _token.getToken().setProperty(INIT_MOD, _initMod); //vision _token.getToken().setHasSight(true); _token.getToken().setSightType(_vision); //resources return _token.getToken(); }
diff --git a/src/backup/BackupTask.java b/src/backup/BackupTask.java index 52c1401..84d200b 100644 --- a/src/backup/BackupTask.java +++ b/src/backup/BackupTask.java @@ -1,236 +1,236 @@ /* * Copyright (C) 2011 Kilian Gaertner * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package backup; import org.bukkit.Server; import org.bukkit.World; import io.FileUtils; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import org.bukkit.command.ConsoleCommandSender; import static io.FileUtils.FILE_SEPARATOR; /** * The BackupTask implements the Interface Runnable for getting executed by the * Server Scheduler. The implemented function run backups the system. * @author Kilian Gaertner */ public class BackupTask implements Runnable, PropertyConstants { // The server where the Task is running private Server server = null; // How many Backups can exists at one time private final int MAX_BACKUPS; private final PropertiesSystem pSystem; private String backupName; private boolean isManuelBackup; /** * The only constructur for the BackupTask. * @param server The server where the Task is running on * @param pSystem This must be a loaded PropertiesSystem */ public BackupTask(Server server,PropertiesSystem pSystem) { this.server = server; this.pSystem = pSystem; MAX_BACKUPS = pSystem.getIntProperty(INT_MAX_BACKUPS); } /** * The implemented function. It starts the backup of the server */ @Override public void run () { boolean backupOnlyWithPlayer = pSystem.getBooleanProperty(BOOL_BACKUP_ONLY_PLAYER); if ((backupOnlyWithPlayer && server.getOnlinePlayers().length > 0) || !backupOnlyWithPlayer || isManuelBackup || backupName != null) backup(); else { System.out.println("[BACKUP] The server skip backup, because no player are online!"); } } /** * Backups the complete server. At first messages were sent to the console * and to every player, so everyone know, a Backup is running. * After this it deactivates all world saves and then saves every player position. * Is this done, every world getting zipped and stored. * */ protected void backup() { // the messages String startBackupMessage = pSystem.getStringProperty(STRING_START_BACKUP_MESSAGE); System.out.println(startBackupMessage); server.broadcastMessage(startBackupMessage); // a hack like methode to send the console command for disabling every world save ConsoleCommandSender ccs = new ConsoleCommandSender(server); server.dispatchCommand(ccs, "save-all"); server.dispatchCommand(ccs, "save-off"); // the Player Position are getting stored server.savePlayers(); String[] worldNames = pSystem.getStringProperty(STRING_NO_BACKUP_WORLDNAMES).split(";"); if (worldNames.length > 0 && !worldNames[0].isEmpty()) { System.out.println("[BACKUP] Skip the followning worlds :"); System.out.println(Arrays.toString(worldNames)); } try { // iterate through every world and zip every one boolean hasToZIP = pSystem.getBooleanProperty(BOOL_ZIP); - if (hasToZIP) + if (!hasToZIP) System.out.println("[BACKUP] Zipping backup is disabled!"); outter : for (World world : server.getWorlds()) { inner : for(String worldName : worldNames) if (worldName.equalsIgnoreCase(world.getName())) continue outter; String backupDir = "backups".concat(FILE_SEPARATOR).concat(world.getName()); if (!hasToZIP) backupDir = backupDir.concat(this.getDate()); // save every information from the RAM into the HDD world.save(); // make a temporary dir of the world FileUtils.copyDirectory(new File(world.getName()), new File(backupDir)); // zip the temporary dir String targetName = world.getName(); String targetDir = "backups".concat(FILE_SEPARATOR); if (backupName != null) { targetName = backupName; targetDir = targetDir.concat("custom").concat(FILE_SEPARATOR); } if (hasToZIP) { FileUtils.zipDirectory(backupDir, targetDir.concat(targetName).concat(getDate())); // delete the temporary dir FileUtils.deleteDirectory(new File(backupDir)); } } } catch (Exception e) { e.printStackTrace(System.out); } // enable the world save server.dispatchCommand(ccs, "save-on"); // the messages String completedBackupMessage = pSystem.getStringProperty(STRING_FINISH_BACKUP_MESSAGE); server.broadcastMessage(completedBackupMessage); System.out.println(completedBackupMessage); // check whether there are old backups to delete deleteOldBackups(); backupName = null; isManuelBackup = false; } /** * @return String representing the current Date in the format * <br> DAY MONTH YEAR-HOUR MINUTE SECOND */ private String getDate() { StringBuilder sBuilder = new StringBuilder(); Calendar cal = Calendar.getInstance(); sBuilder.append(cal.get(Calendar.DAY_OF_MONTH)); int month = cal.get(Calendar.MONTH) + 1; if (month < 10) sBuilder.append("0"); sBuilder.append(month); sBuilder.append(cal.get(Calendar.YEAR)); sBuilder.append("-"); int hours = cal.get(Calendar.HOUR_OF_DAY); if (hours < 10) sBuilder.append("0"); sBuilder.append(hours); int minutes = cal.get(Calendar.MINUTE); if (minutes < 10) sBuilder.append("0"); sBuilder.append(minutes); int seconds = cal.get(Calendar.SECOND); if (seconds < 10) sBuilder.append("0"); sBuilder.append(seconds); return sBuilder.toString(); } /** * Check whethere there are more backups as allowed to store. When this case * is true, it deletes oldest ones */ private void deleteOldBackups () { try { // File backupDir = new File("backups"); // get every zip file in the backup Dir File[] tempArray = backupDir.listFiles(); // when are more backups existing as allowed as to store if (tempArray.length > MAX_BACKUPS) { System.out.println("Delete old backups"); // Store the to delete backups in a list ArrayList<File> backups = new ArrayList<File>(tempArray.length); // For this add all backups in the list and remove later the newest ones backups.addAll(Arrays.asList(tempArray)); // the current index of the newest backup int maxModifiedIndex; // the current time of the newest backup long maxModified; //remove all newest backups from the list to delete for(int i = 0 ; i < MAX_BACKUPS ; ++i) { maxModifiedIndex = 0; maxModified = backups.get(0).lastModified(); for(int j = 1 ; j < backups.size(); ++j) { File currentFile = backups.get(j); if (currentFile.lastModified() > maxModified) { maxModified = currentFile.lastModified(); maxModifiedIndex = j; } } backups.remove(maxModifiedIndex); } // this are the oldest backups, so delete them for(File backupToDelete : backups) backupToDelete.delete(); } } catch(Exception e) { e.printStackTrace(System.out); } } public void setBackupName(String backupName) { this.backupName = backupName; } public void setAsManuelBackup() { this.isManuelBackup = true; } }
true
true
protected void backup() { // the messages String startBackupMessage = pSystem.getStringProperty(STRING_START_BACKUP_MESSAGE); System.out.println(startBackupMessage); server.broadcastMessage(startBackupMessage); // a hack like methode to send the console command for disabling every world save ConsoleCommandSender ccs = new ConsoleCommandSender(server); server.dispatchCommand(ccs, "save-all"); server.dispatchCommand(ccs, "save-off"); // the Player Position are getting stored server.savePlayers(); String[] worldNames = pSystem.getStringProperty(STRING_NO_BACKUP_WORLDNAMES).split(";"); if (worldNames.length > 0 && !worldNames[0].isEmpty()) { System.out.println("[BACKUP] Skip the followning worlds :"); System.out.println(Arrays.toString(worldNames)); } try { // iterate through every world and zip every one boolean hasToZIP = pSystem.getBooleanProperty(BOOL_ZIP); if (hasToZIP) System.out.println("[BACKUP] Zipping backup is disabled!"); outter : for (World world : server.getWorlds()) { inner : for(String worldName : worldNames) if (worldName.equalsIgnoreCase(world.getName())) continue outter; String backupDir = "backups".concat(FILE_SEPARATOR).concat(world.getName()); if (!hasToZIP) backupDir = backupDir.concat(this.getDate()); // save every information from the RAM into the HDD world.save(); // make a temporary dir of the world FileUtils.copyDirectory(new File(world.getName()), new File(backupDir)); // zip the temporary dir String targetName = world.getName(); String targetDir = "backups".concat(FILE_SEPARATOR); if (backupName != null) { targetName = backupName; targetDir = targetDir.concat("custom").concat(FILE_SEPARATOR); } if (hasToZIP) { FileUtils.zipDirectory(backupDir, targetDir.concat(targetName).concat(getDate())); // delete the temporary dir FileUtils.deleteDirectory(new File(backupDir)); } } } catch (Exception e) { e.printStackTrace(System.out); } // enable the world save server.dispatchCommand(ccs, "save-on"); // the messages String completedBackupMessage = pSystem.getStringProperty(STRING_FINISH_BACKUP_MESSAGE); server.broadcastMessage(completedBackupMessage); System.out.println(completedBackupMessage); // check whether there are old backups to delete deleteOldBackups(); backupName = null; isManuelBackup = false; }
protected void backup() { // the messages String startBackupMessage = pSystem.getStringProperty(STRING_START_BACKUP_MESSAGE); System.out.println(startBackupMessage); server.broadcastMessage(startBackupMessage); // a hack like methode to send the console command for disabling every world save ConsoleCommandSender ccs = new ConsoleCommandSender(server); server.dispatchCommand(ccs, "save-all"); server.dispatchCommand(ccs, "save-off"); // the Player Position are getting stored server.savePlayers(); String[] worldNames = pSystem.getStringProperty(STRING_NO_BACKUP_WORLDNAMES).split(";"); if (worldNames.length > 0 && !worldNames[0].isEmpty()) { System.out.println("[BACKUP] Skip the followning worlds :"); System.out.println(Arrays.toString(worldNames)); } try { // iterate through every world and zip every one boolean hasToZIP = pSystem.getBooleanProperty(BOOL_ZIP); if (!hasToZIP) System.out.println("[BACKUP] Zipping backup is disabled!"); outter : for (World world : server.getWorlds()) { inner : for(String worldName : worldNames) if (worldName.equalsIgnoreCase(world.getName())) continue outter; String backupDir = "backups".concat(FILE_SEPARATOR).concat(world.getName()); if (!hasToZIP) backupDir = backupDir.concat(this.getDate()); // save every information from the RAM into the HDD world.save(); // make a temporary dir of the world FileUtils.copyDirectory(new File(world.getName()), new File(backupDir)); // zip the temporary dir String targetName = world.getName(); String targetDir = "backups".concat(FILE_SEPARATOR); if (backupName != null) { targetName = backupName; targetDir = targetDir.concat("custom").concat(FILE_SEPARATOR); } if (hasToZIP) { FileUtils.zipDirectory(backupDir, targetDir.concat(targetName).concat(getDate())); // delete the temporary dir FileUtils.deleteDirectory(new File(backupDir)); } } } catch (Exception e) { e.printStackTrace(System.out); } // enable the world save server.dispatchCommand(ccs, "save-on"); // the messages String completedBackupMessage = pSystem.getStringProperty(STRING_FINISH_BACKUP_MESSAGE); server.broadcastMessage(completedBackupMessage); System.out.println(completedBackupMessage); // check whether there are old backups to delete deleteOldBackups(); backupName = null; isManuelBackup = false; }
diff --git a/src/com/wrapp/android/webimage/ImageLoader.java b/src/com/wrapp/android/webimage/ImageLoader.java index 239c7fa..1c61043 100644 --- a/src/com/wrapp/android/webimage/ImageLoader.java +++ b/src/com/wrapp/android/webimage/ImageLoader.java @@ -1,151 +1,151 @@ /* * Copyright (c) 2011 Bohemian Wrappsody, AB * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.wrapp.android.webimage; import android.graphics.drawable.Drawable; import java.net.URL; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class ImageLoader { private static final int NUM_WORKERS = 2; private static ImageLoader staticInstance; private final Queue<ImageRequest> pendingRequests; private static class Worker extends Thread { @Override public void run() { final Queue<ImageRequest> requestQueue = getInstance().pendingRequests; ImageRequest request; while(true) { synchronized(requestQueue) { while(requestQueue.isEmpty()) { try { requestQueue.wait(); } catch(InterruptedException e) { // Log, but otherwise ignore. Not a big deal. LogWrapper.logException(e); } } request = getNextRequest(requestQueue); } processRequest(request); } } private ImageRequest getNextRequest(Queue<ImageRequest> requestQueue) { ImageRequest request = requestQueue.poll(); Iterator requestIterator = requestQueue.iterator(); while(requestIterator.hasNext()) { ImageRequest checkRequest = (ImageRequest)requestIterator.next(); if(request.listener.equals(checkRequest.listener)) { if(request.imageUrl.equals(checkRequest.imageUrl)) { // Ignore duplicate requests. This is common when doing view recycling in list adapters. request.listener.onDrawableLoadCancelled(); requestIterator.remove(); } else { // If this request in the queue was made by the same listener but is for a new URL, // then use that request instead and remove it from the queue. request.listener.onDrawableLoadCancelled(); request = checkRequest; requestIterator.remove(); } } } return request; } private void processRequest(ImageRequest request) { try { Drawable drawable = ImageCache.loadImage(request); if(drawable == null) { request.listener.onDrawableError("Failed to load image"); } else { // When this request has completed successfully, check the pending requests queue again // to see if this same listener has made a request for a different image. This is quite // common in list adpaters when the user is scrolling quickly. In this case, we return // early without notifying the listener, but at least the image will be cached. final Queue<ImageRequest> requestQueue = getInstance().pendingRequests; synchronized(requestQueue) { for(ImageRequest checkRequest : requestQueue) { if(request.listener.equals(checkRequest.listener) && - !request.imageUrl.equals(checkRequest.listener)) { + !request.imageUrl.equals(checkRequest.imageUrl)) { request.listener.onDrawableLoadCancelled(); return; } } } request.listener.onDrawableLoaded(drawable); } } catch(Exception e) { // Catch any other random exceptions which may be thrown when loading the image. Although // the ImageLoader and ImageCache classes do rigorous try/catch checking, it doesn't hurt // to have a last line of defence. request.listener.onDrawableError(e.getMessage()); } } } private static ImageLoader getInstance() { if(staticInstance == null) { staticInstance = new ImageLoader(); } return staticInstance; } private ImageLoader() { pendingRequests = new LinkedList<ImageRequest>(); final Worker[] workerPool = new Worker[NUM_WORKERS]; for(int i = 0; i < NUM_WORKERS; i++) { workerPool[i] = new Worker(); workerPool[i].start(); } } public static void load(URL imageUrl, ImageRequest.Listener listener, boolean cacheInMemory) { Queue<ImageRequest> requestQueue = getInstance().pendingRequests; synchronized(requestQueue) { requestQueue.add(new ImageRequest(imageUrl, listener, cacheInMemory)); requestQueue.notify(); } } public static void cancelAllRequests() { final Queue<ImageRequest> requestQueue = getInstance().pendingRequests; synchronized(requestQueue) { for(ImageRequest request : requestQueue) { request.listener.onDrawableLoadCancelled(); } requestQueue.clear(); } } }
true
true
private void processRequest(ImageRequest request) { try { Drawable drawable = ImageCache.loadImage(request); if(drawable == null) { request.listener.onDrawableError("Failed to load image"); } else { // When this request has completed successfully, check the pending requests queue again // to see if this same listener has made a request for a different image. This is quite // common in list adpaters when the user is scrolling quickly. In this case, we return // early without notifying the listener, but at least the image will be cached. final Queue<ImageRequest> requestQueue = getInstance().pendingRequests; synchronized(requestQueue) { for(ImageRequest checkRequest : requestQueue) { if(request.listener.equals(checkRequest.listener) && !request.imageUrl.equals(checkRequest.listener)) { request.listener.onDrawableLoadCancelled(); return; } } } request.listener.onDrawableLoaded(drawable); } } catch(Exception e) { // Catch any other random exceptions which may be thrown when loading the image. Although // the ImageLoader and ImageCache classes do rigorous try/catch checking, it doesn't hurt // to have a last line of defence. request.listener.onDrawableError(e.getMessage()); } }
private void processRequest(ImageRequest request) { try { Drawable drawable = ImageCache.loadImage(request); if(drawable == null) { request.listener.onDrawableError("Failed to load image"); } else { // When this request has completed successfully, check the pending requests queue again // to see if this same listener has made a request for a different image. This is quite // common in list adpaters when the user is scrolling quickly. In this case, we return // early without notifying the listener, but at least the image will be cached. final Queue<ImageRequest> requestQueue = getInstance().pendingRequests; synchronized(requestQueue) { for(ImageRequest checkRequest : requestQueue) { if(request.listener.equals(checkRequest.listener) && !request.imageUrl.equals(checkRequest.imageUrl)) { request.listener.onDrawableLoadCancelled(); return; } } } request.listener.onDrawableLoaded(drawable); } } catch(Exception e) { // Catch any other random exceptions which may be thrown when loading the image. Although // the ImageLoader and ImageCache classes do rigorous try/catch checking, it doesn't hurt // to have a last line of defence. request.listener.onDrawableError(e.getMessage()); } }
diff --git a/Android/Roger/src/com/bignerdranch/franklin/roger/RogerActivity.java b/Android/Roger/src/com/bignerdranch/franklin/roger/RogerActivity.java index 7afd6f1..136b0ed 100644 --- a/Android/Roger/src/com/bignerdranch/franklin/roger/RogerActivity.java +++ b/Android/Roger/src/com/bignerdranch/franklin/roger/RogerActivity.java @@ -1,484 +1,485 @@ package com.bignerdranch.franklin.roger; import java.util.ArrayList; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.InflateException; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.bignerdranch.franklin.roger.model.RogerParams; import com.bignerdranch.franklin.roger.pair.ConnectionHelper; import com.bignerdranch.franklin.roger.pair.DiscoveryHelper; import com.bignerdranch.franklin.roger.Constants; import com.bignerdranch.franklin.roger.pair.SelectServerDialog; import com.bignerdranch.franklin.roger.pair.ServerDescription; import com.bignerdranch.franklin.roger.util.ViewUtils; public class RogerActivity extends FragmentActivity { public static final String TAG = "RogerActivity"; private static String SERVER_SELECT = "SelectServer"; private static String THE_MANAGEMENT = "Management"; private static final String LAYOUT_PARAM_DIALOG_TAG = "RogerActivity.layoutParamsDialog"; private TheManagement management; private TextView serverNameTextView; private TextView connectionStatusTextView; private FrameLayout container; private ViewGroup containerBorder; private ProgressBar discoveryProgressBar; private static class TheManagement extends Fragment { public LayoutDescription layoutDescription; public RogerParams rogerParams; public boolean textFillSet; public boolean textFillEnabled; public boolean isListView; @Override public void onCreate(Bundle sharedInstanceState) { super.onCreate(sharedInstanceState); setRetainInstance(true); Log.i(TAG, Constants.ACTION_NEW_LAYOUT); Log.i(TAG, Constants.EXTRA_LAYOUT_DESCRIPTION); } @Override public void onDestroy() { super.onDestroy(); ConnectionHelper.getInstance(getActivity()) .connectToServer(null); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); serverNameTextView = (TextView)findViewById(R.id.serverNameTextView); connectionStatusTextView = (TextView)findViewById(R.id.connectionStatusTextView); container = (FrameLayout)findViewById(R.id.container); containerBorder = (ViewGroup)findViewById(R.id.main_container_border); containerBorder.setVisibility(View.GONE); discoveryProgressBar = (ProgressBar)findViewById(R.id.discoveryProgressBar); DiscoveryHelper.getInstance(this) .addListener(discoveryListener); management = (TheManagement)getSupportFragmentManager() .findFragmentByTag(THE_MANAGEMENT); if (management == null) { management = new TheManagement(); getSupportFragmentManager().beginTransaction() .add(management, THE_MANAGEMENT) .commit(); } if (management.layoutDescription != null) { loadLayout(management.layoutDescription); } if (management.rogerParams == null) { float density = getResources().getDisplayMetrics().density; management.rogerParams = new RogerParams(density, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } ConnectionHelper connector = ConnectionHelper.getInstance(this); if (connector.getState() == ConnectionHelper.STATE_DISCONNECTED || connector.getState() == ConnectionHelper.STATE_FAILED) { refreshServers(); } connector.addListener(connectionStateListener); updateServerStatus(); updateDiscovery(); } @Override public void onDestroy() { super.onDestroy(); ConnectionHelper.getInstance(this) .removeListener(connectionStateListener); DiscoveryHelper.getInstance(this) .removeListener(discoveryListener); } private void updateDiscovery() { DiscoveryHelper discover = DiscoveryHelper.getInstance(this); if (discover.getState() == DiscoveryHelper.STATE_DISCOVERING) { discoveryProgressBar.setVisibility(View.VISIBLE); } else { discoveryProgressBar.setVisibility(View.GONE); } } public void setRogerParams(RogerParams params) { management.rogerParams = params; updateLayoutParams(params); loadLayout(); } private void updateLayoutParams(RogerParams params) { if (container == null) { return; } int width = params.getWidthParam(); int height = params.getHeightParam(); FrameLayout.LayoutParams actualParams = new FrameLayout.LayoutParams(width, height); container.setLayoutParams(actualParams); int containerWidth = ViewGroup.LayoutParams.WRAP_CONTENT; int containerHeight = ViewGroup.LayoutParams.WRAP_CONTENT; if (width == ViewGroup.LayoutParams.FILL_PARENT) { containerWidth = width; } if (height == ViewGroup.LayoutParams.FILL_PARENT) { containerHeight = height; } FrameLayout.LayoutParams containerParams = (FrameLayout.LayoutParams) containerBorder.getLayoutParams(); containerParams.width = containerWidth; containerParams.height = containerHeight; containerBorder.setLayoutParams(containerParams); } private void updateServerStatus() { ConnectionHelper connector = ConnectionHelper.getInstance(this); ServerDescription desc = connector.getConnectedServer(); if (desc != null) { serverNameTextView.setText(desc.getName()); serverNameTextView.setVisibility(View.VISIBLE); connectionStatusTextView.setVisibility(View.VISIBLE); } else { serverNameTextView.setText(""); serverNameTextView.setVisibility(View.GONE); connectionStatusTextView.setVisibility(View.GONE); } int stateResId = 0; switch (connector.getState()) { case ConnectionHelper.STATE_CONNECTING: stateResId = R.string.connection_state_connecting; break; case ConnectionHelper.STATE_CONNECTED: stateResId = R.string.connection_state_connected; break; case ConnectionHelper.STATE_FAILED: stateResId = R.string.connection_state_failed; break; case ConnectionHelper.STATE_DISCONNECTED: stateResId = R.string.connection_state_disconnected; break; case ConnectionHelper.STATE_DOWNLOADING: stateResId = R.string.connection_state_downloading; break; default: break; } connectionStatusTextView.setText(stateResId); } private BroadcastReceiver foundServersReceiver = new BroadcastReceiver() { public void onReceive(Context c, Intent i) { ArrayList<?> addresses = (ArrayList<?>)i.getSerializableExtra(Constants.EXTRA_IP_ADDRESSES); if (addresses == null || addresses.size() == 0) return; ConnectionHelper connector = ConnectionHelper.getInstance(c); int state = connector.getState(); if (addresses.size() == 1 && (state == ConnectionHelper.STATE_DISCONNECTED || state == ConnectionHelper.STATE_FAILED)) { // auto connect connector.connectToServer((ServerDescription)addresses.get(0)); return; } Bundle args = new Bundle(); args.putSerializable(Constants.EXTRA_IP_ADDRESSES, addresses); FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag(SERVER_SELECT) == null) { DialogFragment f = new SelectServerDialog(); f.setArguments(args); f.show(fm, SERVER_SELECT); } } }; @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(Constants.ACTION_FOUND_SERVERS); LocalBroadcastManager.getInstance(this) .registerReceiver(foundServersReceiver, filter); } @Override public void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this) .unregisterReceiver(foundServersReceiver); } private void loadLayout() { if (management.layoutDescription != null) { loadLayout(management.layoutDescription); } } private void loadLayout(LayoutDescription description) { management.layoutDescription = description; if (description.getMinVersion() != 0 && description.getMinVersion() > Build.VERSION.SDK_INT) { Log.e(TAG, "invalid version of Android"); String versionFormat = getString(R.string.error_old_android_version_format); ErrorManager.show(getApplicationContext(), String.format(versionFormat, description.getMinVersion())); containerBorder.setVisibility(View.GONE); return; } container.removeAllViews(); updateLayoutParams(management.rogerParams); final int id = description.getResId(this); if (id == 0) { Log.e(TAG, "ID is 0. Not inflating."); Log.e(TAG, " description was: " + description + ""); String layoutError = getString(R.string.error_zero_layout_id); ErrorManager.show(getApplicationContext(), layoutError); containerBorder.setVisibility(View.GONE); return; } Log.i(TAG, "getting a layout inflater..."); final LayoutInflater inflater = description.getApk(this).getLayoutInflater(getLayoutInflater()); Log.i(TAG, "inflating???"); try { if (management.isListView) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); ListView listView = new ListView(this); ArrayList<String> items = new ArrayList<String>(); for (int i = 0; i < 100; i++) { items.add("" + i); } listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView != null) { addTextFill(convertView); return convertView; } else { View v = inflater.inflate(id, parent, false); addTextFill(v); return v; } } }); container.addView(listView, params); } else { View v = inflater.inflate(id, container, false); container.addView(v); } addTextFill(); containerBorder.setVisibility(View.VISIBLE); } catch (InflateException ex) { + Log.i(TAG, "InflateException", ex); Throwable cause = ex; while (cause.getCause() != null) { cause = cause.getCause(); } ErrorManager.show(getApplicationContext(), cause.getMessage()); } } private void addTextFill() { addTextFill(container); } private void addTextFill(View view) { if (!management.textFillSet) { return; } String dummyText = getString(R.string.dummy_text); ArrayList<TextView> views = ViewUtils.findViewsByClass(view, TextView.class); for (TextView textView : views) { String oldText = (String)ViewUtils.getTag(textView, R.id.original_text); if (oldText == null) { oldText = textView.getText() == null ? "" : textView.getText().toString(); ViewUtils.setTag(textView, R.id.original_text); } if (management.textFillEnabled) { textView.setText(dummyText); } else { textView.setText(oldText); } } } protected void showLayoutParamsDialog() { LayoutDialogFragment dialog = LayoutDialogFragment.newInstance(management.rogerParams); dialog.show(getSupportFragmentManager(), LAYOUT_PARAM_DIALOG_TAG); } protected void refreshServers() { DiscoveryHelper.getInstance(this) .startDiscovery(); } private void updateTextFill() { management.textFillSet = true; management.textFillEnabled = !management.textFillEnabled; loadLayout(); } private void toggleListView() { management.isListView = !management.isListView; loadLayout(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: refreshServers(); break; case R.id.menu_layout_options: showLayoutParamsDialog(); break; case R.id.menu_layout_fill_text: updateTextFill(); break; case R.id.menu_toggle_list_view: toggleListView(); break; } return true; } @Override protected void onStart() { super.onStart(); IntentFilter filter = new IntentFilter(Constants.ACTION_NEW_LAYOUT); Log.i(TAG, "registering reciever for " + Constants.ACTION_NEW_LAYOUT + ""); registerReceiver(downloadReceiver, filter); } @Override protected void onStop() { super.onStop(); Log.i(TAG, "unregistering reciever"); unregisterReceiver(downloadReceiver); } private BroadcastReceiver downloadReceiver = new BroadcastReceiver() { public void onReceive(Context c, Intent i) { Log.i(TAG, "received intent: " + i + ""); if (!Constants.ACTION_NEW_LAYOUT.equals(i.getAction())) return; LayoutDescription desc = (LayoutDescription)i .getSerializableExtra(Constants.EXTRA_LAYOUT_DESCRIPTION); if (desc == null) { desc = new LayoutDescription(); String apkPath = i.getStringExtra(Constants.EXTRA_LAYOUT_APK_PATH); String layoutName = i.getStringExtra(Constants.EXTRA_LAYOUT_LAYOUT_NAME).split("\\.")[0]; String packageName = i.getStringExtra(Constants.EXTRA_LAYOUT_PACKAGE_NAME); int minimumVersion = i.getIntExtra(Constants.EXTRA_LAYOUT_MIN_VERSION, 1); int txnId = i.getIntExtra(Constants.EXTRA_LAYOUT_TXN_ID, 1); desc.setApkPath(apkPath); desc.setLayoutName(layoutName); desc.setPackageName(packageName); desc.setMinVersion(minimumVersion); desc.setTxnId(txnId); } if (desc != null) { loadLayout(desc); } } }; private DiscoveryHelper.Listener discoveryListener = new DiscoveryHelper.Listener() { public void onStateChanged(DiscoveryHelper discover) { if (discoveryProgressBar != null) { discoveryProgressBar.post(new Runnable() { public void run() { updateDiscovery(); }}); } } }; private ConnectionHelper.Listener connectionStateListener = new ConnectionHelper.Listener() { public void onStateChanged(ConnectionHelper connector) { if (connectionStatusTextView != null) { connectionStatusTextView.post(new Runnable() { public void run() { updateServerStatus(); }}); } } }; }
true
true
private void loadLayout(LayoutDescription description) { management.layoutDescription = description; if (description.getMinVersion() != 0 && description.getMinVersion() > Build.VERSION.SDK_INT) { Log.e(TAG, "invalid version of Android"); String versionFormat = getString(R.string.error_old_android_version_format); ErrorManager.show(getApplicationContext(), String.format(versionFormat, description.getMinVersion())); containerBorder.setVisibility(View.GONE); return; } container.removeAllViews(); updateLayoutParams(management.rogerParams); final int id = description.getResId(this); if (id == 0) { Log.e(TAG, "ID is 0. Not inflating."); Log.e(TAG, " description was: " + description + ""); String layoutError = getString(R.string.error_zero_layout_id); ErrorManager.show(getApplicationContext(), layoutError); containerBorder.setVisibility(View.GONE); return; } Log.i(TAG, "getting a layout inflater..."); final LayoutInflater inflater = description.getApk(this).getLayoutInflater(getLayoutInflater()); Log.i(TAG, "inflating???"); try { if (management.isListView) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); ListView listView = new ListView(this); ArrayList<String> items = new ArrayList<String>(); for (int i = 0; i < 100; i++) { items.add("" + i); } listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView != null) { addTextFill(convertView); return convertView; } else { View v = inflater.inflate(id, parent, false); addTextFill(v); return v; } } }); container.addView(listView, params); } else { View v = inflater.inflate(id, container, false); container.addView(v); } addTextFill(); containerBorder.setVisibility(View.VISIBLE); } catch (InflateException ex) { Throwable cause = ex; while (cause.getCause() != null) { cause = cause.getCause(); } ErrorManager.show(getApplicationContext(), cause.getMessage()); } }
private void loadLayout(LayoutDescription description) { management.layoutDescription = description; if (description.getMinVersion() != 0 && description.getMinVersion() > Build.VERSION.SDK_INT) { Log.e(TAG, "invalid version of Android"); String versionFormat = getString(R.string.error_old_android_version_format); ErrorManager.show(getApplicationContext(), String.format(versionFormat, description.getMinVersion())); containerBorder.setVisibility(View.GONE); return; } container.removeAllViews(); updateLayoutParams(management.rogerParams); final int id = description.getResId(this); if (id == 0) { Log.e(TAG, "ID is 0. Not inflating."); Log.e(TAG, " description was: " + description + ""); String layoutError = getString(R.string.error_zero_layout_id); ErrorManager.show(getApplicationContext(), layoutError); containerBorder.setVisibility(View.GONE); return; } Log.i(TAG, "getting a layout inflater..."); final LayoutInflater inflater = description.getApk(this).getLayoutInflater(getLayoutInflater()); Log.i(TAG, "inflating???"); try { if (management.isListView) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); ListView listView = new ListView(this); ArrayList<String> items = new ArrayList<String>(); for (int i = 0; i < 100; i++) { items.add("" + i); } listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView != null) { addTextFill(convertView); return convertView; } else { View v = inflater.inflate(id, parent, false); addTextFill(v); return v; } } }); container.addView(listView, params); } else { View v = inflater.inflate(id, container, false); container.addView(v); } addTextFill(); containerBorder.setVisibility(View.VISIBLE); } catch (InflateException ex) { Log.i(TAG, "InflateException", ex); Throwable cause = ex; while (cause.getCause() != null) { cause = cause.getCause(); } ErrorManager.show(getApplicationContext(), cause.getMessage()); } }
diff --git a/esmska/src/esmska/gui/NotificationIcon.java b/esmska/src/esmska/gui/NotificationIcon.java index 0c024ec3..69d10f95 100644 --- a/esmska/src/esmska/gui/NotificationIcon.java +++ b/esmska/src/esmska/gui/NotificationIcon.java @@ -1,233 +1,233 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package esmska.gui; import esmska.utils.L10N; import java.awt.AWTException; import java.awt.Image; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.SwingUtilities; import esmska.utils.OSType; import java.awt.Dimension; import java.util.ResourceBundle; /** Display icon in the notification area (aka system tray) * * @author ripper */ public class NotificationIcon { private static NotificationIcon instance; private static boolean installed; private static final Logger logger = Logger.getLogger(NotificationIcon.class.getName()); private static final String RES = "/esmska/resources/"; private static final ResourceBundle l10n = L10N.l10nBundle; private static final String pauseQueue = l10n.getString("Pause_sms_queue"); private static final String unpauseQueue = l10n.getString("Unpause_sms_queue"); private static final String showWindow = l10n.getString("Show_program"); private static final String hideWindow = l10n.getString("Hide_program"); private PopupMenu popup = null; private TrayIcon trayIcon = null; private MenuItem toggleItem, pauseQueueItem, historyItem, configItem, quitItem, separatorItem; private NotificationIcon() { // show/hide main window toggleItem = new MenuItem(l10n.getString("Show/hide_program")); toggleItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { toggleMainFrameVisibility(); } }); // pause/unpause sms queue pauseQueueItem = new MenuItem(l10n.getString("NotificationIcon.Pause/unpause_sending")); pauseQueueItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainFrame.getInstance().getQueuePanel(). getSMSQueuePauseAction().actionPerformed(e); } }); // show history historyItem = new MenuItem(l10n.getString("History")); historyItem.addActionListener(MainFrame.getInstance().getHistoryAction()); // show settings - configItem = new MenuItem(l10n.getString("Preferences_")); + configItem = new MenuItem(l10n.getString("Preferences")); configItem.addActionListener(MainFrame.getInstance().getConfigAction()); // exit program - quitItem = new MenuItem(l10n.getString("Quit_")); + quitItem = new MenuItem(l10n.getString("Quit")); quitItem.addActionListener(MainFrame.getInstance().getQuitAction()); // separator separatorItem = new MenuItem("-"); // popup menu popup = new PopupMenu(); MainFrame.getInstance().add(popup); //every popup must have parent // populate menu popup.add(toggleItem); popup.add(pauseQueueItem); popup.add(historyItem); popup.add(configItem); popup.add(separatorItem); popup.add(quitItem); //unpopulate menu on some platforms switch (OSType.detect()) { //on MAC, it's not needed to have items to system provided actions case MAC_OS_X: popup.remove(toggleItem); popup.remove(configItem); popup.remove(separatorItem); popup.remove(quitItem); break; } // add default action on left click MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { //single left click toggles window if (SwingUtilities.isLeftMouseButton(e) && !e.isPopupTrigger()) { toggleMainFrameVisibility(); } //update labels on items updateItems(); } }; //choose best icon size String logo = "esmska.png"; if (isSupported()) { Dimension size = SystemTray.getSystemTray().getTrayIconSize(); if (size.getWidth() <= 16 && size.getHeight() <= 16) { logo = "esmska-16.png"; } else if (size.getWidth() <= 32 && size.getHeight() <= 32) { logo = "esmska-32.png"; } else if (size.getWidth() <= 64 && size.getHeight() <= 64) { logo = "esmska-64.png"; } } // construct a TrayIcon Image image = new ImageIcon(getClass().getResource(RES + logo)).getImage(); trayIcon = new TrayIcon(image, "Esmska", popup); trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(mouseAdapter); } /** Get instance of NotificationIcon. This class is singleton. * @return instance if notification area is supported, null otherwise */ public static NotificationIcon getInstance() { if (!isSupported()) { return null; } if (instance == null) { instance = new NotificationIcon(); } return instance; } /** Show or hide main window. Icon must be installed first. */ public static void toggleMainFrameVisibility() { if (!installed) { return; } MainFrame frame = MainFrame.getInstance(); //if iconified, just deiconify and return if ((frame.getExtendedState() & JFrame.ICONIFIED) != 0) { int state = frame.getExtendedState() & ~JFrame.ICONIFIED; //erase iconify bit frame.setExtendedState(state); return; } //toggle visibility frame.setVisible(!frame.isVisible()); } /** Update labels in popup menu according to current program state */ private void updateItems() { MainFrame frame = MainFrame.getInstance(); boolean queuePaused = frame.getQueuePanel().isPaused(); pauseQueueItem.setLabel(queuePaused ? unpauseQueue : pauseQueue); //visible if visible and not iconified boolean visible = frame.isVisible() && (frame.getExtendedState() & JFrame.ICONIFIED) == 0; toggleItem.setLabel(visible ? hideWindow : showWindow); } /** Install a new icon in the notification area. If an icon is already installed, * nothing happens. If notification area is not supported, nothing happens. */ public static void install() { if (!isSupported()) { return; } getInstance(); SystemTray tray = SystemTray.getSystemTray(); try { tray.remove(instance.trayIcon); tray.add(instance.trayIcon); installed = true; } catch (AWTException ex) { logger.log(Level.WARNING, "Can't install program icon in the notification area", ex); } } /** Remove an icon from notification area. If there is no icon installed, * nothing happens. If notification area is not supported, nothing happens. */ public static void uninstall() { if (!isSupported()) { return; } getInstance(); SystemTray tray = SystemTray.getSystemTray(); tray.remove(instance.trayIcon); installed = false; } /** Returns whether notification area is supported on this system. */ public static boolean isSupported() { return SystemTray.isSupported(); } /** Returns whether the notification icon is currently installed */ public static boolean isInstalled() { return installed; } /** Returns the popup menu on notification icon. */ public PopupMenu getPopup() { return popup; } }
false
true
private NotificationIcon() { // show/hide main window toggleItem = new MenuItem(l10n.getString("Show/hide_program")); toggleItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { toggleMainFrameVisibility(); } }); // pause/unpause sms queue pauseQueueItem = new MenuItem(l10n.getString("NotificationIcon.Pause/unpause_sending")); pauseQueueItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainFrame.getInstance().getQueuePanel(). getSMSQueuePauseAction().actionPerformed(e); } }); // show history historyItem = new MenuItem(l10n.getString("History")); historyItem.addActionListener(MainFrame.getInstance().getHistoryAction()); // show settings configItem = new MenuItem(l10n.getString("Preferences_")); configItem.addActionListener(MainFrame.getInstance().getConfigAction()); // exit program quitItem = new MenuItem(l10n.getString("Quit_")); quitItem.addActionListener(MainFrame.getInstance().getQuitAction()); // separator separatorItem = new MenuItem("-"); // popup menu popup = new PopupMenu(); MainFrame.getInstance().add(popup); //every popup must have parent // populate menu popup.add(toggleItem); popup.add(pauseQueueItem); popup.add(historyItem); popup.add(configItem); popup.add(separatorItem); popup.add(quitItem); //unpopulate menu on some platforms switch (OSType.detect()) { //on MAC, it's not needed to have items to system provided actions case MAC_OS_X: popup.remove(toggleItem); popup.remove(configItem); popup.remove(separatorItem); popup.remove(quitItem); break; } // add default action on left click MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { //single left click toggles window if (SwingUtilities.isLeftMouseButton(e) && !e.isPopupTrigger()) { toggleMainFrameVisibility(); } //update labels on items updateItems(); } }; //choose best icon size String logo = "esmska.png"; if (isSupported()) { Dimension size = SystemTray.getSystemTray().getTrayIconSize(); if (size.getWidth() <= 16 && size.getHeight() <= 16) { logo = "esmska-16.png"; } else if (size.getWidth() <= 32 && size.getHeight() <= 32) { logo = "esmska-32.png"; } else if (size.getWidth() <= 64 && size.getHeight() <= 64) { logo = "esmska-64.png"; } } // construct a TrayIcon Image image = new ImageIcon(getClass().getResource(RES + logo)).getImage(); trayIcon = new TrayIcon(image, "Esmska", popup); trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(mouseAdapter); }
private NotificationIcon() { // show/hide main window toggleItem = new MenuItem(l10n.getString("Show/hide_program")); toggleItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { toggleMainFrameVisibility(); } }); // pause/unpause sms queue pauseQueueItem = new MenuItem(l10n.getString("NotificationIcon.Pause/unpause_sending")); pauseQueueItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainFrame.getInstance().getQueuePanel(). getSMSQueuePauseAction().actionPerformed(e); } }); // show history historyItem = new MenuItem(l10n.getString("History")); historyItem.addActionListener(MainFrame.getInstance().getHistoryAction()); // show settings configItem = new MenuItem(l10n.getString("Preferences")); configItem.addActionListener(MainFrame.getInstance().getConfigAction()); // exit program quitItem = new MenuItem(l10n.getString("Quit")); quitItem.addActionListener(MainFrame.getInstance().getQuitAction()); // separator separatorItem = new MenuItem("-"); // popup menu popup = new PopupMenu(); MainFrame.getInstance().add(popup); //every popup must have parent // populate menu popup.add(toggleItem); popup.add(pauseQueueItem); popup.add(historyItem); popup.add(configItem); popup.add(separatorItem); popup.add(quitItem); //unpopulate menu on some platforms switch (OSType.detect()) { //on MAC, it's not needed to have items to system provided actions case MAC_OS_X: popup.remove(toggleItem); popup.remove(configItem); popup.remove(separatorItem); popup.remove(quitItem); break; } // add default action on left click MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { //single left click toggles window if (SwingUtilities.isLeftMouseButton(e) && !e.isPopupTrigger()) { toggleMainFrameVisibility(); } //update labels on items updateItems(); } }; //choose best icon size String logo = "esmska.png"; if (isSupported()) { Dimension size = SystemTray.getSystemTray().getTrayIconSize(); if (size.getWidth() <= 16 && size.getHeight() <= 16) { logo = "esmska-16.png"; } else if (size.getWidth() <= 32 && size.getHeight() <= 32) { logo = "esmska-32.png"; } else if (size.getWidth() <= 64 && size.getHeight() <= 64) { logo = "esmska-64.png"; } } // construct a TrayIcon Image image = new ImageIcon(getClass().getResource(RES + logo)).getImage(); trayIcon = new TrayIcon(image, "Esmska", popup); trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(mouseAdapter); }
diff --git a/java/src/org/broadinstitute/sting/alignment/bwa/AlignmentValidationWalker.java b/java/src/org/broadinstitute/sting/alignment/bwa/AlignmentValidationWalker.java index 018149c5f..a2f8731fc 100644 --- a/java/src/org/broadinstitute/sting/alignment/bwa/AlignmentValidationWalker.java +++ b/java/src/org/broadinstitute/sting/alignment/bwa/AlignmentValidationWalker.java @@ -1,103 +1,119 @@ package org.broadinstitute.sting.alignment.bwa; import org.broadinstitute.sting.gatk.walkers.ReadWalker; import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.StingException; import org.broadinstitute.sting.utils.cmdLine.Argument; import org.broadinstitute.sting.alignment.Alignment; import net.sf.samtools.SAMRecord; /** * Validates alignments against existing reads. * * @author mhanna * @version 0.1 */ public class AlignmentValidationWalker extends ReadWalker<Integer,Integer> { /** * The supporting BWT index generated using BWT. */ @Argument(fullName="BWTPrefix",shortName="BWT",doc="Index files generated by bwa index -d bwtsw",required=false) String prefix = "/Users/mhanna/reference/Ecoli/Escherichia_coli_K12_MG1655.fasta"; /** * The instance used to generate alignments. */ private BWACAligner aligner = null; /** * Create an aligner object. The aligner object will load and hold the BWT until close() is called. */ @Override public void initialize() { aligner = new BWACAligner(prefix + ".ann", prefix + ".amb", prefix + ".pac", prefix + ".bwt", prefix + ".sa", prefix + ".rbwt", prefix + ".rsa"); } /** * Aligns a read to the given reference. * @param ref Reference over the read. Read will most likely be unmapped, so ref will be null. * @param read Read to align. * @return Number of reads aligned by this map (aka 1). */ @Override public Integer map(char[] ref, SAMRecord read) { byte[] bases = read.getReadBases(); if(read.getReadNegativeStrandFlag()) bases = BaseUtils.simpleReverseComplement(bases); boolean matches = true; Alignment[] alignments = aligner.getAlignments(bases); if(alignments.length == 0 && !read.getReadUnmappedFlag()) matches = false; else { for(Alignment alignment: alignments) { matches = (alignment.getContigIndex() == read.getReferenceIndex()); matches &= (alignment.getAlignmentStart() == read.getAlignmentStart()); matches &= (alignment.isNegativeStrand() == read.getReadNegativeStrandFlag()); matches &= (alignment.getCigar().equals(read.getCigar())); - matches &= (alignment.getMappingQuality() == read.getMappingQuality()); + //matches &= (alignment.getMappingQuality() == read.getMappingQuality()); if(matches) break; } } - if(!matches) + if(!matches) { + logger.error("Found mismatch!"); + logger.error(String.format("Read %s:",read.getReadName())); + logger.error(String.format(" Contig index: %d",read.getReferenceIndex())); + logger.error(String.format(" Alignment start: %d", read.getAlignmentStart())); + logger.error(String.format(" Negative strand: %b", read.getReadNegativeStrandFlag())); + logger.error(String.format(" Cigar: %s%n", read.getCigarString())); + logger.error(String.format(" Mapping quality: %s%n", read.getMappingQuality())); + for(int i = 0; i < alignments.length; i++) { + logger.error(String.format("Alignment %d:",i)); + logger.error(String.format(" Contig index: %d",alignments[i].getContigIndex())); + logger.error(String.format(" Alignment start: %d", alignments[i].getAlignmentStart())); + logger.error(String.format(" Negative strand: %b", alignments[i].isNegativeStrand())); + logger.error(String.format(" Cigar: %s", alignments[i].getCigarString())); + logger.error(String.format(" Mapping quality: %s%n", alignments[i].getMappingQuality())); + } throw new StingException(String.format("Read %s mismatches!", read.getReadName())); + } return 1; } /** * Initial value for reduce. In this case, validated reads will be counted. * @return 0, indicating no reads yet validated. */ @Override public Integer reduceInit() { return 0; } /** * Calculates the number of reads processed. * @param value Number of reads processed by this map. * @param sum Number of reads processed before this map. * @return Number of reads processed up to and including this map. */ @Override public Integer reduce(Integer value, Integer sum) { return value + sum; } /** * Cleanup. * @param result Number of reads processed. */ @Override public void onTraversalDone(Integer result) { aligner.close(); super.onTraversalDone(result); } }
false
true
public Integer map(char[] ref, SAMRecord read) { byte[] bases = read.getReadBases(); if(read.getReadNegativeStrandFlag()) bases = BaseUtils.simpleReverseComplement(bases); boolean matches = true; Alignment[] alignments = aligner.getAlignments(bases); if(alignments.length == 0 && !read.getReadUnmappedFlag()) matches = false; else { for(Alignment alignment: alignments) { matches = (alignment.getContigIndex() == read.getReferenceIndex()); matches &= (alignment.getAlignmentStart() == read.getAlignmentStart()); matches &= (alignment.isNegativeStrand() == read.getReadNegativeStrandFlag()); matches &= (alignment.getCigar().equals(read.getCigar())); matches &= (alignment.getMappingQuality() == read.getMappingQuality()); if(matches) break; } } if(!matches) throw new StingException(String.format("Read %s mismatches!", read.getReadName())); return 1; }
public Integer map(char[] ref, SAMRecord read) { byte[] bases = read.getReadBases(); if(read.getReadNegativeStrandFlag()) bases = BaseUtils.simpleReverseComplement(bases); boolean matches = true; Alignment[] alignments = aligner.getAlignments(bases); if(alignments.length == 0 && !read.getReadUnmappedFlag()) matches = false; else { for(Alignment alignment: alignments) { matches = (alignment.getContigIndex() == read.getReferenceIndex()); matches &= (alignment.getAlignmentStart() == read.getAlignmentStart()); matches &= (alignment.isNegativeStrand() == read.getReadNegativeStrandFlag()); matches &= (alignment.getCigar().equals(read.getCigar())); //matches &= (alignment.getMappingQuality() == read.getMappingQuality()); if(matches) break; } } if(!matches) { logger.error("Found mismatch!"); logger.error(String.format("Read %s:",read.getReadName())); logger.error(String.format(" Contig index: %d",read.getReferenceIndex())); logger.error(String.format(" Alignment start: %d", read.getAlignmentStart())); logger.error(String.format(" Negative strand: %b", read.getReadNegativeStrandFlag())); logger.error(String.format(" Cigar: %s%n", read.getCigarString())); logger.error(String.format(" Mapping quality: %s%n", read.getMappingQuality())); for(int i = 0; i < alignments.length; i++) { logger.error(String.format("Alignment %d:",i)); logger.error(String.format(" Contig index: %d",alignments[i].getContigIndex())); logger.error(String.format(" Alignment start: %d", alignments[i].getAlignmentStart())); logger.error(String.format(" Negative strand: %b", alignments[i].isNegativeStrand())); logger.error(String.format(" Cigar: %s", alignments[i].getCigarString())); logger.error(String.format(" Mapping quality: %s%n", alignments[i].getMappingQuality())); } throw new StingException(String.format("Read %s mismatches!", read.getReadName())); } return 1; }
diff --git a/org.eclipse.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapter.java b/org.eclipse.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapter.java index 5dc0a4a89..40e66f75a 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapter.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapter.java @@ -1,280 +1,280 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.text; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Adapts {@link org.eclipse.jface.text.IDocument} for doing search and * replace operations. * * @since 3.0 */ public class FindReplaceDocumentAdapter implements CharSequence { // Shortcuts to findReplace opertion codes private static final FindReplaceOperationCode FIND_FIRST= FindReplaceOperationCode.FIND_FIRST; private static final FindReplaceOperationCode FIND_NEXT= FindReplaceOperationCode.FIND_NEXT; private static final FindReplaceOperationCode REPLACE= FindReplaceOperationCode.REPLACE; private static final FindReplaceOperationCode REPLACE_FIND_NEXT= FindReplaceOperationCode.REPLACE_FIND_NEXT; /** * The adapted document. */ private IDocument fDocument; /** * State for findReplace. */ private FindReplaceOperationCode fFindReplaceState= null; /** * The matcher used in findReplace. */ private Matcher fFindReplaceMatcher; /** * The match offset from the last findReplace call. */ private int fFindReplaceMatchOffset; /** * Constructs a new find replace document adapter. * * @param document the adapted document */ public FindReplaceDocumentAdapter(IDocument document) { Assert.isNotNull(document); fDocument= document; } /** * Returns the region of a given search string in the document based on a set of search criteria. * * @param startOffset document offset at which search starts * @param findString the string to find * @param forwardSearch the search direction * @param caseSensitive indicates whether lower and upper case should be distinguished * @param wholeWord indicates whether the findString should be limited by white spaces as * defined by Character.isWhiteSpace. Must not be used in combination with <code>regExSearch</code>. * @param regExSearch if <code>true</code> findString represents a regular expression * Must not be used in combination with <code>regExSearch</code>. * @return the find or replace region or <code>null</code> if there was no match * @throws BadLocationException if startOffset is an invalid document offset * @throws PatternSyntaxException if a regular expression has invalid syntax */ public IRegion search(int startOffset, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException { Assert.isTrue(!(regExSearch && wholeWord)); // Adjust offset to special meaning of -1 if (startOffset == -1 && forwardSearch) startOffset= 0; if (startOffset == -1 && !forwardSearch) startOffset= length() - 1; return findReplace(FIND_FIRST, startOffset, findString, null, forwardSearch, caseSensitive, wholeWord, regExSearch); } /** * Stateful findReplace executes a FIND, REPLACE, REPLACE_FIND or FIND_FIRST operation. * In case of REPLACE and REPLACE_FIND it sends a <code>DocumentEvent</code> to all * registered <code>IDocumentListener</code>. * * @param startOffset document offset at which search starts * this value is only used in the FIND_FIRST operation and otherwise ignored * @param findString the string to find * this value is only used in the FIND_FIRST operation and otherwise ignored * @param replaceString the string to replace the current match * this value is only used in the REPLACE and REPLACE_FIND operations and otherwise ignored * @param forwardSearch the search direction * @param caseSensitive indicates whether lower and upper case should be distinguished * @param wholeWord indicates whether the findString should be limited by white spaces as * defined by Character.isWhiteSpace. Must not be used in combination with <code>regExSearch</code>. * @param regExSearch if <code>true</code> this operation represents a regular expression * Must not be used in combination with <code>wholeWord</code>. * @param operationCode specifies what kind of operation is executed * @return the find or replace region or <code>null</code> if there was no match * @throws BadLocationException if startOffset is an invalid document offset * @throws IllegalStateException if a REPLACE or REPLACE_FIND operation is not preceded by a successful FIND operation * @throws PatternSyntaxException if a regular expression has invalid syntax * * @see FindReplaceOperationCode#FIND_FIRST * @see FindReplaceOperationCode#FIND_NEXT * @see FindReplaceOperationCode#REPLACE * @see FindReplaceOperationCode#REPLACE_FIND_NEXT */ public IRegion findReplace(FindReplaceOperationCode operationCode, int startOffset, String findString, String replaceText, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException { // Validate option combinations Assert.isTrue(!(regExSearch && wholeWord)); // Validate state if ((operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) && (fFindReplaceState != FIND_FIRST && fFindReplaceState != FIND_NEXT)) throw new IllegalStateException("illegal findReplace state: cannot replace without preceding find"); //$NON-NLS-1$ if (operationCode == FIND_FIRST) { // Reset if (findString == null || findString.length() == 0) return null; // Validate start offset if (startOffset < 0 || startOffset >= length()) throw new BadLocationException(); int patternFlags= 0; if (regExSearch) patternFlags |= Pattern.MULTILINE; if (!caseSensitive) patternFlags |= Pattern.CASE_INSENSITIVE; if (wholeWord) findString= "\\b" + findString + "\\b"; //$NON-NLS-1$ //$NON-NLS-2$ if (!regExSearch && !wholeWord) findString= "\\Q" + findString + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$ fFindReplaceMatchOffset= startOffset; if (fFindReplaceMatcher != null && fFindReplaceMatcher.pattern().pattern().equals(findString) && fFindReplaceMatcher.pattern().flags() == patternFlags) { /* * Commented out for optimazation: * The call is not needed since FIND_FIRST uses find(int) which resets the matcher */ // fFindReplaceMatcher.reset(); } else { Pattern pattern= Pattern.compile(findString, patternFlags); fFindReplaceMatcher= pattern.matcher(this); } } // Set state fFindReplaceState= operationCode; if (operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) { if (regExSearch) { Pattern pattern= fFindReplaceMatcher.pattern(); Matcher replaceTextMatcher= pattern.matcher(fFindReplaceMatcher.group()); try { replaceText= replaceTextMatcher.replaceFirst(replaceText); } catch (IndexOutOfBoundsException ex) { throw new PatternSyntaxException(ex.getLocalizedMessage(), replaceText, -1); } } int offset= fFindReplaceMatcher.start(); fDocument.replace(offset, fFindReplaceMatcher.group().length(), replaceText); if (operationCode == REPLACE) { return new Region(offset, replaceText.length()); } } if (operationCode == FIND_FIRST || operationCode == FIND_NEXT) { if (forwardSearch) { boolean found= false; if (operationCode == FIND_FIRST) found= fFindReplaceMatcher.find(startOffset); else found= fFindReplaceMatcher.find(); fFindReplaceState= operationCode; - if (found) { + if (found && fFindReplaceMatcher.group().length() > 0) { return new Region(fFindReplaceMatcher.start(), fFindReplaceMatcher.group().length()); } else { return null; } } else { // backward search boolean found= fFindReplaceMatcher.find(0); int index= -1; int length= -1; while (found && fFindReplaceMatcher.start() <= fFindReplaceMatchOffset) { index= fFindReplaceMatcher.start(); length= fFindReplaceMatcher.group().length(); found= fFindReplaceMatcher.find(index + 1); } fFindReplaceMatchOffset= index; if (index > -1) { // must set matcher to correct position fFindReplaceMatcher.find(index); return new Region(index, length); } else return null; } } return null; } /** * Subsitutes the previous match with the given text. * Sends a <code>DocumentEvent</code> to all registered <code>IDocumentListener</code>. * * @param length the length of the specified range * @param text the substitution text * @param isRegExReplace if <code>true</code> <code>text</code> represents a regular expression * @return the replace region or <code>null</code> if there was no match * @throws BadLocationException if startOffset is an invalid document offset * @throws IllegalStateException if a REPLACE or REPLACE_FIND operation is not preceded by a successful FIND operation * @throws PatternSyntaxException if a regular expression has invalid syntax * * @see DocumentEvent * @see IDocumentListener */ public IRegion replace(String text, boolean regExReplace) throws BadLocationException { return findReplace(FindReplaceOperationCode.REPLACE, -1, null, text, false, false, false, regExReplace); } // ---------- CharSequence implementation ---------- /* * @see java.lang.CharSequence#length() */ public int length() { return fDocument.getLength(); } /* * @see java.lang.CharSequence#charAt(int) */ public char charAt(int index) { try { return fDocument.getChar(index); } catch (BadLocationException e) { throw new IndexOutOfBoundsException(); } } /* * @see java.lang.CharSequence#subSequence(int, int) */ public CharSequence subSequence(int start, int end) { try { return fDocument.get(start, end - start); } catch (BadLocationException e) { throw new IndexOutOfBoundsException(); } } /* * @see java.lang.Object#toString() */ public String toString() { return fDocument.get(); } }
true
true
public IRegion findReplace(FindReplaceOperationCode operationCode, int startOffset, String findString, String replaceText, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException { // Validate option combinations Assert.isTrue(!(regExSearch && wholeWord)); // Validate state if ((operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) && (fFindReplaceState != FIND_FIRST && fFindReplaceState != FIND_NEXT)) throw new IllegalStateException("illegal findReplace state: cannot replace without preceding find"); //$NON-NLS-1$ if (operationCode == FIND_FIRST) { // Reset if (findString == null || findString.length() == 0) return null; // Validate start offset if (startOffset < 0 || startOffset >= length()) throw new BadLocationException(); int patternFlags= 0; if (regExSearch) patternFlags |= Pattern.MULTILINE; if (!caseSensitive) patternFlags |= Pattern.CASE_INSENSITIVE; if (wholeWord) findString= "\\b" + findString + "\\b"; //$NON-NLS-1$ //$NON-NLS-2$ if (!regExSearch && !wholeWord) findString= "\\Q" + findString + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$ fFindReplaceMatchOffset= startOffset; if (fFindReplaceMatcher != null && fFindReplaceMatcher.pattern().pattern().equals(findString) && fFindReplaceMatcher.pattern().flags() == patternFlags) { /* * Commented out for optimazation: * The call is not needed since FIND_FIRST uses find(int) which resets the matcher */ // fFindReplaceMatcher.reset(); } else { Pattern pattern= Pattern.compile(findString, patternFlags); fFindReplaceMatcher= pattern.matcher(this); } } // Set state fFindReplaceState= operationCode; if (operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) { if (regExSearch) { Pattern pattern= fFindReplaceMatcher.pattern(); Matcher replaceTextMatcher= pattern.matcher(fFindReplaceMatcher.group()); try { replaceText= replaceTextMatcher.replaceFirst(replaceText); } catch (IndexOutOfBoundsException ex) { throw new PatternSyntaxException(ex.getLocalizedMessage(), replaceText, -1); } } int offset= fFindReplaceMatcher.start(); fDocument.replace(offset, fFindReplaceMatcher.group().length(), replaceText); if (operationCode == REPLACE) { return new Region(offset, replaceText.length()); } } if (operationCode == FIND_FIRST || operationCode == FIND_NEXT) { if (forwardSearch) { boolean found= false; if (operationCode == FIND_FIRST) found= fFindReplaceMatcher.find(startOffset); else found= fFindReplaceMatcher.find(); fFindReplaceState= operationCode; if (found) { return new Region(fFindReplaceMatcher.start(), fFindReplaceMatcher.group().length()); } else { return null; } } else { // backward search boolean found= fFindReplaceMatcher.find(0); int index= -1; int length= -1; while (found && fFindReplaceMatcher.start() <= fFindReplaceMatchOffset) { index= fFindReplaceMatcher.start(); length= fFindReplaceMatcher.group().length(); found= fFindReplaceMatcher.find(index + 1); } fFindReplaceMatchOffset= index; if (index > -1) { // must set matcher to correct position fFindReplaceMatcher.find(index); return new Region(index, length); } else return null; } } return null; }
public IRegion findReplace(FindReplaceOperationCode operationCode, int startOffset, String findString, String replaceText, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException { // Validate option combinations Assert.isTrue(!(regExSearch && wholeWord)); // Validate state if ((operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) && (fFindReplaceState != FIND_FIRST && fFindReplaceState != FIND_NEXT)) throw new IllegalStateException("illegal findReplace state: cannot replace without preceding find"); //$NON-NLS-1$ if (operationCode == FIND_FIRST) { // Reset if (findString == null || findString.length() == 0) return null; // Validate start offset if (startOffset < 0 || startOffset >= length()) throw new BadLocationException(); int patternFlags= 0; if (regExSearch) patternFlags |= Pattern.MULTILINE; if (!caseSensitive) patternFlags |= Pattern.CASE_INSENSITIVE; if (wholeWord) findString= "\\b" + findString + "\\b"; //$NON-NLS-1$ //$NON-NLS-2$ if (!regExSearch && !wholeWord) findString= "\\Q" + findString + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$ fFindReplaceMatchOffset= startOffset; if (fFindReplaceMatcher != null && fFindReplaceMatcher.pattern().pattern().equals(findString) && fFindReplaceMatcher.pattern().flags() == patternFlags) { /* * Commented out for optimazation: * The call is not needed since FIND_FIRST uses find(int) which resets the matcher */ // fFindReplaceMatcher.reset(); } else { Pattern pattern= Pattern.compile(findString, patternFlags); fFindReplaceMatcher= pattern.matcher(this); } } // Set state fFindReplaceState= operationCode; if (operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) { if (regExSearch) { Pattern pattern= fFindReplaceMatcher.pattern(); Matcher replaceTextMatcher= pattern.matcher(fFindReplaceMatcher.group()); try { replaceText= replaceTextMatcher.replaceFirst(replaceText); } catch (IndexOutOfBoundsException ex) { throw new PatternSyntaxException(ex.getLocalizedMessage(), replaceText, -1); } } int offset= fFindReplaceMatcher.start(); fDocument.replace(offset, fFindReplaceMatcher.group().length(), replaceText); if (operationCode == REPLACE) { return new Region(offset, replaceText.length()); } } if (operationCode == FIND_FIRST || operationCode == FIND_NEXT) { if (forwardSearch) { boolean found= false; if (operationCode == FIND_FIRST) found= fFindReplaceMatcher.find(startOffset); else found= fFindReplaceMatcher.find(); fFindReplaceState= operationCode; if (found && fFindReplaceMatcher.group().length() > 0) { return new Region(fFindReplaceMatcher.start(), fFindReplaceMatcher.group().length()); } else { return null; } } else { // backward search boolean found= fFindReplaceMatcher.find(0); int index= -1; int length= -1; while (found && fFindReplaceMatcher.start() <= fFindReplaceMatchOffset) { index= fFindReplaceMatcher.start(); length= fFindReplaceMatcher.group().length(); found= fFindReplaceMatcher.find(index + 1); } fFindReplaceMatchOffset= index; if (index > -1) { // must set matcher to correct position fFindReplaceMatcher.find(index); return new Region(index, length); } else return null; } } return null; }
diff --git a/BitDestroyer/src/abilities/WizSpells.java b/BitDestroyer/src/abilities/WizSpells.java index dfb703c..8b3aba7 100755 --- a/BitDestroyer/src/abilities/WizSpells.java +++ b/BitDestroyer/src/abilities/WizSpells.java @@ -1,67 +1,68 @@ package abilities; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import skeleton.*; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.PaintContext; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.ColorModel; import javax.swing.ImageIcon; import characters.Wizard; public class WizSpells extends Spells{ public WizSpells(){ } public class FrostBolt extends WizSpells{ public FrostBolt(int x, int y) { super.buttonName = "FrostBolt"; super.snare_effect = EffectsDatabase.snareTypes.FROSTBOLT; super.setDamage(10); - ImageIcon ii = new ImageIcon(this.getClass().getResource( + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + ImageIcon ii = new ImageIcon(cl.getResource( "frostboltimgUP.png")); super.image = ii.getImage(); super.visible = true; super.x = x; super.y = y; height = image.getHeight(null); width = image.getWidth(null); } public FrostBolt(int x, int y, String any){ super.snare_effect = EffectsDatabase.snareTypes.FROSTBOLT; super.setDamage(20); ClassLoader cl = Thread.currentThread().getContextClassLoader(); ImageIcon ii = new ImageIcon(cl.getResource( "frostboltimgDOWN.png")); super.image = ii.getImage(); super.visible = true; super.x = x; super.y = y; height = image.getHeight(null); width = image.getWidth(null); } public void moveDown() { y -= MISSILE_SPEED; if (y > Skeleton.height) visible = false; } public void moveUp() { y += MISSILE_SPEED; if (y > Skeleton.height) visible = false; } } }
true
true
public FrostBolt(int x, int y) { super.buttonName = "FrostBolt"; super.snare_effect = EffectsDatabase.snareTypes.FROSTBOLT; super.setDamage(10); ImageIcon ii = new ImageIcon(this.getClass().getResource( "frostboltimgUP.png")); super.image = ii.getImage(); super.visible = true; super.x = x; super.y = y; height = image.getHeight(null); width = image.getWidth(null); }
public FrostBolt(int x, int y) { super.buttonName = "FrostBolt"; super.snare_effect = EffectsDatabase.snareTypes.FROSTBOLT; super.setDamage(10); ClassLoader cl = Thread.currentThread().getContextClassLoader(); ImageIcon ii = new ImageIcon(cl.getResource( "frostboltimgUP.png")); super.image = ii.getImage(); super.visible = true; super.x = x; super.y = y; height = image.getHeight(null); width = image.getWidth(null); }
diff --git a/benchmark/src/main/java/info/gehrels/diplomarbeit/hypergraphdb/HyperGraphDBImporter.java b/benchmark/src/main/java/info/gehrels/diplomarbeit/hypergraphdb/HyperGraphDBImporter.java index c12c1fc..c4dcffa 100644 --- a/benchmark/src/main/java/info/gehrels/diplomarbeit/hypergraphdb/HyperGraphDBImporter.java +++ b/benchmark/src/main/java/info/gehrels/diplomarbeit/hypergraphdb/HyperGraphDBImporter.java @@ -1,60 +1,60 @@ package info.gehrels.diplomarbeit.hypergraphdb; import info.gehrels.diplomarbeit.CachingImporter; import info.gehrels.diplomarbeit.Measurement; import info.gehrels.diplomarbeit.Node; import org.hypergraphdb.HGHandle; import org.hypergraphdb.HGValueLink; import org.hypergraphdb.HyperGraph; import org.hypergraphdb.indexing.ByTargetIndexer; import org.hypergraphdb.indexing.DirectValueIndexer; import static info.gehrels.diplomarbeit.Measurement.measure; import static info.gehrels.diplomarbeit.hypergraphdb.HyperGraphDBHelper.createHyperGraphDB; public class HyperGraphDBImporter extends CachingImporter<HGHandle> { private final HyperGraph hyperGraph; public static void main(final String[] args) throws Exception { measure(new Measurement<Void>() { @Override public void execute(Void database) throws Exception { new HyperGraphDBImporter(args[0], args[1]).importNow(); } }); } public HyperGraphDBImporter(String sourceFile, String dbPath) throws Exception { super(sourceFile); hyperGraph = createHyperGraphDB(dbPath); // For Nodes hyperGraph.getIndexManager().register( new DirectValueIndexer(hyperGraph.getTypeSystem().getTypeHandle(Long.class))); // For Edge labels hyperGraph.getIndexManager() .register( new DirectValueIndexer(hyperGraph.getTypeSystem().getTypeHandle(String.class))); // Index incoming edges hyperGraph.getIndexManager() .register( - new ByTargetIndexer(hyperGraph.getTypeSystem().getTypeHandle(String.class), 0)); + new ByTargetIndexer(hyperGraph.getTypeSystem().getTypeHandle(HGValueLink.class), 0)); // Index outgoing edges hyperGraph.getIndexManager() .register( - new ByTargetIndexer(hyperGraph.getTypeSystem().getTypeHandle(String.class), 1)); + new ByTargetIndexer(hyperGraph.getTypeSystem().getTypeHandle(HGValueLink.class), 1)); } @Override protected void createEdgeBetweenCachedNodes(HGHandle from, HGHandle to, String label) throws Exception { hyperGraph.add(new HGValueLink(label, from, to)); } @Override protected HGHandle createNodeForCache(Node node) { return hyperGraph.add(node.id); } }
false
true
public HyperGraphDBImporter(String sourceFile, String dbPath) throws Exception { super(sourceFile); hyperGraph = createHyperGraphDB(dbPath); // For Nodes hyperGraph.getIndexManager().register( new DirectValueIndexer(hyperGraph.getTypeSystem().getTypeHandle(Long.class))); // For Edge labels hyperGraph.getIndexManager() .register( new DirectValueIndexer(hyperGraph.getTypeSystem().getTypeHandle(String.class))); // Index incoming edges hyperGraph.getIndexManager() .register( new ByTargetIndexer(hyperGraph.getTypeSystem().getTypeHandle(String.class), 0)); // Index outgoing edges hyperGraph.getIndexManager() .register( new ByTargetIndexer(hyperGraph.getTypeSystem().getTypeHandle(String.class), 1)); }
public HyperGraphDBImporter(String sourceFile, String dbPath) throws Exception { super(sourceFile); hyperGraph = createHyperGraphDB(dbPath); // For Nodes hyperGraph.getIndexManager().register( new DirectValueIndexer(hyperGraph.getTypeSystem().getTypeHandle(Long.class))); // For Edge labels hyperGraph.getIndexManager() .register( new DirectValueIndexer(hyperGraph.getTypeSystem().getTypeHandle(String.class))); // Index incoming edges hyperGraph.getIndexManager() .register( new ByTargetIndexer(hyperGraph.getTypeSystem().getTypeHandle(HGValueLink.class), 0)); // Index outgoing edges hyperGraph.getIndexManager() .register( new ByTargetIndexer(hyperGraph.getTypeSystem().getTypeHandle(HGValueLink.class), 1)); }
diff --git a/bug-pattern/src/main/java/jp/co/worksap/oss/findbugs/ForbiddenSystemClass.java b/bug-pattern/src/main/java/jp/co/worksap/oss/findbugs/ForbiddenSystemClass.java index ade18ac..84f1628 100755 --- a/bug-pattern/src/main/java/jp/co/worksap/oss/findbugs/ForbiddenSystemClass.java +++ b/bug-pattern/src/main/java/jp/co/worksap/oss/findbugs/ForbiddenSystemClass.java @@ -1,36 +1,35 @@ package jp.co.worksap.oss.findbugs; import org.apache.bcel.classfile.Code; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; public class ForbiddenSystemClass extends OpcodeStackDetector { private BugReporter bugReporter; public ForbiddenSystemClass(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visit(Code obj) { super.visit(obj); } @Override public void sawOpcode(int seen) { if (seen == GETSTATIC) { if (getClassConstantOperand().equals("java/lang/System") && (getNameConstantOperand().equals("out") || getNameConstantOperand() .equals("err"))) { BugInstance bug = new BugInstance(this, "FORBIDDEN_SYSTEM", NORMAL_PRIORITY).addClassAndMethod(this).addSourceLine( this, getPC()); - bug.addInt(getPC()); bugReporter.reportBug(bug); } } } }
true
true
public void sawOpcode(int seen) { if (seen == GETSTATIC) { if (getClassConstantOperand().equals("java/lang/System") && (getNameConstantOperand().equals("out") || getNameConstantOperand() .equals("err"))) { BugInstance bug = new BugInstance(this, "FORBIDDEN_SYSTEM", NORMAL_PRIORITY).addClassAndMethod(this).addSourceLine( this, getPC()); bug.addInt(getPC()); bugReporter.reportBug(bug); } } }
public void sawOpcode(int seen) { if (seen == GETSTATIC) { if (getClassConstantOperand().equals("java/lang/System") && (getNameConstantOperand().equals("out") || getNameConstantOperand() .equals("err"))) { BugInstance bug = new BugInstance(this, "FORBIDDEN_SYSTEM", NORMAL_PRIORITY).addClassAndMethod(this).addSourceLine( this, getPC()); bugReporter.reportBug(bug); } } }
diff --git a/src/fi/hackoid/BeerProjectile.java b/src/fi/hackoid/BeerProjectile.java index f28744c..6506b50 100644 --- a/src/fi/hackoid/BeerProjectile.java +++ b/src/fi/hackoid/BeerProjectile.java @@ -1,94 +1,94 @@ package fi.hackoid; import java.util.Random; import org.andengine.entity.sprite.AnimatedSprite; import org.andengine.extension.physics.box2d.PhysicsConnector; import org.andengine.extension.physics.box2d.PhysicsFactory; import org.andengine.extension.physics.box2d.PhysicsWorld; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.opengl.texture.region.TiledTextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; public class BeerProjectile { private BitmapTextureAtlas textureAtlas; private TiledTextureRegion textureRegion; AnimatedSprite animatedSprite; Body body; Main main; boolean throwedByPlayer; private Random random = new Random(); private static FixtureDef FIXTURE_DEF_PLAYER = PhysicsFactory.createFixtureDef(1, 0.5f, 0f); private static FixtureDef FIXTURE_DEF_ENEMY = PhysicsFactory.createFixtureDef(1, 0.5f, 0f); static { FIXTURE_DEF_PLAYER.filter.groupIndex = -2; FIXTURE_DEF_ENEMY.filter.groupIndex = -4; } public BeerProjectile(Main main, PhysicsWorld world, AnimatedSprite sprite, boolean right, boolean throwedByPlayer) { this.throwedByPlayer = throwedByPlayer; createResources(main); createScene(main.getVertexBufferObjectManager(), world, sprite, right); main.scene.attachChild(animatedSprite); synchronized (main.beers) { main.beers.add(this); } this.main = main; } public void createResources(Main main) { textureAtlas = new BitmapTextureAtlas(main.getTextureManager(), 128, 128, TextureOptions.BILINEAR); textureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(textureAtlas, main, "object_beerbottle.png", 0, 0, 1, 1); textureAtlas.load(); } public void createScene(VertexBufferObjectManager vertexBufferObjectManager, PhysicsWorld world, AnimatedSprite sprite, boolean right) { - float projectileX = sprite.getX(); + float projectileX = sprite.getX() + sprite.getWidth() / 2; float projectileY = sprite.getY(); animatedSprite = new AnimatedSprite(projectileX, projectileY, textureRegion, vertexBufferObjectManager); animatedSprite.setScaleCenterY(textureRegion.getHeight()); animatedSprite.setScale(1); animatedSprite.setCurrentTileIndex(0); animatedSprite.registerUpdateHandler(world); if (throwedByPlayer) { body = PhysicsFactory.createBoxBody(world, animatedSprite, BodyType.DynamicBody, FIXTURE_DEF_PLAYER); } else { body = PhysicsFactory.createBoxBody(world, animatedSprite, BodyType.DynamicBody, FIXTURE_DEF_ENEMY); } body.setUserData("beer"); world.registerPhysicsConnector(new PhysicsConnector(animatedSprite, body, true, true)); body.setGravityScale(0.1f); body.setLinearDamping(0.05f); body.setLinearVelocity(1 + random.nextInt(5) * (right ? 1 : -1), -random.nextInt(5)); body.applyAngularImpulse((random.nextFloat() - 0.5f) * 15); } public void destroy() { synchronized (main.beers) { main.beers.remove(this); } synchronized (main.beersToBeRemoved) { main.beersToBeRemoved.add(this); } } }
true
true
public void createScene(VertexBufferObjectManager vertexBufferObjectManager, PhysicsWorld world, AnimatedSprite sprite, boolean right) { float projectileX = sprite.getX(); float projectileY = sprite.getY(); animatedSprite = new AnimatedSprite(projectileX, projectileY, textureRegion, vertexBufferObjectManager); animatedSprite.setScaleCenterY(textureRegion.getHeight()); animatedSprite.setScale(1); animatedSprite.setCurrentTileIndex(0); animatedSprite.registerUpdateHandler(world); if (throwedByPlayer) { body = PhysicsFactory.createBoxBody(world, animatedSprite, BodyType.DynamicBody, FIXTURE_DEF_PLAYER); } else { body = PhysicsFactory.createBoxBody(world, animatedSprite, BodyType.DynamicBody, FIXTURE_DEF_ENEMY); } body.setUserData("beer"); world.registerPhysicsConnector(new PhysicsConnector(animatedSprite, body, true, true)); body.setGravityScale(0.1f); body.setLinearDamping(0.05f); body.setLinearVelocity(1 + random.nextInt(5) * (right ? 1 : -1), -random.nextInt(5)); body.applyAngularImpulse((random.nextFloat() - 0.5f) * 15); }
public void createScene(VertexBufferObjectManager vertexBufferObjectManager, PhysicsWorld world, AnimatedSprite sprite, boolean right) { float projectileX = sprite.getX() + sprite.getWidth() / 2; float projectileY = sprite.getY(); animatedSprite = new AnimatedSprite(projectileX, projectileY, textureRegion, vertexBufferObjectManager); animatedSprite.setScaleCenterY(textureRegion.getHeight()); animatedSprite.setScale(1); animatedSprite.setCurrentTileIndex(0); animatedSprite.registerUpdateHandler(world); if (throwedByPlayer) { body = PhysicsFactory.createBoxBody(world, animatedSprite, BodyType.DynamicBody, FIXTURE_DEF_PLAYER); } else { body = PhysicsFactory.createBoxBody(world, animatedSprite, BodyType.DynamicBody, FIXTURE_DEF_ENEMY); } body.setUserData("beer"); world.registerPhysicsConnector(new PhysicsConnector(animatedSprite, body, true, true)); body.setGravityScale(0.1f); body.setLinearDamping(0.05f); body.setLinearVelocity(1 + random.nextInt(5) * (right ? 1 : -1), -random.nextInt(5)); body.applyAngularImpulse((random.nextFloat() - 0.5f) * 15); }
diff --git a/src/commons/org/codehaus/groovy/grails/support/GrailsTestSuite.java b/src/commons/org/codehaus/groovy/grails/support/GrailsTestSuite.java index dacc9bbb8..08095bc03 100644 --- a/src/commons/org/codehaus/groovy/grails/support/GrailsTestSuite.java +++ b/src/commons/org/codehaus/groovy/grails/support/GrailsTestSuite.java @@ -1,49 +1,49 @@ /* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.support; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.util.Assert; /** * IoC class to inject properties of Grails test case classes. * * * @author Steven Devijver * @since Aug 28, 2005 */ public class GrailsTestSuite extends TestSuite { private AutowireCapableBeanFactory beanFactory = null; public GrailsTestSuite(AutowireCapableBeanFactory beanFactory, Class clazz) { super(clazz); Assert.notNull(beanFactory, "Bean factory should not be null!"); this.beanFactory = beanFactory; } public void runTest(Test test, TestResult result) { if (test instanceof TestCase) { - beanFactory.autowireBeanProperties(test, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); + beanFactory.autowireBeanProperties(test, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); } test.run(result); } }
true
true
public void runTest(Test test, TestResult result) { if (test instanceof TestCase) { beanFactory.autowireBeanProperties(test, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); } test.run(result); }
public void runTest(Test test, TestResult result) { if (test instanceof TestCase) { beanFactory.autowireBeanProperties(test, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); } test.run(result); }
diff --git a/classes/test/FileHandle.java b/classes/test/FileHandle.java index 0310d68d..8ea9d76c 100644 --- a/classes/test/FileHandle.java +++ b/classes/test/FileHandle.java @@ -1,16 +1,16 @@ // read a local file package classes.test; import java.io.*; public class FileHandle { public static void main(String[] args) { FileInputStream in = null; try { in = new FileInputStream("./classes/test/FileHandle.java"); in.read(); in.close(); in.read(); - } catch (Exception e) { - System.err.println(e.toString()); + } catch (IOException e) { + System.err.println("An IOException has occurred (expected)."); } } }
true
true
public static void main(String[] args) { FileInputStream in = null; try { in = new FileInputStream("./classes/test/FileHandle.java"); in.read(); in.close(); in.read(); } catch (Exception e) { System.err.println(e.toString()); } }
public static void main(String[] args) { FileInputStream in = null; try { in = new FileInputStream("./classes/test/FileHandle.java"); in.read(); in.close(); in.read(); } catch (IOException e) { System.err.println("An IOException has occurred (expected)."); } }
diff --git a/src/lightbeam/editor/MapSettings.java b/src/lightbeam/editor/MapSettings.java index 9e1db54..5514238 100644 --- a/src/lightbeam/editor/MapSettings.java +++ b/src/lightbeam/editor/MapSettings.java @@ -1,150 +1,150 @@ package lightbeam.editor; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import core.GameObjects; import core.tilestate.ITileState; public class MapSettings extends GameObjects { private JPanel panelSettings = new JPanel(); private JTextField txtRows = new JTextField(); private JTextField txtCols = new JTextField(); private ITileState oldTileState = null; private ITileState curTileState = null; private MapArea maparea = null; private int lblWidth = 59; private int txtWidth = 30; private int btnWidth = 16; private int btnHeight = 16; private int margin_left = 15; private int margin_right = 8; private int margin_top = 15; private int margin_bottom = 8; private int ctrlHeight = 32; public MapSettings( MapArea maparea, int rows, int cols ) { this.maparea = maparea; panelSettings.setBorder( new TitledBorder( "Einstellungen:" ) ); panelSettings.setLayout( null ); JPanel pnlRows = new JPanel(); JPanel pnlCols = new JPanel(); pnlRows.setLayout( null ); pnlCols.setLayout( null ); JLabel lblRows = new JLabel( "Zeilen:" ); lblRows.setBounds( margin_left, margin_top, lblWidth, ctrlHeight ); JLabel lblCols = new JLabel( "Spalten:" ); lblCols.setBounds( margin_left, lblRows.getBounds().y + lblRows.getBounds().height + 5, lblWidth, ctrlHeight ); this.txtRows.setText( rows + "" ); this.txtRows.setBounds( margin_left + lblWidth, margin_top, txtWidth, ctrlHeight ); this.txtRows.setHorizontalAlignment( JTextField.CENTER ); this.txtRows.setEditable( false ); this.txtCols.setText( cols + "" ); this.txtCols.setBounds( margin_left + lblWidth, lblCols.getBounds().y , txtWidth, ctrlHeight ); this.txtCols.setHorizontalAlignment( JTextField.CENTER ); this.txtCols.setEditable( false ); // Spielfeldzeile hinzuf�gen: JButton btnRowsUp = new JButton(); btnRowsUp.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnUp.png" ) ); btnRowsUp.setBounds( 2 * margin_left + txtRows.getBounds().x, txtRows.getBounds().y, btnWidth, btnHeight ); btnRowsUp.addMouseListener( new MouseAdapter(){public void mouseReleased(MouseEvent e){ - oldTileState = MapSettings.this.tileset.getSelected(); - curTileState = MapSettings.this.tileset.tile( 1 ); + oldTileState = MapSettings.this.eTileset.getSelected(); + curTileState = MapSettings.this.eTileset.tile( 1 ); - MapSettings.this.tileset.setSelected( curTileState ); + MapSettings.this.eTileset.setSelected( curTileState ); MapSettings.this.maparea.addRow(); - MapSettings.this.tileset.setSelected( oldTileState ); + MapSettings.this.eTileset.setSelected( oldTileState ); int amountRows = Integer.parseInt( MapSettings.this.txtRows.getText() ) + 1; MapSettings.this.txtRows.setText( amountRows + "" ); }}); // Spielfeldzeile entfernen: JButton btnRowsDown = new JButton(); btnRowsDown.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnDown.png" ) ); btnRowsDown.setBounds( 2 * margin_left + txtRows.getBounds().x, txtRows.getBounds().y + txtRows.getBounds().height - btnHeight, btnWidth, btnHeight ); btnRowsDown.addMouseListener( new MouseAdapter(){public void mouseClicked(MouseEvent e){ if( MapSettings.this.maparea.delRow() == true ) { int amountRows = Integer.parseInt( MapSettings.this.txtRows.getText() ) - 1; MapSettings.this.txtRows.setText( amountRows + "" ); } }}); JButton btnColsUp = new JButton(); btnColsUp.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnUp.png" ) ); btnColsUp.setBounds( 2 * margin_left + txtCols.getBounds().x, txtCols.getBounds().y, btnWidth, btnHeight ); btnColsUp.addMouseListener( new MouseAdapter(){public void mouseClicked(MouseEvent e){ - oldTileState = MapSettings.this.tileset.getSelected(); - curTileState = MapSettings.this.tileset.tile( 1 ); + oldTileState = MapSettings.this.eTileset.getSelected(); + curTileState = MapSettings.this.eTileset.tile( 1 ); - MapSettings.this.tileset.setSelected( curTileState ); + MapSettings.this.eTileset.setSelected( curTileState ); MapSettings.this.maparea.addCol(); - MapSettings.this.tileset.setSelected( oldTileState ); + MapSettings.this.eTileset.setSelected( oldTileState ); int amountCols = Integer.parseInt( MapSettings.this.txtCols.getText() ) + 1; MapSettings.this.txtCols.setText( amountCols + "" ); }}); JButton btnColsDown = new JButton(); btnColsDown.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnDown.png" ) ); btnColsDown.setBounds( 2 * margin_left + txtCols.getBounds().x, txtCols.getBounds().y + txtRows.getBounds().height - btnHeight, btnWidth, btnHeight ); btnColsDown.addMouseListener( new MouseAdapter(){public void mouseClicked(MouseEvent e){ if( MapSettings.this.maparea.delCol() == true ) { int amountCols = Integer.parseInt( MapSettings.this.txtCols.getText() ) - 1; MapSettings.this.txtCols.setText( amountCols + "" ); } }}); int iWidth = margin_left + lblWidth + txtWidth + btnWidth + margin_right; int iHeight = txtCols.getBounds().y + txtCols.getBounds().height + margin_bottom; panelSettings.add( lblRows ); panelSettings.add( txtRows ); panelSettings.add( btnRowsUp ); panelSettings.add( btnRowsDown ); panelSettings.add( lblCols ); panelSettings.add( txtCols ); panelSettings.add( btnColsUp ); panelSettings.add( btnColsDown ); panelSettings.setBounds( 5, 5 , iWidth, iHeight ); } public JPanel panel() { return this.panelSettings; } public void resetSettings( int rows, int cols ) { this.oldTileState = null; this.curTileState = null; this.txtRows.setText( rows + "" ); this.txtRows.setText( cols + "" ); } }
false
true
public MapSettings( MapArea maparea, int rows, int cols ) { this.maparea = maparea; panelSettings.setBorder( new TitledBorder( "Einstellungen:" ) ); panelSettings.setLayout( null ); JPanel pnlRows = new JPanel(); JPanel pnlCols = new JPanel(); pnlRows.setLayout( null ); pnlCols.setLayout( null ); JLabel lblRows = new JLabel( "Zeilen:" ); lblRows.setBounds( margin_left, margin_top, lblWidth, ctrlHeight ); JLabel lblCols = new JLabel( "Spalten:" ); lblCols.setBounds( margin_left, lblRows.getBounds().y + lblRows.getBounds().height + 5, lblWidth, ctrlHeight ); this.txtRows.setText( rows + "" ); this.txtRows.setBounds( margin_left + lblWidth, margin_top, txtWidth, ctrlHeight ); this.txtRows.setHorizontalAlignment( JTextField.CENTER ); this.txtRows.setEditable( false ); this.txtCols.setText( cols + "" ); this.txtCols.setBounds( margin_left + lblWidth, lblCols.getBounds().y , txtWidth, ctrlHeight ); this.txtCols.setHorizontalAlignment( JTextField.CENTER ); this.txtCols.setEditable( false ); // Spielfeldzeile hinzuf�gen: JButton btnRowsUp = new JButton(); btnRowsUp.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnUp.png" ) ); btnRowsUp.setBounds( 2 * margin_left + txtRows.getBounds().x, txtRows.getBounds().y, btnWidth, btnHeight ); btnRowsUp.addMouseListener( new MouseAdapter(){public void mouseReleased(MouseEvent e){ oldTileState = MapSettings.this.tileset.getSelected(); curTileState = MapSettings.this.tileset.tile( 1 ); MapSettings.this.tileset.setSelected( curTileState ); MapSettings.this.maparea.addRow(); MapSettings.this.tileset.setSelected( oldTileState ); int amountRows = Integer.parseInt( MapSettings.this.txtRows.getText() ) + 1; MapSettings.this.txtRows.setText( amountRows + "" ); }}); // Spielfeldzeile entfernen: JButton btnRowsDown = new JButton(); btnRowsDown.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnDown.png" ) ); btnRowsDown.setBounds( 2 * margin_left + txtRows.getBounds().x, txtRows.getBounds().y + txtRows.getBounds().height - btnHeight, btnWidth, btnHeight ); btnRowsDown.addMouseListener( new MouseAdapter(){public void mouseClicked(MouseEvent e){ if( MapSettings.this.maparea.delRow() == true ) { int amountRows = Integer.parseInt( MapSettings.this.txtRows.getText() ) - 1; MapSettings.this.txtRows.setText( amountRows + "" ); } }}); JButton btnColsUp = new JButton(); btnColsUp.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnUp.png" ) ); btnColsUp.setBounds( 2 * margin_left + txtCols.getBounds().x, txtCols.getBounds().y, btnWidth, btnHeight ); btnColsUp.addMouseListener( new MouseAdapter(){public void mouseClicked(MouseEvent e){ oldTileState = MapSettings.this.tileset.getSelected(); curTileState = MapSettings.this.tileset.tile( 1 ); MapSettings.this.tileset.setSelected( curTileState ); MapSettings.this.maparea.addCol(); MapSettings.this.tileset.setSelected( oldTileState ); int amountCols = Integer.parseInt( MapSettings.this.txtCols.getText() ) + 1; MapSettings.this.txtCols.setText( amountCols + "" ); }}); JButton btnColsDown = new JButton(); btnColsDown.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnDown.png" ) ); btnColsDown.setBounds( 2 * margin_left + txtCols.getBounds().x, txtCols.getBounds().y + txtRows.getBounds().height - btnHeight, btnWidth, btnHeight ); btnColsDown.addMouseListener( new MouseAdapter(){public void mouseClicked(MouseEvent e){ if( MapSettings.this.maparea.delCol() == true ) { int amountCols = Integer.parseInt( MapSettings.this.txtCols.getText() ) - 1; MapSettings.this.txtCols.setText( amountCols + "" ); } }}); int iWidth = margin_left + lblWidth + txtWidth + btnWidth + margin_right; int iHeight = txtCols.getBounds().y + txtCols.getBounds().height + margin_bottom; panelSettings.add( lblRows ); panelSettings.add( txtRows ); panelSettings.add( btnRowsUp ); panelSettings.add( btnRowsDown ); panelSettings.add( lblCols ); panelSettings.add( txtCols ); panelSettings.add( btnColsUp ); panelSettings.add( btnColsDown ); panelSettings.setBounds( 5, 5 , iWidth, iHeight ); }
public MapSettings( MapArea maparea, int rows, int cols ) { this.maparea = maparea; panelSettings.setBorder( new TitledBorder( "Einstellungen:" ) ); panelSettings.setLayout( null ); JPanel pnlRows = new JPanel(); JPanel pnlCols = new JPanel(); pnlRows.setLayout( null ); pnlCols.setLayout( null ); JLabel lblRows = new JLabel( "Zeilen:" ); lblRows.setBounds( margin_left, margin_top, lblWidth, ctrlHeight ); JLabel lblCols = new JLabel( "Spalten:" ); lblCols.setBounds( margin_left, lblRows.getBounds().y + lblRows.getBounds().height + 5, lblWidth, ctrlHeight ); this.txtRows.setText( rows + "" ); this.txtRows.setBounds( margin_left + lblWidth, margin_top, txtWidth, ctrlHeight ); this.txtRows.setHorizontalAlignment( JTextField.CENTER ); this.txtRows.setEditable( false ); this.txtCols.setText( cols + "" ); this.txtCols.setBounds( margin_left + lblWidth, lblCols.getBounds().y , txtWidth, ctrlHeight ); this.txtCols.setHorizontalAlignment( JTextField.CENTER ); this.txtCols.setEditable( false ); // Spielfeldzeile hinzuf�gen: JButton btnRowsUp = new JButton(); btnRowsUp.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnUp.png" ) ); btnRowsUp.setBounds( 2 * margin_left + txtRows.getBounds().x, txtRows.getBounds().y, btnWidth, btnHeight ); btnRowsUp.addMouseListener( new MouseAdapter(){public void mouseReleased(MouseEvent e){ oldTileState = MapSettings.this.eTileset.getSelected(); curTileState = MapSettings.this.eTileset.tile( 1 ); MapSettings.this.eTileset.setSelected( curTileState ); MapSettings.this.maparea.addRow(); MapSettings.this.eTileset.setSelected( oldTileState ); int amountRows = Integer.parseInt( MapSettings.this.txtRows.getText() ) + 1; MapSettings.this.txtRows.setText( amountRows + "" ); }}); // Spielfeldzeile entfernen: JButton btnRowsDown = new JButton(); btnRowsDown.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnDown.png" ) ); btnRowsDown.setBounds( 2 * margin_left + txtRows.getBounds().x, txtRows.getBounds().y + txtRows.getBounds().height - btnHeight, btnWidth, btnHeight ); btnRowsDown.addMouseListener( new MouseAdapter(){public void mouseClicked(MouseEvent e){ if( MapSettings.this.maparea.delRow() == true ) { int amountRows = Integer.parseInt( MapSettings.this.txtRows.getText() ) - 1; MapSettings.this.txtRows.setText( amountRows + "" ); } }}); JButton btnColsUp = new JButton(); btnColsUp.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnUp.png" ) ); btnColsUp.setBounds( 2 * margin_left + txtCols.getBounds().x, txtCols.getBounds().y, btnWidth, btnHeight ); btnColsUp.addMouseListener( new MouseAdapter(){public void mouseClicked(MouseEvent e){ oldTileState = MapSettings.this.eTileset.getSelected(); curTileState = MapSettings.this.eTileset.tile( 1 ); MapSettings.this.eTileset.setSelected( curTileState ); MapSettings.this.maparea.addCol(); MapSettings.this.eTileset.setSelected( oldTileState ); int amountCols = Integer.parseInt( MapSettings.this.txtCols.getText() ) + 1; MapSettings.this.txtCols.setText( amountCols + "" ); }}); JButton btnColsDown = new JButton(); btnColsDown.setIcon( new ImageIcon( "./src/fx/Lightbeam/editor/palette/btnDown.png" ) ); btnColsDown.setBounds( 2 * margin_left + txtCols.getBounds().x, txtCols.getBounds().y + txtRows.getBounds().height - btnHeight, btnWidth, btnHeight ); btnColsDown.addMouseListener( new MouseAdapter(){public void mouseClicked(MouseEvent e){ if( MapSettings.this.maparea.delCol() == true ) { int amountCols = Integer.parseInt( MapSettings.this.txtCols.getText() ) - 1; MapSettings.this.txtCols.setText( amountCols + "" ); } }}); int iWidth = margin_left + lblWidth + txtWidth + btnWidth + margin_right; int iHeight = txtCols.getBounds().y + txtCols.getBounds().height + margin_bottom; panelSettings.add( lblRows ); panelSettings.add( txtRows ); panelSettings.add( btnRowsUp ); panelSettings.add( btnRowsDown ); panelSettings.add( lblCols ); panelSettings.add( txtCols ); panelSettings.add( btnColsUp ); panelSettings.add( btnColsDown ); panelSettings.setBounds( 5, 5 , iWidth, iHeight ); }