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/org/starlo/bytepusher/Assembler8080.java b/src/org/starlo/bytepusher/Assembler8080.java index ae043f6..d5110c1 100644 --- a/src/org/starlo/bytepusher/Assembler8080.java +++ b/src/org/starlo/bytepusher/Assembler8080.java @@ -1,51 +1,54 @@ package org.starlo.bytepusher; import java.io.*; import java.util.Locale; import android.util.Log; public class Assembler8080 { private static String[] mTokens = null; public static void assemble(File file){ try { FileInputStream fileStream = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(fileStream)); String line; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { if (!line.contains(";")) { - buffer.append(line); + if(line.length() > 0 && line.charAt(0) == '?') + buffer.append("\t"+line); + else + buffer.append(line); } } String rawString = buffer.toString(); String finalString = rawString.substring(rawString.indexOf("main:")+5, rawString.indexOf("ret")).trim(); mTokens = finalString.split("\\s"); Opcodes8080 opcode = null; for (int i=0; i<mTokens.length-1; i+=2) { opcode = Opcodes8080.valueOf(mTokens[i].toUpperCase(Locale.US)); int ordinal = opcode.ordinal(); if (ordinal <= 8){ singleParamOutput(i); }else if (ordinal <= 10) { doubleParamOutput(i); } } reader.close(); }catch (Exception e) { - //Do nothing! + //Do nothing } } private static void singleParamOutput(int firstTokenIndex){ Log.v("Single", mTokens[firstTokenIndex]+" "+mTokens[firstTokenIndex+1]); } private static void doubleParamOutput(int firstTokenIndex){ String[] params = mTokens[firstTokenIndex+1].split(","); Log.v("Double", mTokens[firstTokenIndex]+" "+params[0]+" "+params[1]); } }
false
true
public static void assemble(File file){ try { FileInputStream fileStream = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(fileStream)); String line; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { if (!line.contains(";")) { buffer.append(line); } } String rawString = buffer.toString(); String finalString = rawString.substring(rawString.indexOf("main:")+5, rawString.indexOf("ret")).trim(); mTokens = finalString.split("\\s"); Opcodes8080 opcode = null; for (int i=0; i<mTokens.length-1; i+=2) { opcode = Opcodes8080.valueOf(mTokens[i].toUpperCase(Locale.US)); int ordinal = opcode.ordinal(); if (ordinal <= 8){ singleParamOutput(i); }else if (ordinal <= 10) { doubleParamOutput(i); } } reader.close(); }catch (Exception e) { //Do nothing! } }
public static void assemble(File file){ try { FileInputStream fileStream = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(fileStream)); String line; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { if (!line.contains(";")) { if(line.length() > 0 && line.charAt(0) == '?') buffer.append("\t"+line); else buffer.append(line); } } String rawString = buffer.toString(); String finalString = rawString.substring(rawString.indexOf("main:")+5, rawString.indexOf("ret")).trim(); mTokens = finalString.split("\\s"); Opcodes8080 opcode = null; for (int i=0; i<mTokens.length-1; i+=2) { opcode = Opcodes8080.valueOf(mTokens[i].toUpperCase(Locale.US)); int ordinal = opcode.ordinal(); if (ordinal <= 8){ singleParamOutput(i); }else if (ordinal <= 10) { doubleParamOutput(i); } } reader.close(); }catch (Exception e) { //Do nothing } }
diff --git a/functional-tests-jcommune/src/test/java/org/jtalks/tests/jcommune/tests/profile/JC125ProfileFieldsInOtherUserProfile.java b/functional-tests-jcommune/src/test/java/org/jtalks/tests/jcommune/tests/profile/JC125ProfileFieldsInOtherUserProfile.java index 0dee7e1..9a4ed53 100644 --- a/functional-tests-jcommune/src/test/java/org/jtalks/tests/jcommune/tests/profile/JC125ProfileFieldsInOtherUserProfile.java +++ b/functional-tests-jcommune/src/test/java/org/jtalks/tests/jcommune/tests/profile/JC125ProfileFieldsInOtherUserProfile.java @@ -1,51 +1,51 @@ package org.jtalks.tests.jcommune.tests.profile; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import static org.jtalks.tests.jcommune.assertion.Exsistence.assertionExistBySelector; import static org.jtalks.tests.jcommune.assertion.Exsistence.assertionNotExistBySelector; import static org.jtalks.tests.jcommune.common.JCommuneSeleniumTest.driver; import static org.jtalks.tests.jcommune.common.JCommuneSeleniumTest.logOut; import static org.jtalks.tests.jcommune.common.JCommuneSeleniumTest.profilePage; import static org.jtalks.tests.jcommune.common.JCommuneSeleniumTest.signIn; /** * @autor masyan */ public class JC125ProfileFieldsInOtherUserProfile { @BeforeMethod(alwaysRun = true) @Parameters({"app-url", "uUsername", "uPassword"}) public void setupCase(String appUrl, String username, String password) { driver.get(appUrl); signIn(username, password); } @AfterMethod(alwaysRun = true) @Parameters({"app-url"}) public void destroy(String appUrl) { logOut(appUrl); } @Test @Parameters({"uUsername2"}) public void ViewProfileFromCurrentUsernameLinkTest(String usernameSecond) { driver.get(driver.getCurrentUrl() + "/users/" + usernameSecond); assertionExistBySelector(driver, profilePage.usernameTableFieldSel); assertionExistBySelector(driver, profilePage.firstNameTableFieldSel); assertionExistBySelector(driver, profilePage.lastNameTableFieldSel); assertionExistBySelector(driver, profilePage.locationTableFieldSel); assertionExistBySelector(driver, profilePage.lastLoginTableFieldSel); assertionExistBySelector(driver, profilePage.registrationDateTableFieldSel); assertionExistBySelector(driver, profilePage.avatarDateTableFieldSel); assertionExistBySelector(driver, profilePage.postCountDateTableFieldSel); + assertionExistBySelector(driver, profilePage.signatureTableFieldSel); assertionNotExistBySelector(driver, profilePage.emailTableFieldSel); assertionNotExistBySelector(driver, profilePage.languageTableFieldSel); assertionNotExistBySelector(driver, profilePage.pageSizeTableFieldSel); - assertionNotExistBySelector(driver, profilePage.signatureTableFieldSel); } }
false
true
public void ViewProfileFromCurrentUsernameLinkTest(String usernameSecond) { driver.get(driver.getCurrentUrl() + "/users/" + usernameSecond); assertionExistBySelector(driver, profilePage.usernameTableFieldSel); assertionExistBySelector(driver, profilePage.firstNameTableFieldSel); assertionExistBySelector(driver, profilePage.lastNameTableFieldSel); assertionExistBySelector(driver, profilePage.locationTableFieldSel); assertionExistBySelector(driver, profilePage.lastLoginTableFieldSel); assertionExistBySelector(driver, profilePage.registrationDateTableFieldSel); assertionExistBySelector(driver, profilePage.avatarDateTableFieldSel); assertionExistBySelector(driver, profilePage.postCountDateTableFieldSel); assertionNotExistBySelector(driver, profilePage.emailTableFieldSel); assertionNotExistBySelector(driver, profilePage.languageTableFieldSel); assertionNotExistBySelector(driver, profilePage.pageSizeTableFieldSel); assertionNotExistBySelector(driver, profilePage.signatureTableFieldSel); }
public void ViewProfileFromCurrentUsernameLinkTest(String usernameSecond) { driver.get(driver.getCurrentUrl() + "/users/" + usernameSecond); assertionExistBySelector(driver, profilePage.usernameTableFieldSel); assertionExistBySelector(driver, profilePage.firstNameTableFieldSel); assertionExistBySelector(driver, profilePage.lastNameTableFieldSel); assertionExistBySelector(driver, profilePage.locationTableFieldSel); assertionExistBySelector(driver, profilePage.lastLoginTableFieldSel); assertionExistBySelector(driver, profilePage.registrationDateTableFieldSel); assertionExistBySelector(driver, profilePage.avatarDateTableFieldSel); assertionExistBySelector(driver, profilePage.postCountDateTableFieldSel); assertionExistBySelector(driver, profilePage.signatureTableFieldSel); assertionNotExistBySelector(driver, profilePage.emailTableFieldSel); assertionNotExistBySelector(driver, profilePage.languageTableFieldSel); assertionNotExistBySelector(driver, profilePage.pageSizeTableFieldSel); }
diff --git a/src/test/java/de/frosner/datagenerator/gui/SwingMenuGuiTest.java b/src/test/java/de/frosner/datagenerator/gui/SwingMenuGuiTest.java index a22f121..971c169 100644 --- a/src/test/java/de/frosner/datagenerator/gui/SwingMenuGuiTest.java +++ b/src/test/java/de/frosner/datagenerator/gui/SwingMenuGuiTest.java @@ -1,127 +1,132 @@ package de.frosner.datagenerator.gui; import static org.fest.assertions.Assertions.assertThat; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import org.fest.swing.edt.FailOnThreadViolationRepaintManager; import org.fest.swing.edt.GuiActionRunner; import org.fest.swing.edt.GuiQuery; import org.fest.swing.fixture.FrameFixture; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class SwingMenuGuiTest { private FrameFixture _testFrame; private SwingMenu _frame; @BeforeClass public static void setUpOnce() { FailOnThreadViolationRepaintManager.install(); } @Before public void setUp() { _frame = GuiActionRunner.execute(new GuiQuery<SwingMenu>() { @Override protected SwingMenu executeInEDT() { return new SwingMenu(); } }); _testFrame = new FrameFixture(_frame); _testFrame.show(); _testFrame.target.toFront(); } @After public void tearDown() { _testFrame.cleanUp(); } @Test public void testVerifyFeatureName() { _testFrame.textBox(SwingMenu.TestUtils.FEATURE_MEAN_FIELD_NAME).enterText("0"); _testFrame.textBox(SwingMenu.TestUtils.FEATURE_SIGMA_FIELD_NAME).enterText("1.0"); _testFrame.textBox(SwingMenu.TestUtils.FEATURE_NAME_FIELD_NAME).enterText(""); _frame.testUtils().clickAddFeatureButton(); assertThat(_frame.testUtils().getFeatureDefinitionListModel().size()).isEqualTo(0); } @Test public void testVerifyFeatureMean() { _testFrame.textBox(SwingMenu.TestUtils.FEATURE_NAME_FIELD_NAME).enterText("Feature 1"); _testFrame.textBox(SwingMenu.TestUtils.FEATURE_SIGMA_FIELD_NAME).enterText("1.0"); _testFrame.textBox(SwingMenu.TestUtils.FEATURE_MEAN_FIELD_NAME).enterText(""); _frame.testUtils().clickAddFeatureButton(); assertThat(_frame.testUtils().getFeatureDefinitionListModel().size()).isEqualTo(0); } @Test public void testVerifyFeatureSigma() { _testFrame.textBox(SwingMenu.TestUtils.FEATURE_NAME_FIELD_NAME).enterText("Feature 1"); _testFrame.textBox(SwingMenu.TestUtils.FEATURE_MEAN_FIELD_NAME).enterText("1"); _testFrame.textBox(SwingMenu.TestUtils.FEATURE_SIGMA_FIELD_NAME).enterText(""); _frame.testUtils().clickAddFeatureButton(); assertThat(_frame.testUtils().getFeatureDefinitionListModel().size()).isEqualTo(0); } @Test public void testAddAndRemoveFeature() throws InterruptedException { assertThat(_frame.testUtils().getFeatureDefinitionListModel().size()).isEqualTo(0); _testFrame.textBox(SwingMenu.TestUtils.FEATURE_NAME_FIELD_NAME).enterText("Feature 1"); _testFrame.textBox(SwingMenu.TestUtils.FEATURE_MEAN_FIELD_NAME).enterText("0"); _testFrame.textBox(SwingMenu.TestUtils.FEATURE_SIGMA_FIELD_NAME).enterText("1.0"); _frame.testUtils().clickAddFeatureButton(); assertThat(_frame.testUtils().getFeatureDefinitionListModel().get(0)).isEqualTo("Feature 1"); _frame.testUtils().selectFeature(0); _frame.testUtils().clickRemoveFeatureButton(); assertThat(_frame.testUtils().getFeatureDefinitionListModel().size()).isEqualTo(0); } @Test public void testSelectExportFile() throws InterruptedException { assertThat(_frame.testUtils().getExportFileField().isEditable()).isFalse(); new Thread(new Runnable() { @Override public void run() { Robot robot; try { robot = new Robot(); robot.delay(500); int delay = 50; robot.keyPress(KeyEvent.VK_ALT); + robot.delay(delay); robot.keyPress(KeyEvent.VK_N); + robot.delay(delay); robot.keyRelease(KeyEvent.VK_ALT); + robot.delay(delay); robot.keyRelease(KeyEvent.VK_N); robot.delay(delay); robot.keyPress(KeyEvent.VK_T); + robot.delay(delay); robot.keyRelease(KeyEvent.VK_T); robot.delay(delay); robot.keyPress(KeyEvent.VK_ENTER); + robot.delay(delay); robot.keyRelease(KeyEvent.VK_ENTER); } catch (AWTException e) { e.printStackTrace(); } } }).start(); _frame.testUtils().clickExportFileDialogButton(); assertThat(_frame.testUtils().getExportFileField().getText()).isEqualTo("t"); } @Test public void testLogging() throws InterruptedException { TextAreaLogger.log("Test"); Thread.sleep(250); assertThat(_frame.testUtils().getLog()).contains("Test"); } }
false
true
public void testSelectExportFile() throws InterruptedException { assertThat(_frame.testUtils().getExportFileField().isEditable()).isFalse(); new Thread(new Runnable() { @Override public void run() { Robot robot; try { robot = new Robot(); robot.delay(500); int delay = 50; robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_N); robot.keyRelease(KeyEvent.VK_ALT); robot.keyRelease(KeyEvent.VK_N); robot.delay(delay); robot.keyPress(KeyEvent.VK_T); robot.keyRelease(KeyEvent.VK_T); robot.delay(delay); robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); } catch (AWTException e) { e.printStackTrace(); } } }).start(); _frame.testUtils().clickExportFileDialogButton(); assertThat(_frame.testUtils().getExportFileField().getText()).isEqualTo("t"); }
public void testSelectExportFile() throws InterruptedException { assertThat(_frame.testUtils().getExportFileField().isEditable()).isFalse(); new Thread(new Runnable() { @Override public void run() { Robot robot; try { robot = new Robot(); robot.delay(500); int delay = 50; robot.keyPress(KeyEvent.VK_ALT); robot.delay(delay); robot.keyPress(KeyEvent.VK_N); robot.delay(delay); robot.keyRelease(KeyEvent.VK_ALT); robot.delay(delay); robot.keyRelease(KeyEvent.VK_N); robot.delay(delay); robot.keyPress(KeyEvent.VK_T); robot.delay(delay); robot.keyRelease(KeyEvent.VK_T); robot.delay(delay); robot.keyPress(KeyEvent.VK_ENTER); robot.delay(delay); robot.keyRelease(KeyEvent.VK_ENTER); } catch (AWTException e) { e.printStackTrace(); } } }).start(); _frame.testUtils().clickExportFileDialogButton(); assertThat(_frame.testUtils().getExportFileField().getText()).isEqualTo("t"); }
diff --git a/src/MoveToSpecificDestionation.java b/src/MoveToSpecificDestionation.java index bd31a9b..8ceab9a 100644 --- a/src/MoveToSpecificDestionation.java +++ b/src/MoveToSpecificDestionation.java @@ -1,19 +1,19 @@ import java.util.Collections; import java.util.List; public class MoveToSpecificDestionation extends Behavior { public MoveToSpecificDestionation(Ant ant) { super(ant); } @Override public BehaviorDecision move() { List<Aim> movement = MyBot.ants.getDirections(owner.getPosition(), owner.getDestination()); Collections.shuffle(movement); - return new BehaviorDecision(movement, owner.getDestination(), "Moving to specific destination at " + owner.getDestination(), 15); + return new BehaviorDecision(owner.getDestination(), "Moving to specific destination at " + owner.getDestination(), 15); } }
true
true
public BehaviorDecision move() { List<Aim> movement = MyBot.ants.getDirections(owner.getPosition(), owner.getDestination()); Collections.shuffle(movement); return new BehaviorDecision(movement, owner.getDestination(), "Moving to specific destination at " + owner.getDestination(), 15); }
public BehaviorDecision move() { List<Aim> movement = MyBot.ants.getDirections(owner.getPosition(), owner.getDestination()); Collections.shuffle(movement); return new BehaviorDecision(owner.getDestination(), "Moving to specific destination at " + owner.getDestination(), 15); }
diff --git a/library/src/main/java/net/sourceforge/cilib/entity/topologies/VonNeumannNeighbourhood.java b/library/src/main/java/net/sourceforge/cilib/entity/topologies/VonNeumannNeighbourhood.java index e0bd0b72..eccabeb8 100644 --- a/library/src/main/java/net/sourceforge/cilib/entity/topologies/VonNeumannNeighbourhood.java +++ b/library/src/main/java/net/sourceforge/cilib/entity/topologies/VonNeumannNeighbourhood.java @@ -1,37 +1,37 @@ package net.sourceforge.cilib.entity.topologies; import com.google.common.collect.Lists; import fj.F; import fj.data.List; public class VonNeumannNeighbourhood<E> extends Neighbourhood<E> { private E find(List<E> list, int n, int r, int c) { return list.index(r * n + c); } @Override public List<E> f(final List<E> list, final E target) { final int np = list.length(); final int index = Lists.newArrayList(list).indexOf(target); final int sqSide = (int) Math.round(Math.sqrt(np)); final int nRows = (int) Math.ceil(np / (double) sqSide); final int row = index / sqSide; final int col = index % sqSide; final F<Integer, Integer> colsInRow = new F<Integer, Integer>() { @Override public Integer f(Integer r) { return r == nRows - 1 ? np - r * sqSide : sqSide; } }; final E north = find(list, sqSide, (row - 1 + nRows) % nRows - ((col >= colsInRow.f((row - 1 + nRows) % nRows)) ? 1 : 0), col); - final E south = find(list, sqSide, (row + 1) % nRows - ((col >= colsInRow.f((row + 1) % nRows)) ? sqSide : 0), col); + final E south = find(list, sqSide, ((col >= colsInRow.f((row + 1) % nRows)) ? 0 : (row + 1) % nRows), col); final E east = find(list, sqSide, row, (col + 1) % colsInRow.f(row)); final E west = find(list, sqSide, row, (col - 1 + colsInRow.f(row)) % colsInRow.f(row)); return List.list(target, north, east, south, west); } }
true
true
public List<E> f(final List<E> list, final E target) { final int np = list.length(); final int index = Lists.newArrayList(list).indexOf(target); final int sqSide = (int) Math.round(Math.sqrt(np)); final int nRows = (int) Math.ceil(np / (double) sqSide); final int row = index / sqSide; final int col = index % sqSide; final F<Integer, Integer> colsInRow = new F<Integer, Integer>() { @Override public Integer f(Integer r) { return r == nRows - 1 ? np - r * sqSide : sqSide; } }; final E north = find(list, sqSide, (row - 1 + nRows) % nRows - ((col >= colsInRow.f((row - 1 + nRows) % nRows)) ? 1 : 0), col); final E south = find(list, sqSide, (row + 1) % nRows - ((col >= colsInRow.f((row + 1) % nRows)) ? sqSide : 0), col); final E east = find(list, sqSide, row, (col + 1) % colsInRow.f(row)); final E west = find(list, sqSide, row, (col - 1 + colsInRow.f(row)) % colsInRow.f(row)); return List.list(target, north, east, south, west); }
public List<E> f(final List<E> list, final E target) { final int np = list.length(); final int index = Lists.newArrayList(list).indexOf(target); final int sqSide = (int) Math.round(Math.sqrt(np)); final int nRows = (int) Math.ceil(np / (double) sqSide); final int row = index / sqSide; final int col = index % sqSide; final F<Integer, Integer> colsInRow = new F<Integer, Integer>() { @Override public Integer f(Integer r) { return r == nRows - 1 ? np - r * sqSide : sqSide; } }; final E north = find(list, sqSide, (row - 1 + nRows) % nRows - ((col >= colsInRow.f((row - 1 + nRows) % nRows)) ? 1 : 0), col); final E south = find(list, sqSide, ((col >= colsInRow.f((row + 1) % nRows)) ? 0 : (row + 1) % nRows), col); final E east = find(list, sqSide, row, (col + 1) % colsInRow.f(row)); final E west = find(list, sqSide, row, (col - 1 + colsInRow.f(row)) % colsInRow.f(row)); return List.list(target, north, east, south, west); }
diff --git a/src/VASSAL/tools/BugUtils.java b/src/VASSAL/tools/BugUtils.java index 2f8b82fc..13b3fd11 100644 --- a/src/VASSAL/tools/BugUtils.java +++ b/src/VASSAL/tools/BugUtils.java @@ -1,102 +1,103 @@ package VASSAL.tools; import java.io.File; import java.io.FileReader; import java.io.InputStream; import java.io.IOException; import VASSAL.Info; import VASSAL.tools.io.IOUtils; public class BugUtils { public static void sendBugReport(String email, String description, String errorLog, Throwable t) throws IOException { final HTTPPostBuilder pb = new HTTPPostBuilder(); InputStream in = null; try { /* final URL url = new URL("http://sourceforge.net/tracker/index.php"); pb.setParameter("group_id", "90612"); pb.setParameter("atid", "594231"); pb.setParameter("func", "postadd"); pb.setParameter("category_id", "100"); pb.setParameter("artifact_group_id", "100"); pb.setParameter("summary", getSummary(t)); pb.setParameter("details", email + "\n\n" + description); pb.setParameter("input_file", "errorLog", errorLog); pb.setParameter("file_description", "the errorLog"); pb.setParameter("submit", "SUBMIT"); */ final String url = "http://www.vassalengine.org/util/bug.php"; pb.setParameter("version", Info.getVersion()); pb.setParameter("email", email); pb.setParameter("summary", getSummary(t)); pb.setParameter("description", description); pb.setParameter("log", "errorLog", errorLog); in = pb.post(url); + final String result = IOUtils.toString(in); // script should return zero on success, otherwise it failed try { - if (Integer.parseInt(IOUtils.toString(in)) != 0) { - throw new NumberFormatException(); + if (Integer.parseInt(result) != 0) { + throw new NumberFormatException("Bad result: " + result); } } catch (NumberFormatException e) { - throw new IOException(); + throw (IOException) new IOException().initCause(e); } in.close(); } finally { IOUtils.closeQuietly(in); } } private static String getSummary(Throwable t) { String summary; if (t == null) { summary = "Automated Bug Report"; } else { final String tc = t.getClass().getName(); summary = tc.substring(tc.lastIndexOf('.') + 1); if (t.getMessage() != null) { summary += ": " + t.getMessage(); } /* for (StackTraceElement e : t.getStackTrace()) { if (e.getClassName().startsWith("VASSAL")) { summary += " at "+e.getClassName()+"."+e.getMethodName()+" (line "+e.getLineNumber()+")"; break; } } */ } return summary; } // FIXME: move this somewhere else? public static String getErrorLog() { String log = null; FileReader r = null; try { r = new FileReader(new File(Info.getConfDir(), "errorLog")); log = IOUtils.toString(r); r.close(); } catch (IOException e) { // Don't bother logging this---if we can't read the errorLog, // then we probably can't write to it either. IOUtils.closeQuietly(r); } return log; } }
false
true
public static void sendBugReport(String email, String description, String errorLog, Throwable t) throws IOException { final HTTPPostBuilder pb = new HTTPPostBuilder(); InputStream in = null; try { /* final URL url = new URL("http://sourceforge.net/tracker/index.php"); pb.setParameter("group_id", "90612"); pb.setParameter("atid", "594231"); pb.setParameter("func", "postadd"); pb.setParameter("category_id", "100"); pb.setParameter("artifact_group_id", "100"); pb.setParameter("summary", getSummary(t)); pb.setParameter("details", email + "\n\n" + description); pb.setParameter("input_file", "errorLog", errorLog); pb.setParameter("file_description", "the errorLog"); pb.setParameter("submit", "SUBMIT"); */ final String url = "http://www.vassalengine.org/util/bug.php"; pb.setParameter("version", Info.getVersion()); pb.setParameter("email", email); pb.setParameter("summary", getSummary(t)); pb.setParameter("description", description); pb.setParameter("log", "errorLog", errorLog); in = pb.post(url); // script should return zero on success, otherwise it failed try { if (Integer.parseInt(IOUtils.toString(in)) != 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { throw new IOException(); } in.close(); } finally { IOUtils.closeQuietly(in); } }
public static void sendBugReport(String email, String description, String errorLog, Throwable t) throws IOException { final HTTPPostBuilder pb = new HTTPPostBuilder(); InputStream in = null; try { /* final URL url = new URL("http://sourceforge.net/tracker/index.php"); pb.setParameter("group_id", "90612"); pb.setParameter("atid", "594231"); pb.setParameter("func", "postadd"); pb.setParameter("category_id", "100"); pb.setParameter("artifact_group_id", "100"); pb.setParameter("summary", getSummary(t)); pb.setParameter("details", email + "\n\n" + description); pb.setParameter("input_file", "errorLog", errorLog); pb.setParameter("file_description", "the errorLog"); pb.setParameter("submit", "SUBMIT"); */ final String url = "http://www.vassalengine.org/util/bug.php"; pb.setParameter("version", Info.getVersion()); pb.setParameter("email", email); pb.setParameter("summary", getSummary(t)); pb.setParameter("description", description); pb.setParameter("log", "errorLog", errorLog); in = pb.post(url); final String result = IOUtils.toString(in); // script should return zero on success, otherwise it failed try { if (Integer.parseInt(result) != 0) { throw new NumberFormatException("Bad result: " + result); } } catch (NumberFormatException e) { throw (IOException) new IOException().initCause(e); } in.close(); } finally { IOUtils.closeQuietly(in); } }
diff --git a/src/org/powerbat/Boot.java b/src/org/powerbat/Boot.java index 4c3e73c..cc848cf 100644 --- a/src/org/powerbat/Boot.java +++ b/src/org/powerbat/Boot.java @@ -1,101 +1,102 @@ package org.powerbat; import javax.swing.*; import org.powerbat.configuration.Global; import org.powerbat.configuration.Global.Paths; import org.powerbat.executor.Executor; import org.powerbat.gui.GUI; import org.powerbat.gui.Splash; import org.powerbat.methods.Updater; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import java.net.URI; /** * The boot class is responsible for basic loading for the client. Bringing all * the classes into unison, it effectively creates what is known as Powerbat. * Advanced technology to help you learn Java and fulfill what I like to know as * 'Good standing'. Helping others for free. Give what you can and take what you * must. From everything to the CustomClassLoader class to the Project class, * everything here was made for you, the user. I hope you have a great time * running this application. * <br> * <br> * * @author Naux * @version 1.0 * @since 1.0 */ public class Boot { /** * Nothing truly big to see here. Runs the application. Really should be * monitored but it isn't. * * @param args ignored. Or is it? * @since 1.0 */ public static void main(String[] args) { if (!Executor.hasJDKInstalled()) { - final int option = JOptionPane.showConfirmDialog(null, "<html>You need to have JDK installed to run Powerbat.<br>Click 'Ok' if you would like to go to the JDK site.</html>", "JDK Required", - JOptionPane.OK_CANCEL_OPTION); + final int option = JOptionPane.showConfirmDialog(null, + "<html>You need to have JDK installed to run Powerbat.<br>Click 'Ok' if you would like to go to the JDK site.</html>", "JDK Required", + JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE); if (option == JOptionPane.OK_OPTION) { final Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(new URI("www.oracle.com/technetwork/java/javase/downloads/")); } catch (Exception ignored) { } } } System.exit(0); return; } Paths.build(); Global.loadImages(); Splash.setStatus("Loading"); final Splash splash = new Splash(); final Timer repaint = new Timer(20, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { splash.repaint(); } }); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { splash.setVisible(true); repaint.start(); } }); } catch (InterruptedException | InvocationTargetException e) { e.printStackTrace(); System.exit(0); } Updater.update(); Splash.setStatus("Loading framework"); SwingUtilities.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); Splash.setStatus("Building GUI"); new GUI(); splash.shouldDispose(true); splash.dispose(); Splash.setStatus(null); repaint.stop(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } }); } }
true
true
public static void main(String[] args) { if (!Executor.hasJDKInstalled()) { final int option = JOptionPane.showConfirmDialog(null, "<html>You need to have JDK installed to run Powerbat.<br>Click 'Ok' if you would like to go to the JDK site.</html>", "JDK Required", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { final Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(new URI("www.oracle.com/technetwork/java/javase/downloads/")); } catch (Exception ignored) { } } } System.exit(0); return; } Paths.build(); Global.loadImages(); Splash.setStatus("Loading"); final Splash splash = new Splash(); final Timer repaint = new Timer(20, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { splash.repaint(); } }); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { splash.setVisible(true); repaint.start(); } }); } catch (InterruptedException | InvocationTargetException e) { e.printStackTrace(); System.exit(0); } Updater.update(); Splash.setStatus("Loading framework"); SwingUtilities.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); Splash.setStatus("Building GUI"); new GUI(); splash.shouldDispose(true); splash.dispose(); Splash.setStatus(null); repaint.stop(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } }); }
public static void main(String[] args) { if (!Executor.hasJDKInstalled()) { final int option = JOptionPane.showConfirmDialog(null, "<html>You need to have JDK installed to run Powerbat.<br>Click 'Ok' if you would like to go to the JDK site.</html>", "JDK Required", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE); if (option == JOptionPane.OK_OPTION) { final Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(new URI("www.oracle.com/technetwork/java/javase/downloads/")); } catch (Exception ignored) { } } } System.exit(0); return; } Paths.build(); Global.loadImages(); Splash.setStatus("Loading"); final Splash splash = new Splash(); final Timer repaint = new Timer(20, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { splash.repaint(); } }); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { splash.setVisible(true); repaint.start(); } }); } catch (InterruptedException | InvocationTargetException e) { e.printStackTrace(); System.exit(0); } Updater.update(); Splash.setStatus("Loading framework"); SwingUtilities.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); Splash.setStatus("Building GUI"); new GUI(); splash.shouldDispose(true); splash.dispose(); Splash.setStatus(null); repaint.stop(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } }); }
diff --git a/mobile-svisstok-tests/src/main/java/tests/adSDK/page/LoginPage.java b/mobile-svisstok-tests/src/main/java/tests/adSDK/page/LoginPage.java index 079a464..b1e886b 100644 --- a/mobile-svisstok-tests/src/main/java/tests/adSDK/page/LoginPage.java +++ b/mobile-svisstok-tests/src/main/java/tests/adSDK/page/LoginPage.java @@ -1,52 +1,54 @@ package tests.adSDK.page; import org.apache.log4j.Logger; import org.openqa.selenium.TimeoutException; import tests.adSDK.page.exceptions.AdSDKLoadException; import tests.adSDK.page.exceptions.AdSDKToolbarException; import com.annotation.FindBy; import com.element.UIView; import com.mobile.driver.nativedriver.NativeDriver; import com.mobile.driver.page.PageFactory; import com.mobile.driver.wait.Sleeper; public class LoginPage extends BasePage{ private static final Logger LOGGER = Logger.getLogger(LoginPage.class); @FindBy(locator = "//window[1]/scrollview[1]/webview[1]/textfield[1]") private UIView loginTextfield; @FindBy(locator = "//window[1]/scrollview[1]/webview[1]/secure[1]") private UIView passwordTextfield; @FindBy(locator = "//window[1]/scrollview[1]/webview[1]/slider[1]") private UIView savePasswordSlider; @FindBy(locator = "//window[1]/scrollview[1]/webview[1]/link[1]") private UIView loginButton; @FindBy(locator = "//window[2]/toolbar[1]/button[1]") private UIView doneButton; public LoginPage(NativeDriver driver) { this.driver = driver; } public CallScreen simpleLogin(String login, String password) { + loginTextfield.touch(); loginTextfield.type(login); + passwordTextfield.touch(); passwordTextfield.type(password); savePasswordSlider.touch(); loginButton.touch(); return PageFactory.initElements(driver, CallScreen.class); } @Override public void checkPage() { loginTextfield.waitForElement(WAIT_FOR_ELEMENT_TIMEOUT); } }
false
true
public CallScreen simpleLogin(String login, String password) { loginTextfield.type(login); passwordTextfield.type(password); savePasswordSlider.touch(); loginButton.touch(); return PageFactory.initElements(driver, CallScreen.class); }
public CallScreen simpleLogin(String login, String password) { loginTextfield.touch(); loginTextfield.type(login); passwordTextfield.touch(); passwordTextfield.type(password); savePasswordSlider.touch(); loginButton.touch(); return PageFactory.initElements(driver, CallScreen.class); }
diff --git a/javafx.sdksamples/src/org/netbeans/modules/javafx/sdksamples/SDKSamplesWizardIterator.java b/javafx.sdksamples/src/org/netbeans/modules/javafx/sdksamples/SDKSamplesWizardIterator.java index c16c88e7..6ca64bf2 100644 --- a/javafx.sdksamples/src/org/netbeans/modules/javafx/sdksamples/SDKSamplesWizardIterator.java +++ b/javafx.sdksamples/src/org/netbeans/modules/javafx/sdksamples/SDKSamplesWizardIterator.java @@ -1,242 +1,243 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2008 Sun Microsystems, Inc. */ package org.netbeans.modules.javafx.sdksamples; import java.awt.Component; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.MessageFormat; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.swing.JComponent; import javax.swing.event.ChangeListener; import org.netbeans.api.project.ProjectManager; import org.netbeans.spi.project.ui.support.ProjectChooser; import org.netbeans.spi.project.ui.templates.support.Templates; import org.openide.WizardDescriptor; import org.openide.filesystems.FileLock; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.NbBundle; /** * * @author Michal Skvor */ public class SDKSamplesWizardIterator implements WizardDescriptor.InstantiatingIterator { private int index; private WizardDescriptor.Panel[] panels; private WizardDescriptor wizard; private FileObject file; public SDKSamplesWizardIterator( FileObject file ) { this.file = file; } public static SDKSamplesWizardIterator createIterator( FileObject file ) { return new SDKSamplesWizardIterator( file ); } private WizardDescriptor.Panel[] createPanels() { return new WizardDescriptor.Panel[] { new SDKSamplesWizardPanel( file ) }; } private String[] createSteps() { return new String[]{ NbBundle.getMessage( SDKSamplesWizardIterator.class, "LBL_CreateProjectStep" )}; } public Set instantiate() throws IOException { Set<FileObject> resultSet = new LinkedHashSet<FileObject>(); File dirF = FileUtil.normalizeFile((File) wizard.getProperty( "projdir" )); dirF.mkdirs(); FileObject template = Templates.getTemplate( wizard ); FileObject dir = FileUtil.toFileObject( dirF ); unZipFile( template.getInputStream(), dir, (String) wizard.getProperty( "name" ), file.getName()); resultSet.add(dir); // Look for nested projects to open as well: Enumeration<? extends FileObject> e = dir.getFolders( true ); while( e.hasMoreElements()) { FileObject subfolder = e.nextElement(); if( ProjectManager.getDefault().isProject( subfolder )) { resultSet.add(subfolder); } } File parent = dirF.getParentFile(); if( parent != null && parent.exists()) { ProjectChooser.setProjectsFolder( parent ); } return resultSet; } public void initialize(WizardDescriptor wizard) { this.wizard = wizard; index = 0; panels = createPanels(); // Make sure list of steps is accurate. String[] steps = createSteps(); for( int i = 0; i < panels.length; i++ ) { Component c = panels[i].getComponent(); if( steps[i] == null ) { // Default step name to component name of panel. // Mainly useful for getting the name of the target // chooser to appear in the list of steps. steps[i] = c.getName(); } if( c instanceof JComponent ) { // assume Swing components JComponent jc = (JComponent) c; // Step #. jc.putClientProperty( "WizardPanel_contentSelectedIndex", new Integer( i )); // Step name (actually the whole list for reference). jc.putClientProperty( "WizardPanel_contentData", steps ); } } } public void uninitialize(WizardDescriptor wizard) { this.wizard = null; } public String name() { return MessageFormat.format( "{0} of {1}", new Object[]{ new Integer(index + 1), new Integer( panels.length )}); } public boolean hasNext() { return index < panels.length - 1; } public boolean hasPrevious() { return index > 0; } public void nextPanel() { if (!hasNext()) { throw new NoSuchElementException(); } index++; } public void previousPanel() { if (!hasPrevious()) { throw new NoSuchElementException(); } index--; } public WizardDescriptor.Panel current() { return panels[index]; } public void addChangeListener(ChangeListener l) { } public void removeChangeListener(ChangeListener l) { } private static void unZipFile( InputStream source, FileObject projectRoot, String name, String filename ) throws IOException { try { ZipInputStream str = new ZipInputStream(source); ZipEntry entry; // Get root entry String rootFileName = ""; ZipEntry root = str.getNextEntry(); if( root.isDirectory()) { rootFileName = root.getName(); } if( rootFileName == null ) return; while(( entry = str.getNextEntry()) != null ) { if( entry.isDirectory()) { if( entry.getName().equals( filename )) continue; FileUtil.createFolder( projectRoot, entry.getName().substring( rootFileName.length())); - } else if( entry.getName().toLowerCase().endsWith( ".png" )){ - FileObject fo = FileUtil.createData( projectRoot, entry.getName().substring( filename.length())); + } else if( entry.getName().toLowerCase().endsWith( ".png" ) || entry.getName().toLowerCase().endsWith( ".jpg" ) || + entry.getName().toLowerCase().endsWith( ".gif" )) { + FileObject fo = FileUtil.createData( projectRoot, entry.getName().substring( rootFileName.length())); FileLock lock = fo.lock(); try { OutputStream out = fo.getOutputStream(lock); try { FileUtil.copy(str, out); } finally { out.close(); } } finally { lock.releaseLock(); } } else { FileObject fo = FileUtil.createData(projectRoot, entry.getName().substring( rootFileName.length())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtil.copy(str, baos); String content = baos.toString( "UTF-8" ). // replaceAll("\n|\r|\r\n", System.getProperty("line.separator")). replaceAll( "@NAME@", name ); FileLock lock = fo.lock(); try { OutputStream out = fo.getOutputStream( lock ); try { FileUtil.copy( new ByteArrayInputStream( content.getBytes( "UTF-8" )), out ); } finally { out.close(); } } finally { lock.releaseLock(); } } } } finally { source.close(); } } }
true
true
private static void unZipFile( InputStream source, FileObject projectRoot, String name, String filename ) throws IOException { try { ZipInputStream str = new ZipInputStream(source); ZipEntry entry; // Get root entry String rootFileName = ""; ZipEntry root = str.getNextEntry(); if( root.isDirectory()) { rootFileName = root.getName(); } if( rootFileName == null ) return; while(( entry = str.getNextEntry()) != null ) { if( entry.isDirectory()) { if( entry.getName().equals( filename )) continue; FileUtil.createFolder( projectRoot, entry.getName().substring( rootFileName.length())); } else if( entry.getName().toLowerCase().endsWith( ".png" )){ FileObject fo = FileUtil.createData( projectRoot, entry.getName().substring( filename.length())); FileLock lock = fo.lock(); try { OutputStream out = fo.getOutputStream(lock); try { FileUtil.copy(str, out); } finally { out.close(); } } finally { lock.releaseLock(); } } else { FileObject fo = FileUtil.createData(projectRoot, entry.getName().substring( rootFileName.length())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtil.copy(str, baos); String content = baos.toString( "UTF-8" ). // replaceAll("\n|\r|\r\n", System.getProperty("line.separator")). replaceAll( "@NAME@", name ); FileLock lock = fo.lock(); try { OutputStream out = fo.getOutputStream( lock ); try { FileUtil.copy( new ByteArrayInputStream( content.getBytes( "UTF-8" )), out ); } finally { out.close(); } } finally { lock.releaseLock(); } } } } finally { source.close(); } }
private static void unZipFile( InputStream source, FileObject projectRoot, String name, String filename ) throws IOException { try { ZipInputStream str = new ZipInputStream(source); ZipEntry entry; // Get root entry String rootFileName = ""; ZipEntry root = str.getNextEntry(); if( root.isDirectory()) { rootFileName = root.getName(); } if( rootFileName == null ) return; while(( entry = str.getNextEntry()) != null ) { if( entry.isDirectory()) { if( entry.getName().equals( filename )) continue; FileUtil.createFolder( projectRoot, entry.getName().substring( rootFileName.length())); } else if( entry.getName().toLowerCase().endsWith( ".png" ) || entry.getName().toLowerCase().endsWith( ".jpg" ) || entry.getName().toLowerCase().endsWith( ".gif" )) { FileObject fo = FileUtil.createData( projectRoot, entry.getName().substring( rootFileName.length())); FileLock lock = fo.lock(); try { OutputStream out = fo.getOutputStream(lock); try { FileUtil.copy(str, out); } finally { out.close(); } } finally { lock.releaseLock(); } } else { FileObject fo = FileUtil.createData(projectRoot, entry.getName().substring( rootFileName.length())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtil.copy(str, baos); String content = baos.toString( "UTF-8" ). // replaceAll("\n|\r|\r\n", System.getProperty("line.separator")). replaceAll( "@NAME@", name ); FileLock lock = fo.lock(); try { OutputStream out = fo.getOutputStream( lock ); try { FileUtil.copy( new ByteArrayInputStream( content.getBytes( "UTF-8" )), out ); } finally { out.close(); } } finally { lock.releaseLock(); } } } } finally { source.close(); } }
diff --git a/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java b/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java index 4de854f9..c53f481a 100644 --- a/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java +++ b/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java @@ -1,238 +1,250 @@ /* * Copyright 2007 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.zxing.qrcode.decoder; import com.google.zxing.ReaderException; import java.io.UnsupportedEncodingException; /** * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes * in one QR Code. This class decodes the bits back into text.</p> * * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p> * * @author [email protected] (Sean Owen) */ final class DecodedBitStreamParser { /** * See ISO 18004:2006, 6.4.4 Table 5 */ private static final char[] ALPHANUMERIC_CHARS = new char[]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' }; private static final String SHIFT_JIS = "Shift_JIS"; private static final boolean ASSUME_SHIFT_JIS; private static final String UTF8 = "UTF-8"; private static final String ISO88591 = "ISO-8859-1"; static { String platformDefault = System.getProperty("file.encoding"); ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(platformDefault) || "EUC-JP".equalsIgnoreCase(platformDefault); } private DecodedBitStreamParser() { } static String decode(byte[] bytes, Version version) throws ReaderException { BitSource bits = new BitSource(bytes); StringBuffer result = new StringBuffer(); Mode mode; do { // While still another segment to read... mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits if (!mode.equals(Mode.TERMINATOR)) { // How many characters will follow, encoded in this mode? int count = bits.readBits(mode.getCharacterCountBits(version)); if (mode.equals(Mode.NUMERIC)) { decodeNumericSegment(bits, result, count); } else if (mode.equals(Mode.ALPHANUMERIC)) { decodeAlphanumericSegment(bits, result, count); } else if (mode.equals(Mode.BYTE)) { decodeByteSegment(bits, result, count); } else if (mode.equals(Mode.KANJI)) { decodeKanjiSegment(bits, result, count); } else { throw new ReaderException("Unsupported mode indicator"); } } } while (!mode.equals(Mode.TERMINATOR)); // I thought it wasn't allowed to leave extra bytes after the terminator but it happens /* int bitsLeft = bits.available(); if (bitsLeft > 0) { if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) { throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator"); } } */ return result.toString(); } private static void decodeKanjiSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { // Each character will require 2 bytes. Read the characters as 2-byte pairs // and decode as Shift_JIS afterwards byte[] buffer = new byte[2 * count]; int offset = 0; while (count > 0) { // Each 13 bits encodes a 2-byte character int twoBytes = bits.readBits(13); int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0); if (assembledTwoBytes < 0x01F00) { // In the 0x8140 to 0x9FFC range assembledTwoBytes += 0x08140; } else { // In the 0xE040 to 0xEBBF range assembledTwoBytes += 0x0C140; } buffer[offset] = (byte) (assembledTwoBytes >> 8); buffer[offset + 1] = (byte) assembledTwoBytes; offset += 2; count--; } // Shift_JIS may not be supported in some environments: try { result.append(new String(buffer, SHIFT_JIS)); } catch (UnsupportedEncodingException uee) { throw new ReaderException(SHIFT_JIS + " encoding is not supported on this device"); } } private static void decodeByteSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { byte[] readBytes = new byte[count]; if (count << 3 > bits.available()) { throw new ReaderException("Count too large: " + count); } for (int i = 0; i < count; i++) { readBytes[i] = (byte) bits.readBits(8); } // The spec isn't clear on this mode; see // section 6.4.5: t does not say which encoding to assuming // upon decoding. I have seen ISO-8859-1 used as well as // Shift_JIS -- without anything like an ECI designator to // give a hint. String encoding = guessEncoding(readBytes); try { result.append(new String(readBytes, encoding)); } catch (UnsupportedEncodingException uce) { throw new ReaderException(uce.toString()); } } private static void decodeAlphanumericSegment(BitSource bits, StringBuffer result, int count) { // Read two characters at a time while (count > 1) { int nextTwoCharsBits = bits.readBits(11); result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]); result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]); count -= 2; } if (count == 1) { // special case: one character left result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]); } } private static void decodeNumericSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { // Read three digits at a time while (count >= 3) { // Each 10 bits encodes three digits int threeDigitsBits = bits.readBits(10); if (threeDigitsBits >= 1000) { throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits); } result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]); result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]); result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]); count -= 3; } if (count == 2) { // Two digits left over to read, encoded in 7 bits int twoDigitsBits = bits.readBits(7); if (twoDigitsBits >= 100) { throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits); } result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]); result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]); } else if (count == 1) { // One digit left over to read int digitBits = bits.readBits(4); if (digitBits >= 10) { throw new ReaderException("Illegal value for digit unit: " + digitBits); } result.append(ALPHANUMERIC_CHARS[digitBits]); } } private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; boolean canBeISO88591 = true; + boolean lastWasPossibleDoubleByteStart = false; for (int i = 0; i < length; i++) { int value = bytes[i] & 0xFF; if (value >= 0x80 && value <= 0x9F && i < length - 1) { canBeISO88591 = false; // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS, // just double check that it is followed by a byte that's valid in // the Shift_JIS encoding - int nextValue = bytes[i + 1] & 0xFF; - if ((value & 0x1) == 0) { - // if even, next value should be in [0x9F,0xFC] - // if not, we'll guess UTF-8 - if (nextValue < 0x9F || nextValue > 0xFC) { - return UTF8; - } + if (lastWasPossibleDoubleByteStart) { + // If we just checked this and the last byte for being a valid double-byte + // char, don't check starting on this byte. If the this and the last byte + // formed a valid pair, then this shouldn't be checked to see if it starts + // a double byte pair of course. + lastWasPossibleDoubleByteStart = false; } else { - // if odd, next value should be in [0x40,0x9E] - // if not, we'll guess UTF-8 - if (nextValue < 0x40 || nextValue > 0x9E) { - return UTF8; + // ... otherwise do check to see if this plus the next byte form a valid + // double byte pair encoding a character. + lastWasPossibleDoubleByteStart = true; + int nextValue = bytes[i + 1] & 0xFF; + if ((value & 0x1) == 0) { + // if even, next value should be in [0x9F,0xFC] + // if not, we'll guess UTF-8 + if (nextValue < 0x9F || nextValue > 0xFC) { + return UTF8; + } + } else { + // if odd, next value should be in [0x40,0x9E] + // if not, we'll guess UTF-8 + if (nextValue < 0x40 || nextValue > 0x9E) { + return UTF8; + } } } } } return canBeISO88591 ? ISO88591 : SHIFT_JIS; } }
false
true
private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; boolean canBeISO88591 = true; for (int i = 0; i < length; i++) { int value = bytes[i] & 0xFF; if (value >= 0x80 && value <= 0x9F && i < length - 1) { canBeISO88591 = false; // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS, // just double check that it is followed by a byte that's valid in // the Shift_JIS encoding int nextValue = bytes[i + 1] & 0xFF; if ((value & 0x1) == 0) { // if even, next value should be in [0x9F,0xFC] // if not, we'll guess UTF-8 if (nextValue < 0x9F || nextValue > 0xFC) { return UTF8; } } else { // if odd, next value should be in [0x40,0x9E] // if not, we'll guess UTF-8 if (nextValue < 0x40 || nextValue > 0x9E) { return UTF8; } } } } return canBeISO88591 ? ISO88591 : SHIFT_JIS; }
private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; boolean canBeISO88591 = true; boolean lastWasPossibleDoubleByteStart = false; for (int i = 0; i < length; i++) { int value = bytes[i] & 0xFF; if (value >= 0x80 && value <= 0x9F && i < length - 1) { canBeISO88591 = false; // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS, // just double check that it is followed by a byte that's valid in // the Shift_JIS encoding if (lastWasPossibleDoubleByteStart) { // If we just checked this and the last byte for being a valid double-byte // char, don't check starting on this byte. If the this and the last byte // formed a valid pair, then this shouldn't be checked to see if it starts // a double byte pair of course. lastWasPossibleDoubleByteStart = false; } else { // ... otherwise do check to see if this plus the next byte form a valid // double byte pair encoding a character. lastWasPossibleDoubleByteStart = true; int nextValue = bytes[i + 1] & 0xFF; if ((value & 0x1) == 0) { // if even, next value should be in [0x9F,0xFC] // if not, we'll guess UTF-8 if (nextValue < 0x9F || nextValue > 0xFC) { return UTF8; } } else { // if odd, next value should be in [0x40,0x9E] // if not, we'll guess UTF-8 if (nextValue < 0x40 || nextValue > 0x9E) { return UTF8; } } } } } return canBeISO88591 ? ISO88591 : SHIFT_JIS; }
diff --git a/ThemeCreative/src/syam/ThemeCreative/Command/HelpCommand.java b/ThemeCreative/src/syam/ThemeCreative/Command/HelpCommand.java index 20896e7..c92bb86 100644 --- a/ThemeCreative/src/syam/ThemeCreative/Command/HelpCommand.java +++ b/ThemeCreative/src/syam/ThemeCreative/Command/HelpCommand.java @@ -1,35 +1,35 @@ package syam.ThemeCreative.Command; import syam.ThemeCreative.ThemeCreative; import syam.ThemeCreative.Util.Actions; public class HelpCommand extends BaseCommand{ public HelpCommand(){ bePlayer = false; name = "help"; argLength = 0; usage = "<- show command help"; } @Override public boolean execute() { Actions.message(sender, null, "&c==================================="); - Actions.message(sender, null, "&bFlagGame Plugin version &3%version &bby syamn"); + Actions.message(sender, null, "&bThemeCreative Plugin version &3%version &bby syamn"); Actions.message(sender, null, " &b<>&f = required, &b[]&f = optional"); // 全コマンドをループで表示 for (BaseCommand cmd : ThemeCreative.commands.toArray(new BaseCommand[0])){ cmd.sender = this.sender; if (cmd.permission()){ Actions.message(sender, null, "&8-&7 /"+command+" &c" + cmd.name + " &7" + cmd.usage); } } Actions.message(sender, null, "&c==================================="); return true; } @Override public boolean permission() { return true; } }
true
true
public boolean execute() { Actions.message(sender, null, "&c==================================="); Actions.message(sender, null, "&bFlagGame Plugin version &3%version &bby syamn"); Actions.message(sender, null, " &b<>&f = required, &b[]&f = optional"); // 全コマンドをループで表示 for (BaseCommand cmd : ThemeCreative.commands.toArray(new BaseCommand[0])){ cmd.sender = this.sender; if (cmd.permission()){ Actions.message(sender, null, "&8-&7 /"+command+" &c" + cmd.name + " &7" + cmd.usage); } } Actions.message(sender, null, "&c==================================="); return true; }
public boolean execute() { Actions.message(sender, null, "&c==================================="); Actions.message(sender, null, "&bThemeCreative Plugin version &3%version &bby syamn"); Actions.message(sender, null, " &b<>&f = required, &b[]&f = optional"); // 全コマンドをループで表示 for (BaseCommand cmd : ThemeCreative.commands.toArray(new BaseCommand[0])){ cmd.sender = this.sender; if (cmd.permission()){ Actions.message(sender, null, "&8-&7 /"+command+" &c" + cmd.name + " &7" + cmd.usage); } } Actions.message(sender, null, "&c==================================="); return true; }
diff --git a/glimpse-server/src/main/java/br/com/tecsinapse/glimpse/server/groovy/GroovyRepl.java b/glimpse-server/src/main/java/br/com/tecsinapse/glimpse/server/groovy/GroovyRepl.java index 7b41fb0..2fe4b15 100644 --- a/glimpse-server/src/main/java/br/com/tecsinapse/glimpse/server/groovy/GroovyRepl.java +++ b/glimpse-server/src/main/java/br/com/tecsinapse/glimpse/server/groovy/GroovyRepl.java @@ -1,26 +1,29 @@ package br.com.tecsinapse.glimpse.server.groovy; import groovy.lang.GroovyShell; import br.com.tecsinapse.glimpse.server.Repl; public class GroovyRepl implements Repl { private GroovyShell groovyShell = new GroovyShell(); public GroovyRepl(VarProducer varProducer) { varProducer.fill(groovyShell); } public String eval(String expression) { try { Object result = groovyShell.evaluate(expression); - return result.toString(); + if (result == null) + return "null"; + else + return result.toString(); } catch (RuntimeException e) { return e.getMessage(); } } public void close() { } }
true
true
public String eval(String expression) { try { Object result = groovyShell.evaluate(expression); return result.toString(); } catch (RuntimeException e) { return e.getMessage(); } }
public String eval(String expression) { try { Object result = groovyShell.evaluate(expression); if (result == null) return "null"; else return result.toString(); } catch (RuntimeException e) { return e.getMessage(); } }
diff --git a/java/com/delcyon/capo/xml/cdom/CElement.java b/java/com/delcyon/capo/xml/cdom/CElement.java index 6391f04..613a323 100644 --- a/java/com/delcyon/capo/xml/cdom/CElement.java +++ b/java/com/delcyon/capo/xml/cdom/CElement.java @@ -1,347 +1,350 @@ /** Copyright (c) 2012 Delcyon, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package com.delcyon.capo.xml.cdom; import java.lang.reflect.Modifier; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.TypeInfo; import com.delcyon.capo.controller.elements.ResourceControlElement.Attributes; import com.delcyon.capo.resourcemanager.ResourceDescriptor.LifeCycle; import com.delcyon.capo.util.EqualityProcessor; import com.delcyon.capo.util.ToStringControl; import com.delcyon.capo.util.ToStringControl.Control; import com.delcyon.capo.xml.cdom.CDOMEvent.EventType; /** * @author jeremiah * */ @ToStringControl(control=Control.exclude,modifiers=Modifier.STATIC+Modifier.FINAL) public class CElement extends CNode implements Element { @SuppressWarnings("unused") protected CElement(){}; //reflection public CElement(String localName) { setNodeName(localName); } public CElement(String namespaceURI,String qName) { setNamespaceURI(namespaceURI); setNodeName(qName); } public CElement(String namespaceURI,String prefix,String localName) { setNamespaceURI(namespaceURI); setNodeName(prefix+":"+localName); } @Override public short getNodeType() { return Node.ELEMENT_NODE; } /* (non-Javadoc) * @see org.w3c.dom.Element#getTagName() */ @Override public String getTagName() { return getNodeName(); } /* (non-Javadoc) * @see org.w3c.dom.Element#getAttribute(java.lang.String) */ @Override public String getAttribute(String name) { if (getAttributes().getNamedItem(name) == null) { return ""; } else { return getAttributes().getNamedItem(name).getNodeValue(); } } /* (non-Javadoc) * @see org.w3c.dom.Element#setAttribute(java.lang.String, java.lang.String) */ @SuppressWarnings("unchecked") @Override public void setAttribute(String name, String value) throws DOMException { ((CNamedNodeMap) getAttributes()).setNamedItemNS(new CAttr(this, null, name, value)); cascadeDOMEvent(prepareEvent(EventType.UPDATE, this)); } /* (non-Javadoc) * @see org.w3c.dom.Element#removeAttribute(java.lang.String) */ @Override public void removeAttribute(String name) throws DOMException { getAttributes().removeNamedItem(name); cascadeDOMEvent(prepareEvent(EventType.UPDATE, this)); } /* (non-Javadoc) * @see org.w3c.dom.Element#getAttributeNode(java.lang.String) */ @Override public Attr getAttributeNode(String name) { return (Attr) getAttributes().getNamedItem(name); } /* (non-Javadoc) * @see org.w3c.dom.Element#setAttributeNode(org.w3c.dom.Attr) */ @Override public Attr setAttributeNode(Attr newAttr) throws DOMException { getAttributes().setNamedItem(newAttr); cascadeDOMEvent(prepareEvent(EventType.UPDATE, this)); return newAttr; } /* (non-Javadoc) * @see org.w3c.dom.Element#removeAttributeNode(org.w3c.dom.Attr) */ @Override public Attr removeAttributeNode(Attr oldAttr) throws DOMException { CNamedNodeMap namedNodeMap = (CNamedNodeMap) getAttributes(); for (int index = 0; index < namedNodeMap.getLength(); index++) { if(namedNodeMap.get(index).equals(oldAttr)) { cascadeDOMEvent(prepareEvent(EventType.UPDATE, this)); return (Attr) namedNodeMap.remove(index); } } return null; } /* (non-Javadoc) * @see org.w3c.dom.Element#getElementsByTagName(java.lang.String) */ @Override public NodeList getElementsByTagName(final String name) { final CNodeList nodeList = new CNodeList(); NodeProcessor nodeProcessor = new NodeProcessor() { @Override public void process(Node parentNode,Node node) throws Exception { if(node instanceof Element) { if(name.equals("*")) { nodeList.add(node); } else { - ((Element) node).getTagName().equals(name); + if(((Element) node).getTagName().equals(name) == true) + { + nodeList.add(node); + } } } } }; try { CNode.walkTree(null,this, nodeProcessor, true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return nodeList; } /* (non-Javadoc) * @see org.w3c.dom.Element#getAttributeNS(java.lang.String, java.lang.String) */ @Override public String getAttributeNS(String namespaceURI, String localName) throws DOMException { if(hasAttributeNS(namespaceURI, localName)) { return getAttributes().getNamedItemNS(namespaceURI, localName).getNodeValue(); } else { return ""; } } /* (non-Javadoc) * @see org.w3c.dom.Element#setAttributeNS(java.lang.String, java.lang.String, java.lang.String) */ @SuppressWarnings("unchecked") @Override public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException { ((CNamedNodeMap) getAttributes()).setNamedItemNS(new CAttr(this, namespaceURI, qualifiedName, value)); cascadeDOMEvent(prepareEvent(EventType.UPDATE, this)); } /* (non-Javadoc) * @see org.w3c.dom.Element#removeAttributeNS(java.lang.String, java.lang.String) */ @Override public void removeAttributeNS(String namespaceURI, String localName) throws DOMException { CNamedNodeMap namedNodeMap = (CNamedNodeMap) getAttributes(); for(int index = 0; index < namedNodeMap.getLength(); index++) { CAttr attr = (CAttr) namedNodeMap.get(index); if(EqualityProcessor.areSame(attr.getNamespaceURI(), namespaceURI) && localName.equals(attr.getLocalName())) { namedNodeMap.remove(index); cascadeDOMEvent(prepareEvent(EventType.UPDATE, this)); return; } } } /* (non-Javadoc) * @see org.w3c.dom.Element#getAttributeNodeNS(java.lang.String, java.lang.String) */ @Override public Attr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException { CNamedNodeMap namedNodeMap = (CNamedNodeMap) getAttributes(); for(int index = 0; index < namedNodeMap.getLength(); index++) { CAttr attr = (CAttr) namedNodeMap.get(index); if(EqualityProcessor.areSame(attr.getNamespaceURI(), namespaceURI) && localName.equals(attr.getLocalName())) { return attr; } } return null; } /* (non-Javadoc) * @see org.w3c.dom.Element#setAttributeNodeNS(org.w3c.dom.Attr) */ @Override public Attr setAttributeNodeNS(Attr newAttr) throws DOMException { Attr attr = (Attr) getAttributes().setNamedItemNS(newAttr); cascadeDOMEvent(prepareEvent(EventType.UPDATE, this)); return attr; } /* (non-Javadoc) * @see org.w3c.dom.Element#getElementsByTagNameNS(java.lang.String, java.lang.String) */ @Override public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException { Thread.dumpStack(); throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.w3c.dom.Element#hasAttribute(java.lang.String) */ @Override public boolean hasAttribute(String name) { return getAttributes().getNamedItem(name) != null; } /* (non-Javadoc) * @see org.w3c.dom.Element#hasAttributeNS(java.lang.String, java.lang.String) */ @Override public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException { return getAttributes().getNamedItemNS(namespaceURI, localName) != null; } /* (non-Javadoc) * @see org.w3c.dom.Element#getSchemaTypeInfo() */ @Override public TypeInfo getSchemaTypeInfo() { Thread.dumpStack(); throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.w3c.dom.Element#setIdAttribute(java.lang.String, boolean) */ @Override public void setIdAttribute(String name, boolean isId) throws DOMException { // TODO Auto-generated method stub Thread.dumpStack(); throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.w3c.dom.Element#setIdAttributeNS(java.lang.String, java.lang.String, boolean) */ @Override public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException { // TODO Auto-generated method stub Thread.dumpStack(); throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.w3c.dom.Element#setIdAttributeNode(org.w3c.dom.Attr, boolean) */ @Override public void setIdAttributeNode(Attr idAttr, boolean isId) throws DOMException { // TODO Auto-generated method stub Thread.dumpStack(); throw new UnsupportedOperationException(); } public void setAttribute(Enum name, Enum value) { setAttribute(name.toString(), value.toString()); } }
true
true
public NodeList getElementsByTagName(final String name) { final CNodeList nodeList = new CNodeList(); NodeProcessor nodeProcessor = new NodeProcessor() { @Override public void process(Node parentNode,Node node) throws Exception { if(node instanceof Element) { if(name.equals("*")) { nodeList.add(node); } else { ((Element) node).getTagName().equals(name); } } } }; try { CNode.walkTree(null,this, nodeProcessor, true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return nodeList; }
public NodeList getElementsByTagName(final String name) { final CNodeList nodeList = new CNodeList(); NodeProcessor nodeProcessor = new NodeProcessor() { @Override public void process(Node parentNode,Node node) throws Exception { if(node instanceof Element) { if(name.equals("*")) { nodeList.add(node); } else { if(((Element) node).getTagName().equals(name) == true) { nodeList.add(node); } } } } }; try { CNode.walkTree(null,this, nodeProcessor, true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return nodeList; }
diff --git a/src/main/java/org/mvel/optimizers/impl/asm/ASMAccessorCompiler.java b/src/main/java/org/mvel/optimizers/impl/asm/ASMAccessorCompiler.java index f3d5ee12..4075e497 100644 --- a/src/main/java/org/mvel/optimizers/impl/asm/ASMAccessorCompiler.java +++ b/src/main/java/org/mvel/optimizers/impl/asm/ASMAccessorCompiler.java @@ -1,956 +1,955 @@ package org.mvel.optimizers.impl.asm; import org.mvel.*; import org.mvel.integration.VariableResolverFactory; import org.mvel.optimizers.AccessorCompiler; import org.mvel.optimizers.ExecutableStatement; import org.mvel.optimizers.OptimizationNotSupported; import org.mvel.util.ParseTools; import org.mvel.util.PropertyTools; import org.mvel.util.StringAppender; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import static org.objectweb.asm.Opcodes.*; import static org.objectweb.asm.Type.*; import java.lang.reflect.*; import java.util.*; public class ASMAccessorCompiler implements AccessorCompiler { private static final int OPCODES_VERSION; static { String javaVersion = System.getProperty("java.version"); if (javaVersion.startsWith("1.4")) OPCODES_VERSION = Opcodes.V1_4; else if (javaVersion.startsWith("1.5")) OPCODES_VERSION = Opcodes.V1_5; else if (javaVersion.startsWith("1.6") || javaVersion.startsWith("1.7")) OPCODES_VERSION = Opcodes.V1_6; else OPCODES_VERSION = Opcodes.V1_2; } private int start = 0; private int cursor = 0; private char[] property; private int length; private Object ctx; private Object thisRef; private VariableResolverFactory variableFactory; private static final int DONE = -1; private static final int BEAN = 0; private static final int METH = 1; private static final int COL = 2; private static final Object[] EMPTYARG = new Object[0]; private boolean first = true; private String className; private ClassWriter cw; private MethodVisitor mv; private Object val; private int stacksize = 1; private long time; private int inputs; private ArrayList<ExecutableStatement> compiledInputs; private Class returnType; public ASMAccessorCompiler(char[] property, Object ctx, Object thisRef, VariableResolverFactory variableResolverFactory) { this.property = property; this.ctx = ctx; this.variableFactory = variableResolverFactory; this.thisRef = thisRef; } public ASMAccessorCompiler() { } public Accessor compile(char[] property, Object staticContext, Object thisRef, VariableResolverFactory factory, boolean root) { time = System.currentTimeMillis(); inputs = 0; compiledInputs = new ArrayList<ExecutableStatement>(); start = cursor = 0; this.first = true; this.val = null; this.length = property.length; this.property = property; this.ctx = staticContext; this.thisRef = thisRef; this.variableFactory = factory; cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); cw.visit(OPCODES_VERSION, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, className = "ASMAccessorImpl_" + String.valueOf(cw.hashCode()).replaceAll("\\-", "_"), null, "java/lang/Object", new String[]{"org/mvel/Accessor"}); MethodVisitor m = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); m.visitCode(); m.visitVarInsn(Opcodes.ALOAD, 0); m.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); m.visitInsn(Opcodes.RETURN); m.visitMaxs(1, 1); m.visitEnd(); mv = cw.visitMethod(ACC_PUBLIC, "getValue", "(Ljava/lang/Object;Ljava/lang/Object;Lorg/mvel/integration/VariableResolverFactory;)Ljava/lang/Object;", null, null); mv.visitCode(); return compileAccessor(); } public Accessor compileAccessor() { debug("\n{Initiate Compile: " + new String(property) + "}\n"); Object curr = ctx; try { while (cursor < length) { switch (nextToken()) { case BEAN: curr = getBeanProperty(curr, capture()); break; case METH: curr = getMethod(curr, capture()); break; case COL: curr = getCollectionProperty(curr, capture()); break; case DONE: break; } first = false; } val = curr; if (returnType != null && returnType.isPrimitive()) { //noinspection unchecked wrapPrimitive(returnType); } if (returnType == void.class) { debug("ACONST_NULL"); mv.visitInsn(ACONST_NULL); } debug("ARETURN"); mv.visitInsn(ARETURN); debug("\n{METHOD STATS (maxstack=" + stacksize + ")}\n"); mv.visitMaxs(stacksize, 1); mv.visitEnd(); buildInputs(); cw.visitEnd(); Class cls = loadClass(cw.toByteArray()); debug("[MVEL JIT Completed Optimization <<" + new String(property) + ">>]::" + cls + " (time: " + (System.currentTimeMillis() - time) + "ms)"); Accessor a; if (inputs == 0) { a = (Accessor) cls.newInstance(); } else { Class[] parms = new Class[inputs]; for (int i = 0; i < inputs; i++) { parms[i] = ExecutableStatement.class; } a = (Accessor) cls.getConstructor(parms).newInstance(compiledInputs.toArray(new ExecutableStatement[compiledInputs.size()])); } debug("[MVEL JIT Test Output: " + a.getValue(ctx, thisRef, variableFactory) + "]"); return a; } catch (InvocationTargetException e) { throw new PropertyAccessException("could not access property", e); } catch (IllegalAccessException e) { throw new PropertyAccessException("could not access property", e); } catch (IndexOutOfBoundsException e) { throw new PropertyAccessException("array or collection index out of bounds (property: " + new String(property) + ")", e); } catch (PropertyAccessException e) { throw new PropertyAccessException("failed to access property: <<" + new String(property) + ">> in: " + (ctx != null ? ctx.getClass() : null), e); } catch (CompileException e) { throw e; } catch (NullPointerException e) { throw new PropertyAccessException("null pointer exception in property: " + new String(property), e); } catch (OptimizationNotSupported e) { throw e; } catch (Exception e) { throw new PropertyAccessException("unknown exception in expression: " + new String(property), e); } } private int nextToken() { switch (property[start = cursor]) { case'[': return COL; case'.': cursor = ++start; } //noinspection StatementWithEmptyBody while (++cursor < length && Character.isJavaIdentifierPart(property[cursor])) ; if (cursor < length) { switch (property[cursor]) { case'[': return COL; case'(': return METH; default: return 0; } } return 0; } private String capture() { return new String(property, start, cursor - start); } private Object getBeanProperty(Object ctx, String property) throws IllegalAccessException, InvocationTargetException { debug("{bean: " + property + "}"); Class cls = (ctx instanceof Class ? ((Class) ctx) : ctx != null ? ctx.getClass() : null); Member member = cls != null ? PropertyTools.getFieldOrAccessor(cls, property) : null; if (first && variableFactory != null && variableFactory.isResolveable(property)) { try { debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); debug("LDC :" + property); mv.visitLdcInsn(property); debug("INVOKEINTERFACE org/mvel/integration/VariableResolverFactory.getVariableResolver"); mv.visitMethodInsn(INVOKEINTERFACE, "org/mvel/integration/VariableResolverFactory", "getVariableResolver", "(Ljava/lang/String;)Lorg/mvel/integration/VariableResolver;"); debug("INVOKEINTERFACE org/mvel/integration/VariableResolver.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, "org/mvel/integration/VariableResolver", "getValue", "()Ljava/lang/Object;"); } catch (Exception e) { throw new OptimizationFailure("critical error in JIT", e); } return variableFactory.getVariableResolver(property).getValue(); } else if (member instanceof Field) { Object o = ((Field) member).get(ctx); if (first) { debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); } debug("CHECKCAST " + getInternalName(cls)); mv.visitTypeInsn(CHECKCAST, getInternalName(cls)); debug("GETFIELD " + property + ":" + getDescriptor(((Field) member).getType())); mv.visitFieldInsn(GETFIELD, getInternalName(cls), property, getDescriptor(((Field) member).getType())); // addAccessorComponent(cls, property, FIELD, ((Field) member).getType()); return o; } else if (member != null) { if (first) { debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); } debug("CHECKCAST " + getInternalName(member.getDeclaringClass())); mv.visitTypeInsn(CHECKCAST, getInternalName(member.getDeclaringClass())); returnType = ((Method) member).getReturnType(); debug("INVOKEVIRTUAL " + member.getName() + ":" + returnType); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(member.getDeclaringClass()), member.getName(), getMethodDescriptor((Method) member)); stacksize++; return ((Method) member).invoke(ctx, EMPTYARG); } else if (ctx instanceof Map && ((Map) ctx).containsKey(property)) { debug("CHECKCAST java/util/Map"); mv.visitTypeInsn(CHECKCAST, "java/util/Map"); debug("LDC: \"" + property + "\""); mv.visitLdcInsn(property); debug("INVOKEINTERFACE: get"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); return ((Map) ctx).get(property); } else if ("this".equals(property)) { debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); // load the thisRef value. return this.thisRef; } else if (Token.LITERALS.containsKey(property)) { return Token.LITERALS.get(property); } else { Class tryStaticMethodRef = tryStaticAccess(); if (tryStaticMethodRef != null) { throw new OptimizationNotSupported("class literal: " + tryStaticMethodRef); } else throw new PropertyAccessException("could not access property (" + property + ")"); } } private void whiteSpaceSkip() { if (cursor < length) //noinspection StatementWithEmptyBody while (Character.isWhitespace(property[cursor]) && ++cursor < length) ; } private boolean scanTo(char c) { for (; cursor < length; cursor++) { if (property[cursor] == c) { return true; } } return false; } private int containsStringLiteralTermination() { int pos = cursor; for (pos--; pos > 0; pos--) { if (property[pos] == '\'' || property[pos] == '"') return pos; else if (!Character.isWhitespace(property[pos])) return pos; } return -1; } /** * Handle accessing a property embedded in a collection, map, or array * * @param ctx - * @param prop - * @return - * @throws Exception - */ private Object getCollectionProperty(Object ctx, String prop) throws Exception { if (prop.length() > 0) ctx = getBeanProperty(ctx, prop); debug("{collection: " + prop + "} ctx=" + ctx); int start = ++cursor; whiteSpaceSkip(); if (cursor == length) throw new PropertyAccessException("unterminated '['"); String item; if (property[cursor] == '\'' || property[cursor] == '"') { start++; int end; if (!scanTo(']')) throw new PropertyAccessException("unterminated '['"); if ((end = containsStringLiteralTermination()) == -1) throw new PropertyAccessException("unterminated string literal in collection accessor"); item = new String(property, start, end - start); } else { if (!scanTo(']')) throw new PropertyAccessException("unterminated '['"); item = new String(property, start, cursor - start); } ++cursor; if (ctx instanceof Map) { debug("CHECKCAST java/util/Map"); mv.visitTypeInsn(CHECKCAST, "java/util/Map"); debug("LDC: \"" + item + "\""); mv.visitLdcInsn(item); debug("INVOKEINTERFACE: get"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); return ((Map) ctx).get(item); } else if (ctx instanceof List) { int index = Integer.parseInt(item); debug("CHECKCAST java/util/List"); mv.visitTypeInsn(CHECKCAST, "java/util/List"); debug("BIGPUSH: " + 6); mv.visitIntInsn(BIPUSH, index); debug("INVOKEINTERFACE: java/util/List.get"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;"); return ((List) ctx).get(index); } else if (ctx instanceof Collection) { int count = Integer.parseInt(item); if (count > ((Collection) ctx).size()) throw new PropertyAccessException("index [" + count + "] out of bounds on collection"); Iterator iter = ((Collection) ctx).iterator(); for (int i = 0; i < count; i++) iter.next(); return iter.next(); } else if (ctx instanceof Object[]) { int index = Integer.parseInt(item); debug("CHECKCAST [Ljava/lang/Object;"); mv.visitTypeInsn(CHECKCAST, "[Ljava/lang/Object;"); if (index < 6) { switch (index) { case 0: debug("ICONST_0"); mv.visitInsn(ICONST_0); break; case 1: debug("ICONST_1"); mv.visitInsn(ICONST_1); break; case 2: debug("ICONST_2"); mv.visitInsn(ICONST_2); break; case 3: debug("ICONST_3"); mv.visitInsn(ICONST_3); break; case 4: debug("ICONST_4"); mv.visitInsn(ICONST_4); break; case 5: debug("ICONST_5"); mv.visitInsn(ICONST_5); break; } } else { debug("BIPUSH " + index); mv.visitIntInsn(BIPUSH, index); } mv.visitInsn(AALOAD); return ((Object[]) ctx)[index]; } else if (ctx instanceof CharSequence) { int index = Integer.parseInt(item); mv.visitIntInsn(BIPUSH, index); mv.visitMethodInsn(INVOKEINTERFACE, "java/lang/CharSequence", "charAt", "(I)C"); return ((CharSequence) ctx).charAt(index); } else { throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName())); } } private static final Map<String, ExecutableStatement[]> SUBEXPRESSION_CACHE = new WeakHashMap<String, ExecutableStatement[]>(); /** * Find an appropriate method, execute it, and return it's response. * * @param ctx - * @param name - * @return - * @throws Exception - */ @SuppressWarnings({"unchecked"}) private Object getMethod(Object ctx, String name) throws Exception { debug("{method: " + name + "}"); int st = cursor; int depth = 1; while (cursor++ < length - 1 && depth != 0) { switch (property[cursor]) { case'(': depth++; continue; case')': depth--; } } cursor--; String tk = (cursor - st) > 1 ? new String(property, st + 1, cursor - st - 1) : ""; cursor++; Object[] preConvArgs; Object[] args; ExecutableStatement[] es; if (tk.length() == 0) { //noinspection ZeroLengthArrayAllocation args = new Object[0]; //noinspection ZeroLengthArrayAllocation preConvArgs = new Object[0]; es = null; } else { if (SUBEXPRESSION_CACHE.containsKey(tk)) { es = SUBEXPRESSION_CACHE.get(tk); args = new Object[es.length]; preConvArgs = new Object[es.length]; for (int i = 0; i < es.length; i++) { preConvArgs[i] = args[i] = es[i].getValue(this.ctx, variableFactory); } } else { String[] subtokens = ParseTools.parseParameterList(tk.toCharArray(), 0, -1); es = new ExecutableStatement[subtokens.length]; args = new Object[subtokens.length]; preConvArgs = new Object[es.length]; for (int i = 0; i < subtokens.length; i++) { preConvArgs[i] = args[i] = (es[i] = (ExecutableStatement) ExpressionParser.compileExpression(subtokens[i])).getValue(this.ctx, variableFactory); } SUBEXPRESSION_CACHE.put(tk, es); } } if (es != null) { for (ExecutableStatement e : es) compiledInputs.add(e); } /** * If the target object is an instance of java.lang.Class itself then do not * adjust the Class scope target. */ Class cls = ctx instanceof Class ? (Class) ctx : ctx.getClass(); Method m; Class[] parameterTypes = null; /** * If we have not cached the method then we need to go ahead and try to resolve it. */ /** * Try to find an instance method from the class target. */ if ((m = ParseTools.getBestCanadidate(args, name, cls.getMethods())) != null) { parameterTypes = m.getParameterTypes(); } if (m == null) { /** * If we didn't find anything, maybe we're looking for the actual java.lang.Class methods. */ if ((m = ParseTools.getBestCanadidate(args, name, cls.getClass().getDeclaredMethods())) != null) { parameterTypes = m.getParameterTypes(); } } if (m == null) { StringAppender errorBuild = new StringAppender(); for (int i = 0; i < args.length; i++) { errorBuild.append(parameterTypes[i] != null ? parameterTypes[i].getClass().getName() : null); if (i < args.length - 1) errorBuild.append(", "); } throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]"); } else { if (es != null) { ExecutableStatement cExpr; for (int i = 0; i < es.length; i++) { - cExpr = es[i]; - if (cExpr.getKnownIngressType() == null) { + if ((cExpr = es[i]).getKnownIngressType() == null) { cExpr.setKnownIngressType(parameterTypes[i]); cExpr.computeTypeConversionRule(); } if (!cExpr.isConvertableIngressEgress()) { args[i] = DataConversion.convert(args[i], parameterTypes[i]); } } } else { /** * Coerce any types if required. */ for (int i = 0; i < args.length; i++) args[i] = DataConversion.convert(args[i], parameterTypes[i]); } if (first) { debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } if (m.getParameterTypes().length == 0) { if ((m.getModifiers() & Modifier.STATIC) != 0) { debug("INVOKESTATIC " + m.getName()); mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { debug("CHECKCAST " + getInternalName(m.getDeclaringClass())); mv.visitTypeInsn(CHECKCAST, getInternalName(m.getDeclaringClass())); debug("INVOKEVIRTUAL " + m.getName()); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } returnType = m.getReturnType(); stacksize++; } else { if ((m.getModifiers() & Modifier.STATIC) == 0) { debug("CHECKCAST " + getInternalName(cls)); mv.visitTypeInsn(CHECKCAST, getInternalName(cls)); } for (int i = 0; i < es.length; i++) { debug("ALOAD 0"); mv.visitVarInsn(ALOAD, 0); debug("GETFIELD p" + inputs++); mv.visitFieldInsn(GETFIELD, className, "p" + (inputs - 1), "Lorg/mvel/optimizers/ExecutableStatement;"); debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); debug("INVOKEINTERFACE ExecutableStatement.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(ExecutableStatement.class), "getValue", "(Ljava/lang/Object;Lorg/mvel/integration/VariableResolverFactory;)Ljava/lang/Object;"); if (parameterTypes[i].isPrimitive()) { unwrapPrimitive(parameterTypes[i]); } else if (preConvArgs[i] == null || (parameterTypes[i] != String.class && !parameterTypes[i].isAssignableFrom(preConvArgs[i].getClass()))) { debug("LDC " + getType(parameterTypes[i])); mv.visitLdcInsn(getType(parameterTypes[i])); debug("INVOKESTATIC DataConversion.convert"); mv.visitMethodInsn(INVOKESTATIC, "org/mvel/DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;"); debug("CHECKCAST " + getInternalName(parameterTypes[i])); mv.visitTypeInsn(CHECKCAST, getInternalName(parameterTypes[i])); } else if (parameterTypes[i] == String.class) { debug("<<<DYNAMIC TYPE OPTIMIZATION STRING>>"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;"); } else { debug("<<<DYNAMIC TYPING BYPASS>>>"); debug("<<<OPT. JUSTIFICATION " + parameterTypes[i] + "=" + preConvArgs[i].getClass() + ">>>"); debug("CHECKCAST " + getInternalName(parameterTypes[i])); mv.visitTypeInsn(CHECKCAST, getInternalName(parameterTypes[i])); } stacksize += 3; } if ((m.getModifiers() & Modifier.STATIC) != 0) { debug("INVOKESTATIC: " + m.getName()); mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { if (m.getDeclaringClass() != cls && m.getDeclaringClass().isInterface()) { debug("INVOKEINTERFACE: " + getInternalName(m.getDeclaringClass()) + "." + m.getName()); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { debug("INVOKEVIRTUAL: " + getInternalName(cls) + "." + m.getName()); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(cls), m.getName(), getMethodDescriptor(m)); } } returnType = m.getReturnType(); stacksize++; } return m.invoke(ctx, args); } } private Class tryStaticAccess() { try { /** * Try to resolve this *smartly* as a static class reference. * * This starts at the end of the token and starts to step backwards to figure out whether * or not this may be a static class reference. We search for method calls simply by * inspecting for ()'s. The first union area we come to where no brackets are present is our * test-point for a class reference. If we find a class, we pass the reference to the * property accessor along with trailing methods (if any). * */ boolean meth = false; int depth = 0; int last = property.length; for (int i = property.length - 1; i > 0; i--) { switch (property[i]) { case'.': if (!meth) { return Class.forName(new String(property, 0, last)); } meth = false; last = i; break; case')': if (depth++ == 0) meth = true; break; case'(': depth--; break; } } } catch (Exception cnfe) { // do nothing. } return null; } private java.lang.Class loadClass(byte[] b) throws Exception { //override classDefine (as it is protected) and define the class. Class clazz = null; ClassLoader loader = ClassLoader.getSystemClassLoader(); Class cls = Class.forName("java.lang.ClassLoader"); java.lang.reflect.Method method = cls.getDeclaredMethod("defineClass", new Class[]{String.class, byte[].class, int.class, int.class}); // protected method invocaton method.setAccessible(true); try { Object[] args = new Object[]{className, b, 0, (b.length)}; clazz = (Class) method.invoke(loader, args); } finally { method.setAccessible(false); } return clazz; } public static void debug(String instruction) { assert ParseTools.debug(instruction); } public String getName() { return "ASM"; } public Object getResultOptPass() { return val; } private void unwrapPrimitive(Class cls) { if (cls == boolean.class) { debug("CHECKCAST java/lang/Boolean"); mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean"); debug("INVOKEVIRTUAL java/lang/Boolean.booleanValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z"); } else if (cls == int.class) { debug("CHECKCAST java/lang/Integer"); mv.visitTypeInsn(CHECKCAST, "java/lang/Integer"); debug("INVOKEVIRTUAL java/lang/Integer.intValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I"); } else if (cls == float.class) { debug("CHECKCAST java/lang/Float"); mv.visitTypeInsn(CHECKCAST, "java/lang/Float"); debug("INVOKEVIRTUAL java/lang/Float.floatValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F"); } else if (cls == double.class) { debug("CHECKCAST java/lang/Double"); mv.visitTypeInsn(CHECKCAST, "java/lang/Double"); debug("INVOKEVIRTUAL java/lang/Double.doubleValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D"); } else if (cls == short.class) { debug("CHECKCAST java/lang/Short"); mv.visitTypeInsn(CHECKCAST, "java/lang/Short"); debug("INVOKEVIRTUAL java/lang/Short.shortValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S"); } else if (cls == long.class) { debug("CHECKCAST java/lang/Long"); mv.visitTypeInsn(CHECKCAST, "java/lang/Long"); debug("INVOKEVIRTUAL java/lang/Long.longValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "longValue", "()L"); } else if (cls == byte.class) { debug("CHECKCAST java/lang/Byte"); mv.visitTypeInsn(CHECKCAST, "java/lang/Byte"); debug("INVOKEVIRTUAL java/lang/Byte.byteValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B"); } else if (cls == char.class) { debug("CHECKCAST java/lang/Character"); mv.visitTypeInsn(CHECKCAST, "java/lang/Character"); debug("INVOKEVIRTUAL java/lang/Character.charValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C"); } } private void wrapPrimitive(Class<? extends Object> cls) { if (cls == boolean.class) { mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); } else if (cls == int.class) { mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); } else if (cls == float.class) { mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); } else if (cls == double.class) { mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); } else if (cls == short.class) { mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); } else if (cls == long.class) { mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); } else if (cls == byte.class) { mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); } else if (cls == char.class) { mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); } } public void buildInputs() { if (inputs == 0) return; debug("\n{SETTING UP MEMBERS...}\n"); StringAppender constSig = new StringAppender("("); int size = inputs; for (int i = 0; i < size; i++) { debug("ACC_PRIVATE p" + i); FieldVisitor fv = cw.visitField(ACC_PRIVATE, "p" + i, "Lorg/mvel/optimizers/ExecutableStatement;", null, null); fv.visitEnd(); constSig.append("Lorg/mvel/optimizers/ExecutableStatement;"); } constSig.append(")V"); debug("\n{CREATING INJECTION CONSTRUCTOR}\n"); MethodVisitor cv = cw.visitMethod(ACC_PUBLIC, "<init>", constSig.toString(), null, null); cv.visitCode(); debug("ALOAD 0"); cv.visitVarInsn(ALOAD, 0); debug("INVOKESPECIAL java/lang/Object.<init>"); cv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); for (int i = 0; i < size; i++) { debug("ALOAD 0"); cv.visitVarInsn(ALOAD, 0); debug("ALOAD " + (i + 1)); cv.visitVarInsn(ALOAD, i + 1); debug("PUTFIELD p" + i); cv.visitFieldInsn(PUTFIELD, className, "p" + i, "Lorg/mvel/optimizers/ExecutableStatement;"); } debug("RETURN"); cv.visitInsn(RETURN); cv.visitMaxs(0, 0); cv.visitEnd(); debug("}"); } }
true
true
private Object getMethod(Object ctx, String name) throws Exception { debug("{method: " + name + "}"); int st = cursor; int depth = 1; while (cursor++ < length - 1 && depth != 0) { switch (property[cursor]) { case'(': depth++; continue; case')': depth--; } } cursor--; String tk = (cursor - st) > 1 ? new String(property, st + 1, cursor - st - 1) : ""; cursor++; Object[] preConvArgs; Object[] args; ExecutableStatement[] es; if (tk.length() == 0) { //noinspection ZeroLengthArrayAllocation args = new Object[0]; //noinspection ZeroLengthArrayAllocation preConvArgs = new Object[0]; es = null; } else { if (SUBEXPRESSION_CACHE.containsKey(tk)) { es = SUBEXPRESSION_CACHE.get(tk); args = new Object[es.length]; preConvArgs = new Object[es.length]; for (int i = 0; i < es.length; i++) { preConvArgs[i] = args[i] = es[i].getValue(this.ctx, variableFactory); } } else { String[] subtokens = ParseTools.parseParameterList(tk.toCharArray(), 0, -1); es = new ExecutableStatement[subtokens.length]; args = new Object[subtokens.length]; preConvArgs = new Object[es.length]; for (int i = 0; i < subtokens.length; i++) { preConvArgs[i] = args[i] = (es[i] = (ExecutableStatement) ExpressionParser.compileExpression(subtokens[i])).getValue(this.ctx, variableFactory); } SUBEXPRESSION_CACHE.put(tk, es); } } if (es != null) { for (ExecutableStatement e : es) compiledInputs.add(e); } /** * If the target object is an instance of java.lang.Class itself then do not * adjust the Class scope target. */ Class cls = ctx instanceof Class ? (Class) ctx : ctx.getClass(); Method m; Class[] parameterTypes = null; /** * If we have not cached the method then we need to go ahead and try to resolve it. */ /** * Try to find an instance method from the class target. */ if ((m = ParseTools.getBestCanadidate(args, name, cls.getMethods())) != null) { parameterTypes = m.getParameterTypes(); } if (m == null) { /** * If we didn't find anything, maybe we're looking for the actual java.lang.Class methods. */ if ((m = ParseTools.getBestCanadidate(args, name, cls.getClass().getDeclaredMethods())) != null) { parameterTypes = m.getParameterTypes(); } } if (m == null) { StringAppender errorBuild = new StringAppender(); for (int i = 0; i < args.length; i++) { errorBuild.append(parameterTypes[i] != null ? parameterTypes[i].getClass().getName() : null); if (i < args.length - 1) errorBuild.append(", "); } throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]"); } else { if (es != null) { ExecutableStatement cExpr; for (int i = 0; i < es.length; i++) { cExpr = es[i]; if (cExpr.getKnownIngressType() == null) { cExpr.setKnownIngressType(parameterTypes[i]); cExpr.computeTypeConversionRule(); } if (!cExpr.isConvertableIngressEgress()) { args[i] = DataConversion.convert(args[i], parameterTypes[i]); } } } else { /** * Coerce any types if required. */ for (int i = 0; i < args.length; i++) args[i] = DataConversion.convert(args[i], parameterTypes[i]); } if (first) { debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } if (m.getParameterTypes().length == 0) { if ((m.getModifiers() & Modifier.STATIC) != 0) { debug("INVOKESTATIC " + m.getName()); mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { debug("CHECKCAST " + getInternalName(m.getDeclaringClass())); mv.visitTypeInsn(CHECKCAST, getInternalName(m.getDeclaringClass())); debug("INVOKEVIRTUAL " + m.getName()); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } returnType = m.getReturnType(); stacksize++; } else { if ((m.getModifiers() & Modifier.STATIC) == 0) { debug("CHECKCAST " + getInternalName(cls)); mv.visitTypeInsn(CHECKCAST, getInternalName(cls)); } for (int i = 0; i < es.length; i++) { debug("ALOAD 0"); mv.visitVarInsn(ALOAD, 0); debug("GETFIELD p" + inputs++); mv.visitFieldInsn(GETFIELD, className, "p" + (inputs - 1), "Lorg/mvel/optimizers/ExecutableStatement;"); debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); debug("INVOKEINTERFACE ExecutableStatement.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(ExecutableStatement.class), "getValue", "(Ljava/lang/Object;Lorg/mvel/integration/VariableResolverFactory;)Ljava/lang/Object;"); if (parameterTypes[i].isPrimitive()) { unwrapPrimitive(parameterTypes[i]); } else if (preConvArgs[i] == null || (parameterTypes[i] != String.class && !parameterTypes[i].isAssignableFrom(preConvArgs[i].getClass()))) { debug("LDC " + getType(parameterTypes[i])); mv.visitLdcInsn(getType(parameterTypes[i])); debug("INVOKESTATIC DataConversion.convert"); mv.visitMethodInsn(INVOKESTATIC, "org/mvel/DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;"); debug("CHECKCAST " + getInternalName(parameterTypes[i])); mv.visitTypeInsn(CHECKCAST, getInternalName(parameterTypes[i])); } else if (parameterTypes[i] == String.class) { debug("<<<DYNAMIC TYPE OPTIMIZATION STRING>>"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;"); } else { debug("<<<DYNAMIC TYPING BYPASS>>>"); debug("<<<OPT. JUSTIFICATION " + parameterTypes[i] + "=" + preConvArgs[i].getClass() + ">>>"); debug("CHECKCAST " + getInternalName(parameterTypes[i])); mv.visitTypeInsn(CHECKCAST, getInternalName(parameterTypes[i])); } stacksize += 3; } if ((m.getModifiers() & Modifier.STATIC) != 0) { debug("INVOKESTATIC: " + m.getName()); mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { if (m.getDeclaringClass() != cls && m.getDeclaringClass().isInterface()) { debug("INVOKEINTERFACE: " + getInternalName(m.getDeclaringClass()) + "." + m.getName()); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { debug("INVOKEVIRTUAL: " + getInternalName(cls) + "." + m.getName()); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(cls), m.getName(), getMethodDescriptor(m)); } } returnType = m.getReturnType(); stacksize++; } return m.invoke(ctx, args); } }
private Object getMethod(Object ctx, String name) throws Exception { debug("{method: " + name + "}"); int st = cursor; int depth = 1; while (cursor++ < length - 1 && depth != 0) { switch (property[cursor]) { case'(': depth++; continue; case')': depth--; } } cursor--; String tk = (cursor - st) > 1 ? new String(property, st + 1, cursor - st - 1) : ""; cursor++; Object[] preConvArgs; Object[] args; ExecutableStatement[] es; if (tk.length() == 0) { //noinspection ZeroLengthArrayAllocation args = new Object[0]; //noinspection ZeroLengthArrayAllocation preConvArgs = new Object[0]; es = null; } else { if (SUBEXPRESSION_CACHE.containsKey(tk)) { es = SUBEXPRESSION_CACHE.get(tk); args = new Object[es.length]; preConvArgs = new Object[es.length]; for (int i = 0; i < es.length; i++) { preConvArgs[i] = args[i] = es[i].getValue(this.ctx, variableFactory); } } else { String[] subtokens = ParseTools.parseParameterList(tk.toCharArray(), 0, -1); es = new ExecutableStatement[subtokens.length]; args = new Object[subtokens.length]; preConvArgs = new Object[es.length]; for (int i = 0; i < subtokens.length; i++) { preConvArgs[i] = args[i] = (es[i] = (ExecutableStatement) ExpressionParser.compileExpression(subtokens[i])).getValue(this.ctx, variableFactory); } SUBEXPRESSION_CACHE.put(tk, es); } } if (es != null) { for (ExecutableStatement e : es) compiledInputs.add(e); } /** * If the target object is an instance of java.lang.Class itself then do not * adjust the Class scope target. */ Class cls = ctx instanceof Class ? (Class) ctx : ctx.getClass(); Method m; Class[] parameterTypes = null; /** * If we have not cached the method then we need to go ahead and try to resolve it. */ /** * Try to find an instance method from the class target. */ if ((m = ParseTools.getBestCanadidate(args, name, cls.getMethods())) != null) { parameterTypes = m.getParameterTypes(); } if (m == null) { /** * If we didn't find anything, maybe we're looking for the actual java.lang.Class methods. */ if ((m = ParseTools.getBestCanadidate(args, name, cls.getClass().getDeclaredMethods())) != null) { parameterTypes = m.getParameterTypes(); } } if (m == null) { StringAppender errorBuild = new StringAppender(); for (int i = 0; i < args.length; i++) { errorBuild.append(parameterTypes[i] != null ? parameterTypes[i].getClass().getName() : null); if (i < args.length - 1) errorBuild.append(", "); } throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]"); } else { if (es != null) { ExecutableStatement cExpr; for (int i = 0; i < es.length; i++) { if ((cExpr = es[i]).getKnownIngressType() == null) { cExpr.setKnownIngressType(parameterTypes[i]); cExpr.computeTypeConversionRule(); } if (!cExpr.isConvertableIngressEgress()) { args[i] = DataConversion.convert(args[i], parameterTypes[i]); } } } else { /** * Coerce any types if required. */ for (int i = 0; i < args.length; i++) args[i] = DataConversion.convert(args[i], parameterTypes[i]); } if (first) { debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } if (m.getParameterTypes().length == 0) { if ((m.getModifiers() & Modifier.STATIC) != 0) { debug("INVOKESTATIC " + m.getName()); mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { debug("CHECKCAST " + getInternalName(m.getDeclaringClass())); mv.visitTypeInsn(CHECKCAST, getInternalName(m.getDeclaringClass())); debug("INVOKEVIRTUAL " + m.getName()); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } returnType = m.getReturnType(); stacksize++; } else { if ((m.getModifiers() & Modifier.STATIC) == 0) { debug("CHECKCAST " + getInternalName(cls)); mv.visitTypeInsn(CHECKCAST, getInternalName(cls)); } for (int i = 0; i < es.length; i++) { debug("ALOAD 0"); mv.visitVarInsn(ALOAD, 0); debug("GETFIELD p" + inputs++); mv.visitFieldInsn(GETFIELD, className, "p" + (inputs - 1), "Lorg/mvel/optimizers/ExecutableStatement;"); debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); debug("INVOKEINTERFACE ExecutableStatement.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(ExecutableStatement.class), "getValue", "(Ljava/lang/Object;Lorg/mvel/integration/VariableResolverFactory;)Ljava/lang/Object;"); if (parameterTypes[i].isPrimitive()) { unwrapPrimitive(parameterTypes[i]); } else if (preConvArgs[i] == null || (parameterTypes[i] != String.class && !parameterTypes[i].isAssignableFrom(preConvArgs[i].getClass()))) { debug("LDC " + getType(parameterTypes[i])); mv.visitLdcInsn(getType(parameterTypes[i])); debug("INVOKESTATIC DataConversion.convert"); mv.visitMethodInsn(INVOKESTATIC, "org/mvel/DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;"); debug("CHECKCAST " + getInternalName(parameterTypes[i])); mv.visitTypeInsn(CHECKCAST, getInternalName(parameterTypes[i])); } else if (parameterTypes[i] == String.class) { debug("<<<DYNAMIC TYPE OPTIMIZATION STRING>>"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;"); } else { debug("<<<DYNAMIC TYPING BYPASS>>>"); debug("<<<OPT. JUSTIFICATION " + parameterTypes[i] + "=" + preConvArgs[i].getClass() + ">>>"); debug("CHECKCAST " + getInternalName(parameterTypes[i])); mv.visitTypeInsn(CHECKCAST, getInternalName(parameterTypes[i])); } stacksize += 3; } if ((m.getModifiers() & Modifier.STATIC) != 0) { debug("INVOKESTATIC: " + m.getName()); mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { if (m.getDeclaringClass() != cls && m.getDeclaringClass().isInterface()) { debug("INVOKEINTERFACE: " + getInternalName(m.getDeclaringClass()) + "." + m.getName()); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { debug("INVOKEVIRTUAL: " + getInternalName(cls) + "." + m.getName()); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(cls), m.getName(), getMethodDescriptor(m)); } } returnType = m.getReturnType(); stacksize++; } return m.invoke(ctx, args); } }
diff --git a/src/main/java/jscover/server/HttpServer.java b/src/main/java/jscover/server/HttpServer.java index 200c5322..be5a1a06 100644 --- a/src/main/java/jscover/server/HttpServer.java +++ b/src/main/java/jscover/server/HttpServer.java @@ -1,487 +1,485 @@ /** 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.server; import jscover.util.IoUtils; import java.io.*; import java.net.*; import java.util.*; import static java.lang.String.format; public class HttpServer extends Thread { private Socket socket; private String version; protected File wwwRoot; protected InputStream is; protected OutputStream os; protected PrintWriter pw = null; protected IoUtils ioUtils = IoUtils.getInstance(); public HttpServer(Socket socket, File wwwRoot, String version) { this.wwwRoot = wwwRoot; this.socket = socket; this.version = version; } public void run() { BufferedReader br = null; try { is = socket.getInputStream(); os = socket.getOutputStream(); br = new BufferedReader(new InputStreamReader(is)); pw = new PrintWriter(os); - String requestString = null; - while (requestString == null) - requestString = br.readLine(); + String requestString = br.readLine(); StringTokenizer tokenizer = new StringTokenizer(requestString); String httpMethod = tokenizer.nextToken(); HttpRequest httpRequest = new HttpRequest(tokenizer.nextToken()); String headerLine; Map<String, List<String>> headers = new HashMap<String, List<String>>(); while (!(headerLine = br.readLine()).equals("")) { int index = headerLine.indexOf(':'); if (index >= 0) { String headerField = headerLine.substring(0, index).trim(); String headerValue = headerLine.substring(index + 1).trim(); if (!headers.containsKey(headerField)) headers.put(headerField, new ArrayList<String>()); headers.get(headerField).add(headerValue); } } httpRequest.setHeaders(headers); if (httpMethod.equals("GET")) { if (httpRequest.getPath().equals("/stop")) { sendResponse(HTTP_STATUS.HTTP_OK, MIME.TEXT_PLAIN, "Shutting down the server."); ioUtils.closeQuietly(br); ioUtils.closeQuietly(os); System.exit(0); } handleGet(httpRequest); } else if (httpMethod.equals("HEAD")) { handleHead(httpRequest); } else if (httpMethod.equals("POST")) { int length = Integer.valueOf(headers.get("Content-Length").get(0)); handlePost(httpRequest, ioUtils.toStringNoClose(br, length)); } else throw new UnsupportedOperationException("No support for "+httpMethod); } catch (Exception e) { e.printStackTrace(); } finally { ioUtils.closeQuietly(br); ioUtils.closeQuietly(os); } } protected void handleHead(HttpRequest httpRequest) { throw new UnsupportedOperationException("No support for HEAD"); } protected void handlePost(HttpRequest request, String data) { String response = format("<html><body>Posted<pre id=\"postData\">%s</pre></body></html>", data); sendResponse(HTTP_STATUS.HTTP_OK, MIME.HTML, response); } protected void handleGet(HttpRequest request) throws IOException { String path = request.getRelativePath(); File file = new File(wwwRoot, path); if (!file.exists()) { String data = "<html><body>Not found</body></html>"; sendResponse(HTTP_STATUS.HTTP_FILE_NOT_FOUND, MIME.HTML, data); } else if (file.isFile()) { sendResponse(HTTP_STATUS.HTTP_OK, request.getMime(), file); } else { StringBuilder data = new StringBuilder(); data.append("<html>\n<body>\n"); data.append(format("<h1>Directory %s</h1>\n", request.getPath())); File parentDir = file.getParentFile(); if (!file.equals(wwwRoot)) { if (parentDir.equals(wwwRoot)) data.append("<a href=\"/\">..</a><br/>\n"); else data.append(format("<a href=\"%s\">..</a><br/>\n", getRelativePath(parentDir))); } for (File linkTo : file.listFiles()) { data.append(format("<a href=\"%s\">%s</a><br/>\n", getRelativePath(linkTo), linkTo.getName())); } data.append("</body>\n</html>"); sendResponse(HTTP_STATUS.HTTP_OK, MIME.HTML, data.toString()); } } private String getRelativePath(File linkTo) { String path = linkTo.getAbsolutePath().substring(wwwRoot.getAbsolutePath().length()); return path.replaceAll("\\\\", "/"); } protected void sendResponse(HTTP_STATUS status, MIME mime, String data) { pw.print(format("HTTP/1.0 %s\n", status)); pw.write(format("Server: JSCover/%s\n", version)); pw.write(format("Content-Type: %s\n", mime.getContentType())); pw.write(format("Content-Length: %d\n\n", data.length())); pw.write(data); pw.flush(); } private void sendResponse(HTTP_STATUS status, MIME mime, File data) { pw.print(format("HTTP/1.0 %s\n", status)); pw.write(format("Server: JSCover/%s\n", version)); pw.write(format("Content-Type: %s\n", mime.getContentType())); pw.write(format("Content-Length: %d\n\n", data.length())); pw.flush(); ioUtils.copyNoClose(data, os); } protected void sendResponse(HTTP_STATUS status, MIME mime, InputStream is) { pw.print(format("HTTP/1.0 %s\n", status)); pw.write(format("Server: JSCover/%s\n", version)); pw.write(format("Content-Type: %s\n\n", mime.getContentType())); pw.flush(); ioUtils.copy(is, os); } }
true
true
public void run() { BufferedReader br = null; try { is = socket.getInputStream(); os = socket.getOutputStream(); br = new BufferedReader(new InputStreamReader(is)); pw = new PrintWriter(os); String requestString = null; while (requestString == null) requestString = br.readLine(); StringTokenizer tokenizer = new StringTokenizer(requestString); String httpMethod = tokenizer.nextToken(); HttpRequest httpRequest = new HttpRequest(tokenizer.nextToken()); String headerLine; Map<String, List<String>> headers = new HashMap<String, List<String>>(); while (!(headerLine = br.readLine()).equals("")) { int index = headerLine.indexOf(':'); if (index >= 0) { String headerField = headerLine.substring(0, index).trim(); String headerValue = headerLine.substring(index + 1).trim(); if (!headers.containsKey(headerField)) headers.put(headerField, new ArrayList<String>()); headers.get(headerField).add(headerValue); } } httpRequest.setHeaders(headers); if (httpMethod.equals("GET")) { if (httpRequest.getPath().equals("/stop")) { sendResponse(HTTP_STATUS.HTTP_OK, MIME.TEXT_PLAIN, "Shutting down the server."); ioUtils.closeQuietly(br); ioUtils.closeQuietly(os); System.exit(0); } handleGet(httpRequest); } else if (httpMethod.equals("HEAD")) { handleHead(httpRequest); } else if (httpMethod.equals("POST")) { int length = Integer.valueOf(headers.get("Content-Length").get(0)); handlePost(httpRequest, ioUtils.toStringNoClose(br, length)); } else throw new UnsupportedOperationException("No support for "+httpMethod); } catch (Exception e) { e.printStackTrace(); } finally { ioUtils.closeQuietly(br); ioUtils.closeQuietly(os); } }
public void run() { BufferedReader br = null; try { is = socket.getInputStream(); os = socket.getOutputStream(); br = new BufferedReader(new InputStreamReader(is)); pw = new PrintWriter(os); String requestString = br.readLine(); StringTokenizer tokenizer = new StringTokenizer(requestString); String httpMethod = tokenizer.nextToken(); HttpRequest httpRequest = new HttpRequest(tokenizer.nextToken()); String headerLine; Map<String, List<String>> headers = new HashMap<String, List<String>>(); while (!(headerLine = br.readLine()).equals("")) { int index = headerLine.indexOf(':'); if (index >= 0) { String headerField = headerLine.substring(0, index).trim(); String headerValue = headerLine.substring(index + 1).trim(); if (!headers.containsKey(headerField)) headers.put(headerField, new ArrayList<String>()); headers.get(headerField).add(headerValue); } } httpRequest.setHeaders(headers); if (httpMethod.equals("GET")) { if (httpRequest.getPath().equals("/stop")) { sendResponse(HTTP_STATUS.HTTP_OK, MIME.TEXT_PLAIN, "Shutting down the server."); ioUtils.closeQuietly(br); ioUtils.closeQuietly(os); System.exit(0); } handleGet(httpRequest); } else if (httpMethod.equals("HEAD")) { handleHead(httpRequest); } else if (httpMethod.equals("POST")) { int length = Integer.valueOf(headers.get("Content-Length").get(0)); handlePost(httpRequest, ioUtils.toStringNoClose(br, length)); } else throw new UnsupportedOperationException("No support for "+httpMethod); } catch (Exception e) { e.printStackTrace(); } finally { ioUtils.closeQuietly(br); ioUtils.closeQuietly(os); } }
diff --git a/src/delivery/model/PaypalPDT.java b/src/delivery/model/PaypalPDT.java index 6805102..982a374 100644 --- a/src/delivery/model/PaypalPDT.java +++ b/src/delivery/model/PaypalPDT.java @@ -1,144 +1,144 @@ package delivery.model; import java.io.*; import java.util.*; import java.net.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.*; import co.aceteq.util.UpdateDB; public class PaypalPDT { private String tx; private String st; private String amt; private String cc; private String item_name; private boolean verified; private String paypalResp; private final static String at = "zW23TEL-sHErudZAvhyX5fythMDM8zmA_nNcbmgucFrE6QfSOjVpY4AOxh4"; public PaypalPDT() { verified = false; } public static HttpsURLConnection getSSLByPassedConnection(String url) throws Exception { X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { tm }, null); SSLContext.setDefault(ctx); HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection(); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String paramString, SSLSession paramSSLSession) { return true; } }); return conn; } public boolean verifyTransaction(){ boolean verified = false; try{ String str = "cmd=_notify-synch&tx="+tx+"&at="+at; HttpsURLConnection uc = getSSLByPassedConnection("https://www.sandbox.paypal.com/cgi-bin/webscr"); uc.setDoOutput(true); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.println(str); pw.close(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String res = in.readLine(); str = ""; while((str = in.readLine()) != null){ - res += str; + res += "\n" + str; } this.paypalResp = res; System.out.println(res); if (res.substring(0,4).equals("SUCC")) { System.out.println("Success matched."); verified = true; } }catch(Exception e) { e.printStackTrace(); } this.verified = verified; return verified; } public void save() { Map<String,String> strData = new HashMap<String,String>(); strData.put("tx",this.tx); strData.put("st",this.st); strData.put("amt",this.amt); strData.put("verified",new Boolean(this.verified).toString()); strData.put("paypalResponse",this.paypalResp); UpdateDB.insert("transactions",strData,null); } public void setTx(String x) { this.tx = x; } public String getTx() { return this.tx; } public void setSt(String x) { this.st = x; } public String getSt() { return this.st; } public void setAmt(String x) { this.amt = x; } public String getAmt() { return this.amt; } public void setCc(String x) { this.cc = x; } public void setItem_name(String x) { this.item_name = x; } public String getCc() { return this.cc; } public String getItem_name() { return this.item_name; } }
true
true
public boolean verifyTransaction(){ boolean verified = false; try{ String str = "cmd=_notify-synch&tx="+tx+"&at="+at; HttpsURLConnection uc = getSSLByPassedConnection("https://www.sandbox.paypal.com/cgi-bin/webscr"); uc.setDoOutput(true); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.println(str); pw.close(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String res = in.readLine(); str = ""; while((str = in.readLine()) != null){ res += str; } this.paypalResp = res; System.out.println(res); if (res.substring(0,4).equals("SUCC")) { System.out.println("Success matched."); verified = true; } }catch(Exception e) { e.printStackTrace(); } this.verified = verified; return verified; }
public boolean verifyTransaction(){ boolean verified = false; try{ String str = "cmd=_notify-synch&tx="+tx+"&at="+at; HttpsURLConnection uc = getSSLByPassedConnection("https://www.sandbox.paypal.com/cgi-bin/webscr"); uc.setDoOutput(true); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.println(str); pw.close(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String res = in.readLine(); str = ""; while((str = in.readLine()) != null){ res += "\n" + str; } this.paypalResp = res; System.out.println(res); if (res.substring(0,4).equals("SUCC")) { System.out.println("Success matched."); verified = true; } }catch(Exception e) { e.printStackTrace(); } this.verified = verified; return verified; }
diff --git a/src/com/android/calendar/widget/CalendarAppWidgetService.java b/src/com/android/calendar/widget/CalendarAppWidgetService.java index 0420cc43..2ee9f1b2 100644 --- a/src/com/android/calendar/widget/CalendarAppWidgetService.java +++ b/src/com/android/calendar/widget/CalendarAppWidgetService.java @@ -1,391 +1,394 @@ /* * Copyright (C) 2009 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.calendar.widget; import com.google.common.annotations.VisibleForTesting; import com.android.calendar.R; import com.android.calendar.Utils; import com.android.calendar.widget.CalendarAppWidgetModel.DayInfo; import com.android.calendar.widget.CalendarAppWidgetModel.EventInfo; import com.android.calendar.widget.CalendarAppWidgetModel.RowInfo; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.provider.Calendar.Attendees; import android.provider.Calendar.CalendarCache; import android.provider.Calendar.Calendars; import android.provider.Calendar.Instances; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import android.view.View; import android.widget.RemoteViews; import android.widget.RemoteViewsService; public class CalendarAppWidgetService extends RemoteViewsService { private static final String TAG = "CalendarWidget"; static final int EVENT_MIN_COUNT = 20; static final int EVENT_MAX_COUNT = 503; private static final String EVENT_SORT_ORDER = Instances.START_DAY + " ASC, " + Instances.START_MINUTE + " ASC, " + Instances.END_DAY + " ASC, " + Instances.END_MINUTE + " ASC LIMIT " + EVENT_MAX_COUNT; // TODO can't use parameter here because provider is dropping them private static final String EVENT_SELECTION = Calendars.SELECTED + "=1 AND " + Instances.SELF_ATTENDEE_STATUS + "!=" + Attendees.ATTENDEE_STATUS_DECLINED; static final String[] EVENT_PROJECTION = new String[] { Instances.ALL_DAY, Instances.BEGIN, Instances.END, Instances.TITLE, Instances.EVENT_LOCATION, Instances.EVENT_ID, Instances.START_DAY, Instances.END_DAY, Instances.COLOR }; static final int INDEX_ALL_DAY = 0; static final int INDEX_BEGIN = 1; static final int INDEX_END = 2; static final int INDEX_TITLE = 3; static final int INDEX_EVENT_LOCATION = 4; static final int INDEX_EVENT_ID = 5; static final int INDEX_START_DAY = 6; static final int INDEX_END_DAY = 7; static final int INDEX_COLOR = 8; static final int MAX_DAYS = 7; private static final long SEARCH_DURATION = MAX_DAYS * DateUtils.DAY_IN_MILLIS; /** * Update interval used when no next-update calculated, or bad trigger time in past. * Unit: milliseconds. */ private static final long UPDATE_TIME_NO_EVENTS = DateUtils.HOUR_IN_MILLIS * 6; @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new CalendarFactory(getApplicationContext(), intent); } protected static class CalendarFactory implements RemoteViewsService.RemoteViewsFactory { private static final boolean LOGD = false; // Suppress unnecessary logging about update time. Need to be static as this object is // re-instanciated frequently. // TODO: It seems loadData() is called via onCreate() four times, which should mean // unnecessary CalendarFactory object is created and dropped. It is not efficient. private static long sLastUpdateTime = UPDATE_TIME_NO_EVENTS; private Context mContext; private Resources mResources; private CalendarAppWidgetModel mModel; private Cursor mCursor; protected CalendarFactory(Context context, Intent intent) { mContext = context; mResources = context.getResources(); } @Override public void onCreate() { loadData(); } @Override public void onDataSetChanged() { loadData(); } @Override public void onDestroy() { mCursor.close(); } @Override public RemoteViews getLoadingView() { RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_loading); return views; } @Override public RemoteViews getViewAt(int position) { // we use getCount here so that it doesn't return null when empty if (position < 0 || position >= getCount()) { return null; } if (mModel.mEventInfos.isEmpty() || mModel.mRowInfos.isEmpty()) { RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_no_events); final Intent intent = CalendarAppWidgetProvider.getLaunchFillInIntent(0); views.setOnClickFillInIntent(R.id.appwidget_no_events, intent); return views; } RowInfo rowInfo = mModel.mRowInfos.get(position); if (rowInfo.mType == RowInfo.TYPE_DAY) { RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_day); DayInfo dayInfo = mModel.mDayInfos.get(rowInfo.mIndex); updateTextView(views, R.id.date, View.VISIBLE, dayInfo.mDayLabel); return views; } else { final RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_row); final EventInfo eventInfo = mModel.mEventInfos.get(rowInfo.mIndex); final long now = System.currentTimeMillis(); if (!eventInfo.allDay && eventInfo.start <= now && now <= eventInfo.end) { views.setInt(R.id.appwidget_row, "setBackgroundColor", mResources.getColor(R.color.appwidget_row_in_progress)); + } else { + views.setInt(R.id.appwidget_row, "setBackgroundColor", + mResources.getColor(R.color.appwidget_row_default)); } updateTextView(views, R.id.when, eventInfo.visibWhen, eventInfo.when); updateTextView(views, R.id.where, eventInfo.visibWhere, eventInfo.where); updateTextView(views, R.id.title, eventInfo.visibTitle, eventInfo.title); views.setViewVisibility(R.id.color, View.VISIBLE); views.setInt(R.id.color, "setBackgroundColor", eventInfo.color); // An element in ListView. final Intent fillInIntent = CalendarAppWidgetProvider.getLaunchFillInIntent(eventInfo.start); views.setOnClickFillInIntent(R.id.appwidget_row, fillInIntent); return views; } } @Override public int getViewTypeCount() { return 4; } @Override public int getCount() { // if there are no events, we still return 1 to represent the "no // events" view return Math.max(1, mModel.mRowInfos.size()); } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return true; } private void loadData() { final long now = System.currentTimeMillis(); if (LOGD) Log.d(TAG, "Querying for widget events..."); if (mCursor != null) { mCursor.close(); } final ContentResolver resolver = mContext.getContentResolver(); mCursor = getUpcomingInstancesCursor(resolver, SEARCH_DURATION, now); String tz = getTimeZoneFromDB(resolver); mModel = buildAppWidgetModel(mContext, mCursor, tz); // Schedule an alarm to wake ourselves up for the next update. We also cancel // all existing wake-ups because PendingIntents don't match against extras. long triggerTime = calculateUpdateTime(mModel, now); // If no next-update calculated, or bad trigger time in past, schedule // update about six hours from now. if (triggerTime < now) { Log.w(TAG, "Encountered bad trigger time " + formatDebugTime(triggerTime, now)); triggerTime = now + UPDATE_TIME_NO_EVENTS; } final AlarmManager alertManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE); final PendingIntent pendingUpdate = CalendarAppWidgetProvider.getUpdateIntent(mContext); alertManager.cancel(pendingUpdate); alertManager.set(AlarmManager.RTC, triggerTime, pendingUpdate); if (triggerTime != sLastUpdateTime) { Log.d(TAG, "Scheduled next update at " + formatDebugTime(triggerTime, now)); sLastUpdateTime = triggerTime; } } /** * Query across all calendars for upcoming event instances from now until * some time in the future. * * Widen the time range that we query by one day on each end so that we can * catch all-day events. All-day events are stored starting at midnight in * UTC but should be included in the list of events starting at midnight * local time. This may fetch more events than we actually want, so we * filter them out later. * * @param resolver {@link ContentResolver} to use when querying * {@link Instances#CONTENT_URI}. * @param searchDuration Distance into the future to look for event * instances, in milliseconds. * @param now Current system time to use for this update, possibly from * {@link System#currentTimeMillis()}. */ private Cursor getUpcomingInstancesCursor(ContentResolver resolver, long searchDuration, long now) { // Search for events from now until some time in the future // Add a day on either side to catch all-day events long begin = now - DateUtils.DAY_IN_MILLIS; long end = now + searchDuration + DateUtils.DAY_IN_MILLIS; Uri uri = Uri.withAppendedPath(Instances.CONTENT_URI, String.format("%d/%d", begin, end)); Cursor cursor = resolver.query(uri, EVENT_PROJECTION, EVENT_SELECTION, null, EVENT_SORT_ORDER); // Start managing the cursor ourselves MatrixCursor matrixCursor = Utils.matrixCursorFromCursor(cursor); cursor.close(); return matrixCursor; } private String getTimeZoneFromDB(ContentResolver resolver) { String tz = null; Cursor tzCursor = null; try { tzCursor = resolver.query( CalendarCache.URI, CalendarCache.POJECTION, null, null, null); if (tzCursor != null) { int keyColumn = tzCursor.getColumnIndexOrThrow(CalendarCache.KEY); int valueColumn = tzCursor.getColumnIndexOrThrow(CalendarCache.VALUE); while (tzCursor.moveToNext()) { if (TextUtils.equals(tzCursor.getString(keyColumn), CalendarCache.TIMEZONE_KEY_INSTANCES)) { tz = tzCursor.getString(valueColumn); } } } if (tz == null) { tz = Time.getCurrentTimezone(); } } finally { if (tzCursor != null) { tzCursor.close(); } } return tz; } @VisibleForTesting protected static CalendarAppWidgetModel buildAppWidgetModel( Context context, Cursor cursor, String timeZone) { CalendarAppWidgetModel model = new CalendarAppWidgetModel(context); model.buildFromCursor(cursor, timeZone); return model; } /** * Calculates and returns the next time we should push widget updates. */ private long calculateUpdateTime(CalendarAppWidgetModel model, long now) { // Make sure an update happens at midnight or earlier long minUpdateTime = getNextMidnightTimeMillis(); for (EventInfo event : model.mEventInfos) { final boolean allDay = event.allDay; final long start; final long end; if (allDay) { // Adjust all-day times into local timezone final Time recycle = new Time(); start = Utils.convertUtcToLocal(recycle, event.start); end = Utils.convertUtcToLocal(recycle, event.end); } else { start = event.start; end = event.end; } // We want to update widget when we enter/exit time range of an event. if (now < start) { minUpdateTime = Math.min(minUpdateTime, start); } else if (now < end) { minUpdateTime = Math.min(minUpdateTime, end); } } return minUpdateTime; } private static long getNextMidnightTimeMillis() { Time time = new Time(); time.setToNow(); time.monthDay++; time.hour = 0; time.minute = 0; time.second = 0; long midnight = time.normalize(true); return midnight; } static void updateTextView(RemoteViews views, int id, int visibility, String string) { views.setViewVisibility(id, visibility); if (visibility == View.VISIBLE) { views.setTextViewText(id, string); } } } /** * Format given time for debugging output. * * @param unixTime Target time to report. * @param now Current system time from {@link System#currentTimeMillis()} * for calculating time difference. */ static String formatDebugTime(long unixTime, long now) { Time time = new Time(); time.set(unixTime); long delta = unixTime - now; if (delta > DateUtils.MINUTE_IN_MILLIS) { delta /= DateUtils.MINUTE_IN_MILLIS; return String.format("[%d] %s (%+d mins)", unixTime, time.format("%H:%M:%S"), delta); } else { delta /= DateUtils.SECOND_IN_MILLIS; return String.format("[%d] %s (%+d secs)", unixTime, time.format("%H:%M:%S"), delta); } } }
true
true
public RemoteViews getViewAt(int position) { // we use getCount here so that it doesn't return null when empty if (position < 0 || position >= getCount()) { return null; } if (mModel.mEventInfos.isEmpty() || mModel.mRowInfos.isEmpty()) { RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_no_events); final Intent intent = CalendarAppWidgetProvider.getLaunchFillInIntent(0); views.setOnClickFillInIntent(R.id.appwidget_no_events, intent); return views; } RowInfo rowInfo = mModel.mRowInfos.get(position); if (rowInfo.mType == RowInfo.TYPE_DAY) { RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_day); DayInfo dayInfo = mModel.mDayInfos.get(rowInfo.mIndex); updateTextView(views, R.id.date, View.VISIBLE, dayInfo.mDayLabel); return views; } else { final RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_row); final EventInfo eventInfo = mModel.mEventInfos.get(rowInfo.mIndex); final long now = System.currentTimeMillis(); if (!eventInfo.allDay && eventInfo.start <= now && now <= eventInfo.end) { views.setInt(R.id.appwidget_row, "setBackgroundColor", mResources.getColor(R.color.appwidget_row_in_progress)); } updateTextView(views, R.id.when, eventInfo.visibWhen, eventInfo.when); updateTextView(views, R.id.where, eventInfo.visibWhere, eventInfo.where); updateTextView(views, R.id.title, eventInfo.visibTitle, eventInfo.title); views.setViewVisibility(R.id.color, View.VISIBLE); views.setInt(R.id.color, "setBackgroundColor", eventInfo.color); // An element in ListView. final Intent fillInIntent = CalendarAppWidgetProvider.getLaunchFillInIntent(eventInfo.start); views.setOnClickFillInIntent(R.id.appwidget_row, fillInIntent); return views; } }
public RemoteViews getViewAt(int position) { // we use getCount here so that it doesn't return null when empty if (position < 0 || position >= getCount()) { return null; } if (mModel.mEventInfos.isEmpty() || mModel.mRowInfos.isEmpty()) { RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_no_events); final Intent intent = CalendarAppWidgetProvider.getLaunchFillInIntent(0); views.setOnClickFillInIntent(R.id.appwidget_no_events, intent); return views; } RowInfo rowInfo = mModel.mRowInfos.get(position); if (rowInfo.mType == RowInfo.TYPE_DAY) { RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_day); DayInfo dayInfo = mModel.mDayInfos.get(rowInfo.mIndex); updateTextView(views, R.id.date, View.VISIBLE, dayInfo.mDayLabel); return views; } else { final RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.appwidget_row); final EventInfo eventInfo = mModel.mEventInfos.get(rowInfo.mIndex); final long now = System.currentTimeMillis(); if (!eventInfo.allDay && eventInfo.start <= now && now <= eventInfo.end) { views.setInt(R.id.appwidget_row, "setBackgroundColor", mResources.getColor(R.color.appwidget_row_in_progress)); } else { views.setInt(R.id.appwidget_row, "setBackgroundColor", mResources.getColor(R.color.appwidget_row_default)); } updateTextView(views, R.id.when, eventInfo.visibWhen, eventInfo.when); updateTextView(views, R.id.where, eventInfo.visibWhere, eventInfo.where); updateTextView(views, R.id.title, eventInfo.visibTitle, eventInfo.title); views.setViewVisibility(R.id.color, View.VISIBLE); views.setInt(R.id.color, "setBackgroundColor", eventInfo.color); // An element in ListView. final Intent fillInIntent = CalendarAppWidgetProvider.getLaunchFillInIntent(eventInfo.start); views.setOnClickFillInIntent(R.id.appwidget_row, fillInIntent); return views; } }
diff --git a/src/main/java/net/pterodactylus/sone/freenet/wot/IdentityManager.java b/src/main/java/net/pterodactylus/sone/freenet/wot/IdentityManager.java index dbf42065..aac5cd86 100644 --- a/src/main/java/net/pterodactylus/sone/freenet/wot/IdentityManager.java +++ b/src/main/java/net/pterodactylus/sone/freenet/wot/IdentityManager.java @@ -1,308 +1,308 @@ /* * Sone - IdentityManager.java - Copyright © 2010 David Roden * * 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 net.pterodactylus.sone.freenet.wot; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import net.pterodactylus.sone.freenet.plugin.PluginException; import net.pterodactylus.util.logging.Logging; import net.pterodactylus.util.service.AbstractService; /** * The identity manager takes care of loading and storing identities, their * contexts, and properties. It does so in a way that does not expose errors via * exceptions but it only logs them and tries to return sensible defaults. * <p> * It is also responsible for polling identities from the Web of Trust plugin * and notifying registered {@link IdentityListener}s when {@link Identity}s and * {@link OwnIdentity}s are discovered or disappearing. * * @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a> */ public class IdentityManager extends AbstractService { /** Object used for synchronization. */ private final Object syncObject = new Object() { /* inner class for better lock names. */ }; /** The logger. */ private static final Logger logger = Logging.getLogger(IdentityManager.class); /** The event manager. */ private final IdentityListenerManager identityListenerManager = new IdentityListenerManager(); /** The Web of Trust connector. */ private final WebOfTrustConnector webOfTrustConnector; /** The context to filter for. */ private volatile String context; /** The currently known own identities. */ /* synchronize access on syncObject. */ private Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>(); /** * Creates a new identity manager. * * @param webOfTrustConnector * The Web of Trust connector */ public IdentityManager(WebOfTrustConnector webOfTrustConnector) { super("Sone Identity Manager", false); this.webOfTrustConnector = webOfTrustConnector; } // // LISTENER MANAGEMENT // /** * Adds a listener for identity events. * * @param identityListener * The listener to add */ public void addIdentityListener(IdentityListener identityListener) { identityListenerManager.addListener(identityListener); } /** * Removes a listener for identity events. * * @param identityListener * The listener to remove */ public void removeIdentityListener(IdentityListener identityListener) { identityListenerManager.removeListener(identityListener); } // // ACCESSORS // /** * Sets the context to filter own identities and trusted identities for. * * @param context * The context to filter for, or {@code null} to not filter */ public void setContext(String context) { this.context = context; } /** * Returns whether the Web of Trust plugin could be reached during the last * try. * * @return {@code true} if the Web of Trust plugin is connected, * {@code false} otherwise */ public boolean isConnected() { try { webOfTrustConnector.ping(); return true; } catch (PluginException pe1) { /* not connected, ignore. */ return false; } } /** * Returns the own identity with the given ID. * * @param id * The ID of the own identity * @return The own identity, or {@code null} if there is no such identity */ public OwnIdentity getOwnIdentity(String id) { Set<OwnIdentity> allOwnIdentities = getAllOwnIdentities(); for (OwnIdentity ownIdentity : allOwnIdentities) { if (ownIdentity.getId().equals(id)) { return ownIdentity; } } return null; } /** * Returns all own identities. * * @return All own identities */ public Set<OwnIdentity> getAllOwnIdentities() { try { Set<OwnIdentity> ownIdentities = webOfTrustConnector.loadAllOwnIdentities(); Map<String, OwnIdentity> newOwnIdentities = new HashMap<String, OwnIdentity>(); for (OwnIdentity ownIdentity : ownIdentities) { newOwnIdentities.put(ownIdentity.getId(), ownIdentity); } checkOwnIdentities(newOwnIdentities); return ownIdentities; } catch (WebOfTrustException wote1) { logger.log(Level.WARNING, "Could not load all own identities!", wote1); return Collections.emptySet(); } } // // SERVICE METHODS // /** * {@inheritDoc} */ @Override protected void serviceRun() { Map<OwnIdentity, Map<String, Identity>> oldIdentities = Collections.emptyMap(); while (!shouldStop()) { Map<OwnIdentity, Map<String, Identity>> currentIdentities = new HashMap<OwnIdentity, Map<String, Identity>>(); Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>(); try { /* get all identities with the wanted context from WoT. */ Set<OwnIdentity> ownIdentities = webOfTrustConnector.loadAllOwnIdentities(); /* check for changes. */ for (OwnIdentity ownIdentity : ownIdentities) { currentOwnIdentities.put(ownIdentity.getId(), ownIdentity); } checkOwnIdentities(currentOwnIdentities); /* now filter for context and get all identities. */ for (OwnIdentity ownIdentity : ownIdentities) { if ((context != null) && !ownIdentity.hasContext(context)) { continue; } Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context); Map<String, Identity> identities = new HashMap<String, Identity>(); currentIdentities.put(ownIdentity, identities); for (Identity identity : trustedIdentities) { identities.put(identity.getId(), identity); } /* find new identities. */ - for (Identity currentIdentity : currentIdentities.get(ownIdentities).values()) { - if (!oldIdentities.containsKey(currentIdentity.getId())) { + for (Identity currentIdentity : currentIdentities.get(ownIdentity).values()) { + if (!oldIdentities.containsKey(ownIdentity) || !oldIdentities.get(ownIdentity).containsKey(currentIdentity.getId())) { identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity); } } /* find removed identities. */ if (oldIdentities.containsKey(ownIdentity)) { - for (Identity oldIdentity : oldIdentities.get(ownIdentities).values()) { + for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) { if (!currentIdentities.containsKey(oldIdentity.getId())) { identityListenerManager.fireIdentityRemoved(ownIdentity, oldIdentity); } } /* check for changes in the contexts. */ for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) { if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) { continue; } Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId()); Set<String> oldContexts = oldIdentity.getContexts(); Set<String> newContexts = newIdentity.getContexts(); if (oldContexts.size() != newContexts.size()) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); continue; } for (String oldContext : oldContexts) { if (!newContexts.contains(oldContext)) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); break; } } } /* check for changes in the properties. */ for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) { if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) { continue; } Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId()); Map<String, String> oldProperties = oldIdentity.getProperties(); Map<String, String> newProperties = newIdentity.getProperties(); if (oldProperties.size() != newProperties.size()) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); continue; } for (Entry<String, String> oldProperty : oldProperties.entrySet()) { if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); break; } } } } /* remember the current set of identities. */ oldIdentities = currentIdentities; } } catch (WebOfTrustException wote1) { logger.log(Level.WARNING, "WoT has disappeared!", wote1); } /* wait a minute before checking again. */ sleep(60 * 1000); } } // // PRIVATE METHODS // /** * Checks the given new list of own identities for added or removed own * identities, as compared to {@link #currentOwnIdentities}. * * @param newOwnIdentities * The new own identities */ private void checkOwnIdentities(Map<String, OwnIdentity> newOwnIdentities) { synchronized (syncObject) { /* find removed own identities: */ for (OwnIdentity oldOwnIdentity : currentOwnIdentities.values()) { if (!newOwnIdentities.containsKey(oldOwnIdentity.getId())) { identityListenerManager.fireOwnIdentityRemoved(oldOwnIdentity); } } /* find added own identities. */ for (OwnIdentity currentOwnIdentity : newOwnIdentities.values()) { if (!currentOwnIdentities.containsKey(currentOwnIdentity.getId())) { identityListenerManager.fireOwnIdentityAdded(currentOwnIdentity); } } currentOwnIdentities.clear(); currentOwnIdentities.putAll(newOwnIdentities); } } }
false
true
protected void serviceRun() { Map<OwnIdentity, Map<String, Identity>> oldIdentities = Collections.emptyMap(); while (!shouldStop()) { Map<OwnIdentity, Map<String, Identity>> currentIdentities = new HashMap<OwnIdentity, Map<String, Identity>>(); Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>(); try { /* get all identities with the wanted context from WoT. */ Set<OwnIdentity> ownIdentities = webOfTrustConnector.loadAllOwnIdentities(); /* check for changes. */ for (OwnIdentity ownIdentity : ownIdentities) { currentOwnIdentities.put(ownIdentity.getId(), ownIdentity); } checkOwnIdentities(currentOwnIdentities); /* now filter for context and get all identities. */ for (OwnIdentity ownIdentity : ownIdentities) { if ((context != null) && !ownIdentity.hasContext(context)) { continue; } Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context); Map<String, Identity> identities = new HashMap<String, Identity>(); currentIdentities.put(ownIdentity, identities); for (Identity identity : trustedIdentities) { identities.put(identity.getId(), identity); } /* find new identities. */ for (Identity currentIdentity : currentIdentities.get(ownIdentities).values()) { if (!oldIdentities.containsKey(currentIdentity.getId())) { identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity); } } /* find removed identities. */ if (oldIdentities.containsKey(ownIdentity)) { for (Identity oldIdentity : oldIdentities.get(ownIdentities).values()) { if (!currentIdentities.containsKey(oldIdentity.getId())) { identityListenerManager.fireIdentityRemoved(ownIdentity, oldIdentity); } } /* check for changes in the contexts. */ for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) { if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) { continue; } Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId()); Set<String> oldContexts = oldIdentity.getContexts(); Set<String> newContexts = newIdentity.getContexts(); if (oldContexts.size() != newContexts.size()) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); continue; } for (String oldContext : oldContexts) { if (!newContexts.contains(oldContext)) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); break; } } } /* check for changes in the properties. */ for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) { if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) { continue; } Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId()); Map<String, String> oldProperties = oldIdentity.getProperties(); Map<String, String> newProperties = newIdentity.getProperties(); if (oldProperties.size() != newProperties.size()) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); continue; } for (Entry<String, String> oldProperty : oldProperties.entrySet()) { if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); break; } } } } /* remember the current set of identities. */ oldIdentities = currentIdentities; } } catch (WebOfTrustException wote1) { logger.log(Level.WARNING, "WoT has disappeared!", wote1); } /* wait a minute before checking again. */ sleep(60 * 1000); } }
protected void serviceRun() { Map<OwnIdentity, Map<String, Identity>> oldIdentities = Collections.emptyMap(); while (!shouldStop()) { Map<OwnIdentity, Map<String, Identity>> currentIdentities = new HashMap<OwnIdentity, Map<String, Identity>>(); Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>(); try { /* get all identities with the wanted context from WoT. */ Set<OwnIdentity> ownIdentities = webOfTrustConnector.loadAllOwnIdentities(); /* check for changes. */ for (OwnIdentity ownIdentity : ownIdentities) { currentOwnIdentities.put(ownIdentity.getId(), ownIdentity); } checkOwnIdentities(currentOwnIdentities); /* now filter for context and get all identities. */ for (OwnIdentity ownIdentity : ownIdentities) { if ((context != null) && !ownIdentity.hasContext(context)) { continue; } Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context); Map<String, Identity> identities = new HashMap<String, Identity>(); currentIdentities.put(ownIdentity, identities); for (Identity identity : trustedIdentities) { identities.put(identity.getId(), identity); } /* find new identities. */ for (Identity currentIdentity : currentIdentities.get(ownIdentity).values()) { if (!oldIdentities.containsKey(ownIdentity) || !oldIdentities.get(ownIdentity).containsKey(currentIdentity.getId())) { identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity); } } /* find removed identities. */ if (oldIdentities.containsKey(ownIdentity)) { for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) { if (!currentIdentities.containsKey(oldIdentity.getId())) { identityListenerManager.fireIdentityRemoved(ownIdentity, oldIdentity); } } /* check for changes in the contexts. */ for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) { if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) { continue; } Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId()); Set<String> oldContexts = oldIdentity.getContexts(); Set<String> newContexts = newIdentity.getContexts(); if (oldContexts.size() != newContexts.size()) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); continue; } for (String oldContext : oldContexts) { if (!newContexts.contains(oldContext)) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); break; } } } /* check for changes in the properties. */ for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) { if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) { continue; } Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId()); Map<String, String> oldProperties = oldIdentity.getProperties(); Map<String, String> newProperties = newIdentity.getProperties(); if (oldProperties.size() != newProperties.size()) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); continue; } for (Entry<String, String> oldProperty : oldProperties.entrySet()) { if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) { identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity); break; } } } } /* remember the current set of identities. */ oldIdentities = currentIdentities; } } catch (WebOfTrustException wote1) { logger.log(Level.WARNING, "WoT has disappeared!", wote1); } /* wait a minute before checking again. */ sleep(60 * 1000); } }
diff --git a/dev/core/src/com/google/gwt/soyc/MakeTopLevelHtmlForPerm.java b/dev/core/src/com/google/gwt/soyc/MakeTopLevelHtmlForPerm.java index 298192cc1..1a170c293 100644 --- a/dev/core/src/com/google/gwt/soyc/MakeTopLevelHtmlForPerm.java +++ b/dev/core/src/com/google/gwt/soyc/MakeTopLevelHtmlForPerm.java @@ -1,916 +1,916 @@ /* * Copyright 2008 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.gwt.soyc; import com.google.gwt.dev.util.Util; import com.google.gwt.soyc.io.OutputDirectory; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A utility to make the top level HTTML file for one permutation. */ public class MakeTopLevelHtmlForPerm { /** * A dependency linker for the initial code download. It links to the * dependencies for the initial download. */ public class DependencyLinkerForInitialCode implements DependencyLinker { public String dependencyLinkForClass(String className) { String packageName = globalInformation.getClassToPackage().get(className); assert packageName != null; return dependenciesFileName("initial", packageName) + "#" + className; } } /** * A dependency linker for the leftovers fragment. It links to leftovers * status pages. */ public class DependencyLinkerForLeftoversFragment implements DependencyLinker { public String dependencyLinkForClass(String className) { return leftoversStatusFileName(className); } } /** * A dependency linker for the total program breakdown. It links to a split * status page. * */ public class DependencyLinkerForTotalBreakdown implements DependencyLinker { public String dependencyLinkForClass(String className) { return splitStatusFileName(className); } } /** * A dependency linker that never links to anything. */ public static class NullDependencyLinker implements DependencyLinker { public String dependencyLinkForClass(String className) { return null; } } interface DependencyLinker { String dependencyLinkForClass(String className); } /** * By a convention shared with the compiler, the initial download is fragment * number 0. */ private static final int FRAGMENT_NUMBER_INITIAL_DOWNLOAD = 0; /** * Just within this file, the convention is that the total program is fragment * number -1. */ private static final int FRAGMENT_NUMBER_TOTAL_PROGRAM = -1; /** * A pattern describing the name of dependency graphs for code fragments * corresponding to a specific split point. These can be either exclusive * fragments or fragments of code for split points in the initial load * sequence. */ private static final Pattern PATTERN_SP_INT = Pattern.compile("sp([0-9]+)"); private static String escapeXml(String unescaped) { String escaped = unescaped.replaceAll("\\&", "&amp;"); escaped = escaped.replaceAll("\\<", "&lt;"); escaped = escaped.replaceAll("\\>", "&gt;"); escaped = escaped.replaceAll("\\\"", "&quot;"); escaped = escaped.replaceAll("\\'", "&apos;"); return escaped; } public static void makeTopLevelHtmlForAllPerms( Map<String, String> allPermsInfo, OutputDirectory outDir) throws IOException { PrintWriter outFile = new PrintWriter(outDir.getOutputStream("index.html")); addStandardHtmlProlog(outFile, "Compile report", "Compile report", "Overview of permutations"); outFile.println("<ul>"); for (String permutationId : allPermsInfo.keySet()) { String permutationInfo = allPermsInfo.get(permutationId); outFile.print("<li><a href=\"SoycDashboard" + "-" + permutationId + "-index.html\">Permutation " + permutationId); if (permutationInfo.length() > 0) { outFile.println(" (" + permutationInfo + ")" + "</a></li>"); } else { outFile.println("</a>"); } } outFile.println("</ul>"); addStandardHtmlEnding(outFile); outFile.close(); } private static void addSmallHtmlProlog(final PrintWriter outFile, String title) { outFile.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\""); outFile.println("\"http://www.w3.org/TR/html4/strict.dtd\">"); outFile.println("<html>"); outFile.println("<head>"); outFile.println("<title>"); outFile.println(title); outFile.println("</title>"); outFile.println("<style type=\"text/css\" media=\"screen\">"); outFile.println("@import url('goog.css');"); outFile.println("@import url('inlay.css');"); outFile.println("@import url('soyc.css');"); outFile.println("</style>"); outFile.println("</head>"); } private static void addStandardHtmlEnding(final PrintWriter out) { out.println("</div>"); out.println("</body>"); out.println("</html>"); } private static void addStandardHtmlProlog(final PrintWriter outFile, String title, String header1, String header2) { outFile.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\""); outFile.println("\"http://www.w3.org/TR/html4/strict.dtd\">"); outFile.println("<html>"); outFile.println("<head>"); outFile.println("<title>"); outFile.println(title); outFile.println("</title>"); outFile.println("<style type=\"text/css\" media=\"screen\">"); outFile.println("@import url('goog.css');"); outFile.println("@import url('inlay.css');"); outFile.println("@import url('soyc.css');"); outFile.println("</style>"); outFile.println("</head>"); outFile.println("<body>"); outFile.println("<div class=\"g-doc\">"); outFile.println("<div id=\"hd\" class=\"g-section g-tpl-50-50 g-split\">"); outFile.println("<div class=\"g-unit g-first\">"); outFile.println("<p>"); outFile.println("<a href=\"index.html\" id=\"gwt-logo\" class=\"soyc-ir\"><span>Google Web Toolkit</span></a>"); outFile.println("</p>"); outFile.println("</div>"); outFile.println("<div class=\"g-unit\">"); outFile.println("</div>"); outFile.println("</div>"); outFile.println("<div id=\"soyc-appbar-lrg\">"); outFile.println("<div class=\"g-section g-tpl-75-25 g-split\">"); outFile.println("<div class=\"g-unit g-first\">"); outFile.println("<h1>" + header1 + "</h1>"); outFile.println("</div>"); outFile.println("<div class=\"g-unit\"></div>"); outFile.println("</div>"); outFile.println("</div>"); outFile.println("<div id=\"bd\">"); outFile.println("<h2>" + header2 + "</h2>"); } private static String classesInPackageFileName(SizeBreakdown breakdown, String packageName, String permutationId) { return breakdown.getId() + "_" + filename(packageName) + "-" + permutationId + "_Classes.html"; } /** * Convert a potentially long string into a short file name. The current * implementation simply hashes the long name. */ private static String filename(String longFileName) { try { return Util.computeStrongName(longFileName.getBytes(Util.DEFAULT_ENCODING)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private static String headerLineForBreakdown(SizeBreakdown breakdown) { return "(Analyzing code subset: " + breakdown.getDescription() + ")"; } private static String shellFileName(SizeBreakdown breakdown, String permutationId) { return breakdown.getId() + "-" + permutationId + "-overallBreakdown.html"; } /** * Global information for this permutation. */ private final GlobalInformation globalInformation; private final OutputDirectory outDir; MakeTopLevelHtmlForPerm(GlobalInformation globalInformation, OutputDirectory outDir) { this.globalInformation = globalInformation; this.outDir = outDir; } public void makeBreakdownShell(SizeBreakdown breakdown) throws IOException { Map<String, CodeCollection> nameToCodeColl = breakdown.nameToCodeColl; Map<String, LiteralsCollection> nameToLitColl = breakdown.nameToLitColl; String packageBreakdownFileName = makePackageHtml(breakdown); String codeTypeBreakdownFileName = makeCodeTypeHtml(breakdown, nameToCodeColl, nameToLitColl); PrintWriter outFile = new PrintWriter(getOutFile(shellFileName(breakdown, getPermutationId()))); addStandardHtmlProlog(outFile, "Application breakdown analysis", "Application breakdown analysis", ""); outFile.println("<div id=\"bd\"> "); outFile.println("<h2>Package breakdown</h2>"); outFile.println("<iframe class='soyc-iframe-package' src=\"" + packageBreakdownFileName + "\" scrolling=auto></iframe>"); outFile.println("<h2>Code type breakdown</h2>"); outFile.println("<iframe class='soyc-iframe-code' src=\"" + codeTypeBreakdownFileName + "\" scrolling=auto></iframe>"); outFile.println("</div>"); addStandardHtmlEnding(outFile); outFile.close(); } public void makeCodeTypeClassesHtmls(SizeBreakdown breakdown) throws IOException { HashMap<String, CodeCollection> nameToCodeColl = breakdown.nameToCodeColl; for (String codeType : nameToCodeColl.keySet()) { // construct file name String outFileName = breakdown.getId() + "_" + codeType + "-" + getPermutationId() + "Classes.html"; float sumSize = 0f; TreeMap<Float, String> sortedClasses = new TreeMap<Float, String>( Collections.reverseOrder()); for (String className : nameToCodeColl.get(codeType).classes) { if (breakdown.classToSize.containsKey(className)) { float curSize = 0f; if (breakdown.classToSize.containsKey(className)) { curSize = breakdown.classToSize.get(className); } if (curSize != 0f) { sortedClasses.put(curSize, className); sumSize += curSize; } } } final PrintWriter outFile = new PrintWriter(getOutFile(outFileName)); addStandardHtmlProlog(outFile, "Classes in package " + codeType, "Classes in package " + codeType, headerLineForBreakdown(breakdown)); outFile.println("<table class=\"soyc-table\">"); outFile.println("<colgroup>"); outFile.println("<col id=\"soyc-splitpoint-type-col\">"); outFile.println("<col id=\"soyc-splitpoint-size-col\">"); outFile.println("</colgroup>"); outFile.println("<thead>"); outFile.println("<th>Code type</th>"); outFile.println("<th>Size <span class=\"soyc-th-units\">Bytes (% All Code)</span></th>"); outFile.println("</thead>"); for (Float size : sortedClasses.keySet()) { String className = sortedClasses.get(size); float perc = (size / sumSize) * 100; outFile.println("<tr>"); outFile.println("<td>" + className + "</a></td>"); outFile.println("<td>"); outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">"); outFile.println("<div style=\"width:" + perc + "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>"); outFile.println("</div>"); outFile.println(size + " (" + formatNumber(perc) + "%)"); outFile.println("</td>"); outFile.println("</tr>"); } addStandardHtmlEnding(outFile); outFile.close(); } } public void makeDependenciesHtml() throws IOException { for (String depGraphName : globalInformation.dependencies.keySet()) { makeDependenciesHtml(depGraphName, globalInformation.dependencies.get(depGraphName)); } } public void makeLeftoverStatusPages() throws IOException { for (String className : globalInformation.getClassToPackage().keySet()) { makeLeftoversStatusPage(className); } } public void makeLiteralsClassesTableHtmls(SizeBreakdown breakdown) throws IOException { Map<String, LiteralsCollection> nameToLitColl = breakdown.nameToLitColl; for (String literalType : nameToLitColl.keySet()) { String outFileName = literalType + "-" + getPermutationId() + "Lits.html"; final PrintWriter outFile = new PrintWriter(getOutFile(breakdown.getId() + "_" + outFileName)); addStandardHtmlProlog(outFile, "Literals of type " + literalType, "Literals of type " + literalType, headerLineForBreakdown(breakdown)); outFile.println("<table width=\"80%\" style=\"font-size: 11pt;\" bgcolor=\"white\">"); for (String literal : nameToLitColl.get(literalType).literals) { if (literal.trim().length() == 0) { literal = "[whitespace only string]"; } String escliteral = escapeXml(literal); outFile.println("<tr>"); outFile.println("<td>" + escliteral + "</td>"); outFile.println("</tr>"); } outFile.println("</table>"); outFile.println("<center>"); addStandardHtmlEnding(outFile); outFile.close(); } } /** * Make size breakdowns for each package for one code collection. */ public void makePackageClassesHtmls(SizeBreakdown breakdown, DependencyLinker depLinker) throws IOException { for (String packageName : globalInformation.getPackageToClasses().keySet()) { TreeMap<Float, String> sortedClasses = new TreeMap<Float, String>( Collections.reverseOrder()); float sumSize = 0f; for (String className : globalInformation.getPackageToClasses().get( packageName)) { float curSize = 0f; if (!breakdown.classToSize.containsKey(className)) { // This class not present in this code collection } else { curSize = breakdown.classToSize.get(className); } if (curSize != 0f) { sumSize += curSize; sortedClasses.put(curSize, className); } } PrintWriter outFile = new PrintWriter( getOutFile(classesInPackageFileName(breakdown, packageName, getPermutationId()))); addStandardHtmlProlog(outFile, "Classes in package " + packageName, "Classes in package " + packageName, headerLineForBreakdown(breakdown)); outFile.println("<table class=\"soyc-table\">"); outFile.println("<colgroup>"); outFile.println("<col id=\"soyc-splitpoint-type-col\">"); outFile.println("<col id=\"soyc-splitpoint-size-col\">"); outFile.println("</colgroup>"); outFile.println("<thead>"); outFile.println("<th>Package</th>"); outFile.println("<th>Size <span class=\"soyc-th-units\">Bytes (% All Code)</span></th>"); outFile.println("</thead>"); for (Float size : sortedClasses.keySet()) { String className = sortedClasses.get(size); String drillDownFileName = depLinker.dependencyLinkForClass(className); float perc = (size / sumSize) * 100; outFile.println("<tr>"); if (drillDownFileName == null) { outFile.println("<td>" + className + "</td>"); } else { outFile.println("<td><a href=\"" + drillDownFileName + "\" target=\"_top\">" + className + "</a></td>"); } outFile.println("<td>"); outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">"); outFile.println("<div style=\"width:" + perc + "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>"); outFile.println("</div>"); outFile.println(size + " (" + formatNumber(perc) + "%)"); outFile.println("</td>"); outFile.println("</tr>"); } outFile.println("</table>"); addStandardHtmlEnding(outFile); outFile.close(); } } public void makeSplitStatusPages() throws IOException { for (String className : globalInformation.getClassToPackage().keySet()) { makeSplitStatusPage(className); } } public void makeTopLevelShell() throws IOException { String permutationId = getPermutationId(); PrintWriter outFile = new PrintWriter(getOutFile("SoycDashboard" + "-" + getPermutationId() + "-index.html")); addStandardHtmlProlog(outFile, "Compile report: Permutation " + permutationId, "Compile report: Permutation " + permutationId, ""); outFile.println("<div id=\"bd\">"); outFile.println("<div id=\"soyc-summary\" class=\"g-section\">"); outFile.println("<dl>"); outFile.println("<dt>Full code size</dt>"); outFile.println("<dd class=\"value\">" - + globalInformation.getInitialCodeBreakdown().sizeAllCode + + globalInformation.getTotalCodeBreakdown().sizeAllCode + " Bytes</dd>"); outFile.println("<dd class=\"report\"><a href=\"total-" + permutationId + "-overallBreakdown.html\">Report</a></dd>"); outFile.println("</dl>"); outFile.println("<dl>"); outFile.println("<dt>Initial download size</dt>"); // TODO(kprobst) -- add percentage here: (48%)</dd>"); outFile.println("<dd class=\"value\">" - + globalInformation.getTotalCodeBreakdown().sizeAllCode + " Bytes</dd>"); + + globalInformation.getInitialCodeBreakdown().sizeAllCode + " Bytes</dd>"); outFile.println("<dd class=\"report\"><a href=\"initial-" + permutationId + "-overallBreakdown.html\">Report</a></dd>"); outFile.println("</dl>"); outFile.println("<dl>"); outFile.println("<dt>Left over code</dt>"); outFile.println("<dd class=\"value\">" + globalInformation.getLeftoversBreakdown().sizeAllCode + " Bytes</dd>"); outFile.println("<dd class=\"report\"><a href=\"leftovers-" + permutationId + "-overallBreakdown.html\">Report</a></dd>"); outFile.println("</dl>"); outFile.println("</div>"); outFile.println("<table id=\"soyc-table-splitpoints\" class=\"soyc-table\">"); outFile.println("<caption>"); outFile.println("<strong>Split Points</strong>"); outFile.println("</caption>"); outFile.println("<colgroup>"); outFile.println("<col id=\"soyc-splitpoint-number-col\">"); outFile.println("<col id=\"soyc-splitpoint-location-col\">"); outFile.println("<col id=\"soyc-splitpoint-size-col\">"); outFile.println("</colgroup>"); outFile.println("<thead>"); outFile.println("<th>#</th>"); outFile.println("<th>Location</th>"); outFile.println("<th>Size</th>"); outFile.println("</thead>"); outFile.println("<tbody>"); - if (globalInformation.getSplitPointToLocation().size() > 1) { + if (globalInformation.getSplitPointToLocation().size() >= 1) { int numSplitPoints = globalInformation.getSplitPointToLocation().size(); float maxSize = globalInformation.getTotalCodeBreakdown().sizeAllCode; for (int i = FRAGMENT_NUMBER_TOTAL_PROGRAM; i <= numSplitPoints + 1; i++) { SizeBreakdown breakdown; if (i == FRAGMENT_NUMBER_TOTAL_PROGRAM) { continue; } else if (i == numSplitPoints + 1) { // leftovers continue; } else if (i == FRAGMENT_NUMBER_INITIAL_DOWNLOAD) { continue; } else { breakdown = globalInformation.splitPointCodeBreakdown(i); } String drillDownFileName = shellFileName(breakdown, getPermutationId()); String splitPointDescription = globalInformation.getSplitPointToLocation().get( i); float size = breakdown.sizeAllCode; float ratio; ratio = (size / maxSize) * 100; outFile.println("<tr>"); outFile.println("<td>" + i + "</td>"); outFile.println("<td><a href=\"" + drillDownFileName + "\">" + splitPointDescription + "</a></td>"); outFile.println("<td>"); outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">"); outFile.println("<div style=\"width:" + ratio + "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>"); outFile.println("</div>"); outFile.println((int) size + " Bytes (" + formatNumber(ratio) + "%)"); outFile.println("</td>"); outFile.println("</tr>"); } } outFile.println("</tbody>"); outFile.println("</table>"); outFile.println("</div>"); addStandardHtmlEnding(outFile); outFile.close(); } private void addLefttoversStatus(String className, String packageName, PrintWriter outFile) { outFile.println("<ul class=\"soyc-exclusive\">"); if (globalInformation.dependencies != null) { outFile.println("<li><a href=\"" + dependenciesFileName("total", packageName) + "#" + className + "\">See why it's live</a></li>"); for (int sp = 1; sp <= globalInformation.getNumSplitPoints(); sp++) { outFile.println("<li><a href=\"" + dependenciesFileName("sp" + sp, packageName) + "#" + className + "\">See why it's not exclusive to s.p. #" + sp + " (" + globalInformation.getSplitPointToLocation().get(sp) + ")</a></li>"); } } outFile.println("</ul>"); } /** * Returns a file name for the dependencies list. */ private String dependenciesFileName(String depGraphName, String packageName) { return "methodDependencies-" + depGraphName + "-" + filename(packageName) + "-" + getPermutationId() + ".html"; } /** * Format floating point number to two decimal points. * * @param number * @return formatted number */ private String formatNumber(float number) { DecimalFormat formatBy = new DecimalFormat("#.##"); return formatBy.format(number); } /** * Return a {@link File} object for a file to be emitted into the output * directory. */ private OutputStream getOutFile(String localFileName) throws IOException { return outDir.getOutputStream(localFileName); } /** * @return the ID for the current permutation */ private String getPermutationId() { return globalInformation.getPermutationId(); } /** * Describe the code covered by the dependency graph with the supplied name. */ private String inferDepGraphDescription(String depGraphName) { if (depGraphName.equals("initial")) { return "Initially Live Code"; } if (depGraphName.equals("total")) { return "All Code"; } Matcher matcher = PATTERN_SP_INT.matcher(depGraphName); if (matcher.matches()) { int splitPoint = Integer.valueOf(matcher.group(1)); if (isInitialSplitPoint(splitPoint)) { return "Code Becoming Live at Split Point " + splitPoint; } else { return "Code not Exclusive to Split Point " + splitPoint; } } throw new RuntimeException("Unexpected dependency graph name: " + depGraphName); } /** * Returns whether a split point is initial or not. * * @param splitPoint * @returns true of the split point is initial, false otherwise */ private boolean isInitialSplitPoint(int splitPoint) { return globalInformation.getSplitPointInitialLoadSequence().contains( splitPoint); } /** * Makes a file name for a leftovers status file. * * @param className * @return the file name of the leftovers status file */ private String leftoversStatusFileName(String className) { return "leftoverStatus-" + filename(className) + "-" + getPermutationId() + ".html"; } /** * Produces an HTML file that breaks down by code type. * * @param breakdown * @param nameToCodeColl * @param nameToLitColl * @return the name of the produced file * @throws IOException */ private String makeCodeTypeHtml(SizeBreakdown breakdown, Map<String, CodeCollection> nameToCodeColl, Map<String, LiteralsCollection> nameToLitColl) throws IOException { String outFileName = breakdown.getId() + "-" + getPermutationId() + "-codeTypeBreakdown.html"; float sumSize = 0f; TreeMap<Float, String> sortedCodeTypes = new TreeMap<Float, String>( Collections.reverseOrder()); for (String codeType : nameToCodeColl.keySet()) { float curSize = nameToCodeColl.get(codeType).getCumPartialSize(breakdown); sumSize += curSize; if (curSize != 0f) { sortedCodeTypes.put(curSize, codeType); } } final PrintWriter outFile = new PrintWriter(getOutFile(outFileName)); addSmallHtmlProlog(outFile, "Code breakdown"); outFile.println("<body class=\"soyc-breakdown\">"); outFile.println("<div class=\"g-doc\">"); outFile.println("<table class=\"soyc-table\">"); outFile.println("<colgroup>"); outFile.println("<col id=\"soyc-splitpoint-type-col\">"); outFile.println("<col id=\"soyc-splitpoint-size-col\">"); outFile.println("</colgroup>"); outFile.println("<thead>"); outFile.println("<th>Type</th>"); outFile.println("<th>Size</th>"); outFile.println("</thead>"); for (Float size : sortedCodeTypes.keySet()) { String codeType = sortedCodeTypes.get(size); String drillDownFileName = breakdown.getId() + "_" + codeType + "-" + getPermutationId() + "Classes.html"; float perc = (size / sumSize) * 100; outFile.println("<tr>"); outFile.println("<td><a href=\"" + drillDownFileName + "\" target=\"_top\">" + codeType + "</a></td>"); outFile.println("<td>"); outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">"); outFile.println("<div style=\"width:" + perc + "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>"); outFile.println("</div>"); outFile.println(size + " (" + formatNumber(perc) + "%)"); outFile.println("</td>"); outFile.println("</tr>"); } outFile.println("</table>"); TreeMap<Float, String> sortedLitTypes = new TreeMap<Float, String>( Collections.reverseOrder()); float curSize = nameToLitColl.get("string").size; sumSize += curSize; if (curSize != 0f) { sortedLitTypes.put(curSize, "string"); } for (Float size : sortedLitTypes.keySet()) { String literal = sortedLitTypes.get(size); String drillDownFileName = breakdown.getId() + "_" + literal + "-" + getPermutationId() + "Lits.html"; outFile.println("<p class=\"soyc-breakdown-strings\"><a href=\"" + drillDownFileName + "\" target=\"_top\">Strings</a> occupy " + size + " bytes</p>"); } addStandardHtmlEnding(outFile); outFile.close(); return outFileName; } /** * Produces an HTML file that displays dependencies. * * @param depGraphName name of dependency graph * @param dependencies map of dependencies * @throws IOException */ private void makeDependenciesHtml(String depGraphName, Map<String, String> dependencies) throws IOException { String depGraphDescription = inferDepGraphDescription(depGraphName); PrintWriter outFile = null; String curPackageName = ""; String curClassName = ""; for (String method : dependencies.keySet()) { // this key set is already in alphabetical order // get the package of this method, i.e., everything up to .[A-Z] String packageName = method; packageName = packageName.replaceAll("\\.\\p{Upper}.*", ""); String className = method; className = className.replaceAll("::.*", ""); if ((curPackageName.compareTo("") == 0) || (curPackageName.compareTo(packageName) != 0)) { curPackageName = packageName; if (outFile != null) { // finish up the current file addStandardHtmlEnding(outFile); outFile.close(); } String outFileName = dependenciesFileName(depGraphName, curPackageName); outFile = new PrintWriter(getOutFile(outFileName)); String packageDescription = packageName.length() == 0 ? "the default package" : packageName; addStandardHtmlProlog(outFile, "Method Dependencies for " + depGraphDescription, "Method Dependencies for " + depGraphDescription, "Showing Package: " + packageDescription); } String name = method; if (curClassName.compareTo(className) != 0) { name = className; curClassName = className; outFile.println("<a name=\"" + curClassName + "\"><h3 class=\"soyc-class-header\">Class: " + curClassName + "</a></h3>"); } outFile.println("<div class='main'>"); outFile.println("<a class='toggle soyc-call-stack-link' onclick='toggle.call(this)'><span class='calledBy'> Call stack: </span>" + name + "</a>"); outFile.println("<ul class=\"soyc-call-stack-list\">"); String depMethod = dependencies.get(method); while (depMethod != null) { String nextDep = dependencies.get(depMethod); if (nextDep != null) { outFile.println("<li>" + depMethod + "</li>"); } depMethod = nextDep; } outFile.println("</ul>"); outFile.println("</div>"); } addStandardHtmlEnding(outFile); outFile.close(); } /** * Produces an HTML file for leftovers status. * * @param className * @throws IOException */ private void makeLeftoversStatusPage(String className) throws IOException { String packageName = globalInformation.getClassToPackage().get(className); PrintWriter outFile = new PrintWriter( getOutFile(leftoversStatusFileName(className))); addStandardHtmlProlog(outFile, "Leftovers page for " + className, "Leftovers page for " + className, ""); outFile.println("<div id=\"bd\">"); outFile.println("<p>This class has some leftover code, neither initial nor exclusive to any split point:</p>"); addLefttoversStatus(className, packageName, outFile); addStandardHtmlEnding(outFile); outFile.close(); } /** * Produces an HTML file that shows information about a package. * * @param breakdown * @return the name of the HTML file * @throws IOException */ private String makePackageHtml(SizeBreakdown breakdown) throws IOException { String outFileName = breakdown.getId() + "-" + getPermutationId() + "-" + "packageBreakdown.html"; Map<String, Integer> packageToPartialSize = breakdown.packageToSize; TreeMap<Integer, String> sortedPackages = new TreeMap<Integer, String>( Collections.reverseOrder()); float sumSize = 0f; for (String packageName : packageToPartialSize.keySet()) { sortedPackages.put(packageToPartialSize.get(packageName), packageName); sumSize += packageToPartialSize.get(packageName); } final PrintWriter outFile = new PrintWriter(getOutFile(outFileName)); addSmallHtmlProlog(outFile, "Package breakdown"); outFile.println("<body class=\"soyc-breakdown\">"); outFile.println("<div class=\"g-doc\">"); outFile.println("<table class=\"soyc-table\">"); outFile.println("<colgroup>"); outFile.println("<col id=\"soyc-splitpoint-type-col\">"); outFile.println("<col id=\"soyc-splitpoint-size-col\">"); outFile.println("</colgroup>"); outFile.println("<thead>"); outFile.println("<th>Package</th>"); outFile.println("<th>Size <span class=\"soyc-th-units\">Bytes (% All Code)</span></th>"); outFile.println("</thead>"); for (int size : sortedPackages.keySet()) { String packageName = sortedPackages.get(size); String drillDownFileName = classesInPackageFileName(breakdown, packageName, getPermutationId()); float perc = (size / sumSize) * 100; outFile.println("<tr>"); outFile.println("<td><a href=\"" + drillDownFileName + "\" target=\"_top\">" + packageName + "</a></td>"); outFile.println("<td>"); outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">"); outFile.println("<div style=\"width:" + perc + "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>"); outFile.println("</div>"); outFile.println(size + " (" + formatNumber(perc) + "%)"); outFile.println("</td>"); outFile.println("</tr>"); } outFile.println("</table>"); addStandardHtmlEnding(outFile); outFile.close(); return outFileName; } private void makeSplitStatusPage(String className) throws IOException { String packageName = globalInformation.getClassToPackage().get(className); PrintWriter outFile = new PrintWriter( getOutFile(splitStatusFileName(className))); addStandardHtmlProlog(outFile, "Split point status for " + className, "Split point status for " + className, ""); outFile.println("<div id=\"bd\">"); if (globalInformation.getInitialCodeBreakdown().classToSize.containsKey(className)) { if (globalInformation.dependencies != null) { outFile.println("<p>Some code is included in the initial fragment (<a href=\"" + dependenciesFileName("initial", packageName) + "#" + className + "\">see why</a>)</p>"); } else { outFile.println("<p>Some code is included in the initial fragment</p>"); } } for (int sp : splitPointsWithClass(className)) { outFile.println("<p>Some code downloads with split point " + sp + ": " + globalInformation.getSplitPointToLocation().get(sp) + "</p>"); } if (globalInformation.getLeftoversBreakdown().classToSize.containsKey(className)) { outFile.println("<p>Some code is left over:</p>"); addLefttoversStatus(className, packageName, outFile); } addStandardHtmlEnding(outFile); outFile.close(); } /** * Find which split points include code belonging to <code>className</code>. */ private Iterable<Integer> splitPointsWithClass(String className) { List<Integer> sps = new ArrayList<Integer>(); for (int sp = 1; sp <= globalInformation.getNumSplitPoints(); sp++) { Map<String, Integer> classToSize = globalInformation.splitPointCodeBreakdown(sp).classToSize; if (classToSize.containsKey(className)) { sps.add(sp); } } return sps; } private String splitStatusFileName(String className) { return "splitStatus-" + filename(className) + "-" + getPermutationId() + ".html"; } }
false
true
public void makeTopLevelShell() throws IOException { String permutationId = getPermutationId(); PrintWriter outFile = new PrintWriter(getOutFile("SoycDashboard" + "-" + getPermutationId() + "-index.html")); addStandardHtmlProlog(outFile, "Compile report: Permutation " + permutationId, "Compile report: Permutation " + permutationId, ""); outFile.println("<div id=\"bd\">"); outFile.println("<div id=\"soyc-summary\" class=\"g-section\">"); outFile.println("<dl>"); outFile.println("<dt>Full code size</dt>"); outFile.println("<dd class=\"value\">" + globalInformation.getInitialCodeBreakdown().sizeAllCode + " Bytes</dd>"); outFile.println("<dd class=\"report\"><a href=\"total-" + permutationId + "-overallBreakdown.html\">Report</a></dd>"); outFile.println("</dl>"); outFile.println("<dl>"); outFile.println("<dt>Initial download size</dt>"); // TODO(kprobst) -- add percentage here: (48%)</dd>"); outFile.println("<dd class=\"value\">" + globalInformation.getTotalCodeBreakdown().sizeAllCode + " Bytes</dd>"); outFile.println("<dd class=\"report\"><a href=\"initial-" + permutationId + "-overallBreakdown.html\">Report</a></dd>"); outFile.println("</dl>"); outFile.println("<dl>"); outFile.println("<dt>Left over code</dt>"); outFile.println("<dd class=\"value\">" + globalInformation.getLeftoversBreakdown().sizeAllCode + " Bytes</dd>"); outFile.println("<dd class=\"report\"><a href=\"leftovers-" + permutationId + "-overallBreakdown.html\">Report</a></dd>"); outFile.println("</dl>"); outFile.println("</div>"); outFile.println("<table id=\"soyc-table-splitpoints\" class=\"soyc-table\">"); outFile.println("<caption>"); outFile.println("<strong>Split Points</strong>"); outFile.println("</caption>"); outFile.println("<colgroup>"); outFile.println("<col id=\"soyc-splitpoint-number-col\">"); outFile.println("<col id=\"soyc-splitpoint-location-col\">"); outFile.println("<col id=\"soyc-splitpoint-size-col\">"); outFile.println("</colgroup>"); outFile.println("<thead>"); outFile.println("<th>#</th>"); outFile.println("<th>Location</th>"); outFile.println("<th>Size</th>"); outFile.println("</thead>"); outFile.println("<tbody>"); if (globalInformation.getSplitPointToLocation().size() > 1) { int numSplitPoints = globalInformation.getSplitPointToLocation().size(); float maxSize = globalInformation.getTotalCodeBreakdown().sizeAllCode; for (int i = FRAGMENT_NUMBER_TOTAL_PROGRAM; i <= numSplitPoints + 1; i++) { SizeBreakdown breakdown; if (i == FRAGMENT_NUMBER_TOTAL_PROGRAM) { continue; } else if (i == numSplitPoints + 1) { // leftovers continue; } else if (i == FRAGMENT_NUMBER_INITIAL_DOWNLOAD) { continue; } else { breakdown = globalInformation.splitPointCodeBreakdown(i); } String drillDownFileName = shellFileName(breakdown, getPermutationId()); String splitPointDescription = globalInformation.getSplitPointToLocation().get( i); float size = breakdown.sizeAllCode; float ratio; ratio = (size / maxSize) * 100; outFile.println("<tr>"); outFile.println("<td>" + i + "</td>"); outFile.println("<td><a href=\"" + drillDownFileName + "\">" + splitPointDescription + "</a></td>"); outFile.println("<td>"); outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">"); outFile.println("<div style=\"width:" + ratio + "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>"); outFile.println("</div>"); outFile.println((int) size + " Bytes (" + formatNumber(ratio) + "%)"); outFile.println("</td>"); outFile.println("</tr>"); } } outFile.println("</tbody>"); outFile.println("</table>"); outFile.println("</div>"); addStandardHtmlEnding(outFile); outFile.close(); }
public void makeTopLevelShell() throws IOException { String permutationId = getPermutationId(); PrintWriter outFile = new PrintWriter(getOutFile("SoycDashboard" + "-" + getPermutationId() + "-index.html")); addStandardHtmlProlog(outFile, "Compile report: Permutation " + permutationId, "Compile report: Permutation " + permutationId, ""); outFile.println("<div id=\"bd\">"); outFile.println("<div id=\"soyc-summary\" class=\"g-section\">"); outFile.println("<dl>"); outFile.println("<dt>Full code size</dt>"); outFile.println("<dd class=\"value\">" + globalInformation.getTotalCodeBreakdown().sizeAllCode + " Bytes</dd>"); outFile.println("<dd class=\"report\"><a href=\"total-" + permutationId + "-overallBreakdown.html\">Report</a></dd>"); outFile.println("</dl>"); outFile.println("<dl>"); outFile.println("<dt>Initial download size</dt>"); // TODO(kprobst) -- add percentage here: (48%)</dd>"); outFile.println("<dd class=\"value\">" + globalInformation.getInitialCodeBreakdown().sizeAllCode + " Bytes</dd>"); outFile.println("<dd class=\"report\"><a href=\"initial-" + permutationId + "-overallBreakdown.html\">Report</a></dd>"); outFile.println("</dl>"); outFile.println("<dl>"); outFile.println("<dt>Left over code</dt>"); outFile.println("<dd class=\"value\">" + globalInformation.getLeftoversBreakdown().sizeAllCode + " Bytes</dd>"); outFile.println("<dd class=\"report\"><a href=\"leftovers-" + permutationId + "-overallBreakdown.html\">Report</a></dd>"); outFile.println("</dl>"); outFile.println("</div>"); outFile.println("<table id=\"soyc-table-splitpoints\" class=\"soyc-table\">"); outFile.println("<caption>"); outFile.println("<strong>Split Points</strong>"); outFile.println("</caption>"); outFile.println("<colgroup>"); outFile.println("<col id=\"soyc-splitpoint-number-col\">"); outFile.println("<col id=\"soyc-splitpoint-location-col\">"); outFile.println("<col id=\"soyc-splitpoint-size-col\">"); outFile.println("</colgroup>"); outFile.println("<thead>"); outFile.println("<th>#</th>"); outFile.println("<th>Location</th>"); outFile.println("<th>Size</th>"); outFile.println("</thead>"); outFile.println("<tbody>"); if (globalInformation.getSplitPointToLocation().size() >= 1) { int numSplitPoints = globalInformation.getSplitPointToLocation().size(); float maxSize = globalInformation.getTotalCodeBreakdown().sizeAllCode; for (int i = FRAGMENT_NUMBER_TOTAL_PROGRAM; i <= numSplitPoints + 1; i++) { SizeBreakdown breakdown; if (i == FRAGMENT_NUMBER_TOTAL_PROGRAM) { continue; } else if (i == numSplitPoints + 1) { // leftovers continue; } else if (i == FRAGMENT_NUMBER_INITIAL_DOWNLOAD) { continue; } else { breakdown = globalInformation.splitPointCodeBreakdown(i); } String drillDownFileName = shellFileName(breakdown, getPermutationId()); String splitPointDescription = globalInformation.getSplitPointToLocation().get( i); float size = breakdown.sizeAllCode; float ratio; ratio = (size / maxSize) * 100; outFile.println("<tr>"); outFile.println("<td>" + i + "</td>"); outFile.println("<td><a href=\"" + drillDownFileName + "\">" + splitPointDescription + "</a></td>"); outFile.println("<td>"); outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">"); outFile.println("<div style=\"width:" + ratio + "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>"); outFile.println("</div>"); outFile.println((int) size + " Bytes (" + formatNumber(ratio) + "%)"); outFile.println("</td>"); outFile.println("</tr>"); } } outFile.println("</tbody>"); outFile.println("</table>"); outFile.println("</div>"); addStandardHtmlEnding(outFile); outFile.close(); }
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/parse/GadgetHtmlParser.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/parse/GadgetHtmlParser.java index 0f6fc50a3..3c38f59c6 100644 --- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/parse/GadgetHtmlParser.java +++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/parse/GadgetHtmlParser.java @@ -1,363 +1,364 @@ /** * 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.shindig.gadgets.parse; import com.google.common.collect.Lists; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.Provider; import org.apache.shindig.common.cache.Cache; import org.apache.shindig.common.cache.CacheProvider; import org.apache.shindig.common.util.HashUtil; import org.apache.shindig.gadgets.GadgetException; import org.apache.shindig.gadgets.parse.nekohtml.NekoSimplifiedHtmlParser; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.LinkedList; /** * Parser for arbitrary HTML content */ @ImplementedBy(NekoSimplifiedHtmlParser.class) public abstract class GadgetHtmlParser { public static final String PARSED_DOCUMENTS = "parsedDocuments"; public static final String PARSED_FRAGMENTS = "parsedFragments"; private Cache<String, Document> documentCache; private Cache<String, DocumentFragment> fragmentCache; private Provider<HtmlSerializer> serializerProvider = new DefaultSerializerProvider(); protected final DOMImplementation documentFactory; protected GadgetHtmlParser(DOMImplementation documentFactory) { this.documentFactory = documentFactory; } @Inject public void setCacheProvider(CacheProvider cacheProvider) { documentCache = cacheProvider.createCache(PARSED_DOCUMENTS); fragmentCache = cacheProvider.createCache(PARSED_FRAGMENTS); } @Inject public void setSerializerProvider(Provider<HtmlSerializer> serProvider) { this.serializerProvider = serProvider; } /** * @param content * @return true if we detect a preamble of doctype or html */ protected static boolean attemptFullDocParseFirst(String content) { String normalized = content.substring(0, Math.min(100, content.length())).toUpperCase(); return normalized.contains("<!DOCTYPE") || normalized.contains("<HTML"); } public Document parseDom(String source) throws GadgetException { Document document = null; String key = null; // Avoid checksum overhead if we arent caching boolean shouldCache = shouldCache(); if (shouldCache) { // TODO - Consider using the source if its under a certain size key = HashUtil.checksum(source.getBytes()); document = documentCache.getElement(key); } if (document == null) { try { document = parseDomImpl(source); - } catch (GadgetException e) { - throw e; } catch (DOMException e) { // DOMException is a RuntimeException document = errorDom(e); HtmlSerialization.attach(document, serializerProvider.get(), source); return document; + } catch (NullPointerException e) { + throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, + "Caught exception in parseDomImpl", e); } HtmlSerialization.attach(document, serializerProvider.get(), source); Node html = document.getDocumentElement(); Node head = null; Node body = null; LinkedList<Node> beforeHead = Lists.newLinkedList(); LinkedList<Node> beforeBody = Lists.newLinkedList(); while (html.hasChildNodes()) { Node child = html.removeChild(html.getFirstChild()); if (child.getNodeType() == Node.ELEMENT_NODE && "head".equalsIgnoreCase(child.getNodeName())) { if (head == null) { head = child; } else { // Concatenate <head> elements together. transferChildren(head, child); } } else if (child.getNodeType() == Node.ELEMENT_NODE && "body".equalsIgnoreCase(child.getNodeName())) { if (body == null) { body = child; } else { // Concatenate <body> elements together. transferChildren(body, child); } } else if (head == null) { beforeHead.add(child); } else if (body == null) { beforeBody.add(child); } else { // Both <head> and <body> are present. Append to tail of <body>. body.appendChild(child); } } // Ensure head tag exists if (head == null) { // beforeHead contains all elements that should be prepended to <body>. Switch them. LinkedList<Node> temp = beforeBody; beforeBody = beforeHead; beforeHead = temp; // Add as first element head = document.createElement("head"); html.insertBefore(head, html.getFirstChild()); } else { // Re-append head node. html.appendChild(head); } // Ensure body tag exists. if (body == null) { // Add immediately after head. body = document.createElement("body"); html.insertBefore(body, head.getNextSibling()); } else { // Re-append body node. html.appendChild(body); } // Leftovers: nodes before the first <head> node found and the first <body> node found. // Prepend beforeHead to the front of <head>, and beforeBody to beginning of <body>, // in the order they were found in the document. prependToNode(head, beforeHead); prependToNode(body, beforeBody); // One exception. <style>/<link rel="stylesheet" nodes from <body> end up at the end of <head>, // since doing so is HTML compliant and can never break rendering due to ordering concerns. LinkedList<Node> styleNodes = Lists.newLinkedList(); NodeList bodyKids = body.getChildNodes(); for (int i = 0; i < bodyKids.getLength(); ++i) { Node bodyKid = bodyKids.item(i); if (bodyKid.getNodeType() == Node.ELEMENT_NODE && isStyleElement((Element)bodyKid)) { styleNodes.add(bodyKid); } } for (Node styleNode : styleNodes) { head.appendChild(body.removeChild(styleNode)); } // Finally, reprocess all script nodes for OpenSocial purposes, as these // may be interpreted (rightly, from the perspective of HTML) as containing text only. reprocessScriptForOpenSocial(html); if (shouldCache) { documentCache.addElement(key, document); } } if (shouldCache) { Document copy = (Document)document.cloneNode(true); HtmlSerialization.copySerializer(document, copy); return copy; } return document; } protected void transferChildren(Node to, Node from) { while (from.hasChildNodes()) { to.appendChild(from.removeChild(from.getFirstChild())); } } protected void prependToNode(Node to, LinkedList<Node> from) { while (!from.isEmpty()) { to.insertBefore(from.removeLast(), to.getFirstChild()); } } private boolean isStyleElement(Element elem) { return "style".equalsIgnoreCase(elem.getNodeName()) || ("link".equalsIgnoreCase(elem.getNodeName()) && ("stylesheet".equalsIgnoreCase(elem.getAttribute("rel")) || elem.getAttribute("type").toLowerCase().contains("css"))); } /** * Parses a snippet of markup and appends the result as children to the * provided node. * * @param source markup to be parsed * @param result Node to append results to * @throws GadgetException */ public void parseFragment(String source, Node result) throws GadgetException { boolean shouldCache = shouldCache(); String key = null; if (shouldCache) { key = HashUtil.checksum(source.getBytes()); DocumentFragment cachedFragment = fragmentCache.getElement(key); if (cachedFragment != null) { copyFragment(cachedFragment, result); return; } } DocumentFragment fragment = null; try { fragment = parseFragmentImpl(source); } catch (DOMException e) { // DOMException is a RuntimeException appendParseException(result, e); return; } reprocessScriptForOpenSocial(fragment); if (shouldCache) { fragmentCache.addElement(key, fragment); } copyFragment(fragment, result); } private void copyFragment(DocumentFragment source, Node dest) { Document destDoc = dest.getOwnerDocument(); NodeList nodes = source.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node clone = destDoc.importNode(nodes.item(i), true); dest.appendChild(clone); } } protected Document errorDom(DOMException e) { // Create a bare-bones DOM whose body is just error text. // We do this to echo information to the developer that originally // supplied the data, since doing so is more useful than simply // returning a black-box HTML error code stemming from an NPE or other condition downstream. // The method is protected to allow overriding of this behavior. Document doc = documentFactory.createDocument(null, null, null); Node html = doc.createElement("html"); html.appendChild(doc.createElement("head")); Node body = doc.createElement("body"); appendParseException(body, e); html.appendChild(body); doc.appendChild(html); return doc; } private void appendParseException(Node node, DOMException e) { node.appendChild(node.getOwnerDocument().createTextNode( GadgetException.Code.HTML_PARSE_ERROR.toString() + ": " + e.toString())); } protected boolean shouldCache() { return documentCache != null && documentCache.getCapacity() != 0; } private void reprocessScriptForOpenSocial(Node root) throws GadgetException { LinkedList<Node> nodeQueue = Lists.newLinkedList(); nodeQueue.add(root); while (!nodeQueue.isEmpty()) { Node next = nodeQueue.removeFirst(); if (next.getNodeType() == Node.ELEMENT_NODE && "script".equalsIgnoreCase(next.getNodeName())) { Attr typeAttr = (Attr)next.getAttributes().getNamedItem("type"); if (typeAttr != null && SocialDataTags.SCRIPT_TYPE_TO_OSML_TAG.get(typeAttr.getValue()) != null) { // The underlying parser impl may have already parsed these. // Only re-parse with the coalesced text children if that's all there are. boolean parseOs = true; StringBuilder sb = new StringBuilder(); NodeList scriptKids = next.getChildNodes(); for (int i = 0; parseOs && i < scriptKids.getLength(); ++i) { Node scriptKid = scriptKids.item(i); if (scriptKid.getNodeType() != Node.TEXT_NODE) { parseOs = false; } sb.append(scriptKid.getTextContent()); } if (parseOs) { // Clean out the script node. while (next.hasChildNodes()) { next.removeChild(next.getFirstChild()); } DocumentFragment osFragment = parseFragmentImpl(sb.toString()); while (osFragment.hasChildNodes()) { Node osKid = osFragment.removeChild(osFragment.getFirstChild()); osKid = next.getOwnerDocument().adoptNode(osKid); if (osKid.getNodeType() == Node.ELEMENT_NODE) { next.appendChild(osKid); } } } } } // Enqueue children for inspection. NodeList children = next.getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { nodeQueue.add(children.item(i)); } } } /** * TODO: remove the need for parseDomImpl as a parsing method. Gadget HTML is * tag soup handled in custom fashion, or is a legitimate fragment. In either case, * we can simply use the fragment parsing implementation and patch up in higher-level calls. * @param source a piece of HTML * @return a Document parsed from the HTML * @throws GadgetException */ protected abstract Document parseDomImpl(String source) throws GadgetException; /** * @param source a snippet of HTML markup * @return a DocumentFragment containing the parsed elements * @throws GadgetException */ protected abstract DocumentFragment parseFragmentImpl(String source) throws GadgetException; private static class DefaultSerializerProvider implements Provider<HtmlSerializer> { public HtmlSerializer get() { return new DefaultHtmlSerializer(); } } }
false
true
public Document parseDom(String source) throws GadgetException { Document document = null; String key = null; // Avoid checksum overhead if we arent caching boolean shouldCache = shouldCache(); if (shouldCache) { // TODO - Consider using the source if its under a certain size key = HashUtil.checksum(source.getBytes()); document = documentCache.getElement(key); } if (document == null) { try { document = parseDomImpl(source); } catch (GadgetException e) { throw e; } catch (DOMException e) { // DOMException is a RuntimeException document = errorDom(e); HtmlSerialization.attach(document, serializerProvider.get(), source); return document; } HtmlSerialization.attach(document, serializerProvider.get(), source); Node html = document.getDocumentElement(); Node head = null; Node body = null; LinkedList<Node> beforeHead = Lists.newLinkedList(); LinkedList<Node> beforeBody = Lists.newLinkedList(); while (html.hasChildNodes()) { Node child = html.removeChild(html.getFirstChild()); if (child.getNodeType() == Node.ELEMENT_NODE && "head".equalsIgnoreCase(child.getNodeName())) { if (head == null) { head = child; } else { // Concatenate <head> elements together. transferChildren(head, child); } } else if (child.getNodeType() == Node.ELEMENT_NODE && "body".equalsIgnoreCase(child.getNodeName())) { if (body == null) { body = child; } else { // Concatenate <body> elements together. transferChildren(body, child); } } else if (head == null) { beforeHead.add(child); } else if (body == null) { beforeBody.add(child); } else { // Both <head> and <body> are present. Append to tail of <body>. body.appendChild(child); } } // Ensure head tag exists if (head == null) { // beforeHead contains all elements that should be prepended to <body>. Switch them. LinkedList<Node> temp = beforeBody; beforeBody = beforeHead; beforeHead = temp; // Add as first element head = document.createElement("head"); html.insertBefore(head, html.getFirstChild()); } else { // Re-append head node. html.appendChild(head); } // Ensure body tag exists. if (body == null) { // Add immediately after head. body = document.createElement("body"); html.insertBefore(body, head.getNextSibling()); } else { // Re-append body node. html.appendChild(body); } // Leftovers: nodes before the first <head> node found and the first <body> node found. // Prepend beforeHead to the front of <head>, and beforeBody to beginning of <body>, // in the order they were found in the document. prependToNode(head, beforeHead); prependToNode(body, beforeBody); // One exception. <style>/<link rel="stylesheet" nodes from <body> end up at the end of <head>, // since doing so is HTML compliant and can never break rendering due to ordering concerns. LinkedList<Node> styleNodes = Lists.newLinkedList(); NodeList bodyKids = body.getChildNodes(); for (int i = 0; i < bodyKids.getLength(); ++i) { Node bodyKid = bodyKids.item(i); if (bodyKid.getNodeType() == Node.ELEMENT_NODE && isStyleElement((Element)bodyKid)) { styleNodes.add(bodyKid); } } for (Node styleNode : styleNodes) { head.appendChild(body.removeChild(styleNode)); } // Finally, reprocess all script nodes for OpenSocial purposes, as these // may be interpreted (rightly, from the perspective of HTML) as containing text only. reprocessScriptForOpenSocial(html); if (shouldCache) { documentCache.addElement(key, document); } } if (shouldCache) { Document copy = (Document)document.cloneNode(true); HtmlSerialization.copySerializer(document, copy); return copy; } return document; }
public Document parseDom(String source) throws GadgetException { Document document = null; String key = null; // Avoid checksum overhead if we arent caching boolean shouldCache = shouldCache(); if (shouldCache) { // TODO - Consider using the source if its under a certain size key = HashUtil.checksum(source.getBytes()); document = documentCache.getElement(key); } if (document == null) { try { document = parseDomImpl(source); } catch (DOMException e) { // DOMException is a RuntimeException document = errorDom(e); HtmlSerialization.attach(document, serializerProvider.get(), source); return document; } catch (NullPointerException e) { throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, "Caught exception in parseDomImpl", e); } HtmlSerialization.attach(document, serializerProvider.get(), source); Node html = document.getDocumentElement(); Node head = null; Node body = null; LinkedList<Node> beforeHead = Lists.newLinkedList(); LinkedList<Node> beforeBody = Lists.newLinkedList(); while (html.hasChildNodes()) { Node child = html.removeChild(html.getFirstChild()); if (child.getNodeType() == Node.ELEMENT_NODE && "head".equalsIgnoreCase(child.getNodeName())) { if (head == null) { head = child; } else { // Concatenate <head> elements together. transferChildren(head, child); } } else if (child.getNodeType() == Node.ELEMENT_NODE && "body".equalsIgnoreCase(child.getNodeName())) { if (body == null) { body = child; } else { // Concatenate <body> elements together. transferChildren(body, child); } } else if (head == null) { beforeHead.add(child); } else if (body == null) { beforeBody.add(child); } else { // Both <head> and <body> are present. Append to tail of <body>. body.appendChild(child); } } // Ensure head tag exists if (head == null) { // beforeHead contains all elements that should be prepended to <body>. Switch them. LinkedList<Node> temp = beforeBody; beforeBody = beforeHead; beforeHead = temp; // Add as first element head = document.createElement("head"); html.insertBefore(head, html.getFirstChild()); } else { // Re-append head node. html.appendChild(head); } // Ensure body tag exists. if (body == null) { // Add immediately after head. body = document.createElement("body"); html.insertBefore(body, head.getNextSibling()); } else { // Re-append body node. html.appendChild(body); } // Leftovers: nodes before the first <head> node found and the first <body> node found. // Prepend beforeHead to the front of <head>, and beforeBody to beginning of <body>, // in the order they were found in the document. prependToNode(head, beforeHead); prependToNode(body, beforeBody); // One exception. <style>/<link rel="stylesheet" nodes from <body> end up at the end of <head>, // since doing so is HTML compliant and can never break rendering due to ordering concerns. LinkedList<Node> styleNodes = Lists.newLinkedList(); NodeList bodyKids = body.getChildNodes(); for (int i = 0; i < bodyKids.getLength(); ++i) { Node bodyKid = bodyKids.item(i); if (bodyKid.getNodeType() == Node.ELEMENT_NODE && isStyleElement((Element)bodyKid)) { styleNodes.add(bodyKid); } } for (Node styleNode : styleNodes) { head.appendChild(body.removeChild(styleNode)); } // Finally, reprocess all script nodes for OpenSocial purposes, as these // may be interpreted (rightly, from the perspective of HTML) as containing text only. reprocessScriptForOpenSocial(html); if (shouldCache) { documentCache.addElement(key, document); } } if (shouldCache) { Document copy = (Document)document.cloneNode(true); HtmlSerialization.copySerializer(document, copy); return copy; } return document; }
diff --git a/tool/src/java/org/sakaiproject/assignment2/tool/producers/renderers/AsnnSubmitEditorRenderer.java b/tool/src/java/org/sakaiproject/assignment2/tool/producers/renderers/AsnnSubmitEditorRenderer.java index 14e3e89e..e4d7444c 100644 --- a/tool/src/java/org/sakaiproject/assignment2/tool/producers/renderers/AsnnSubmitEditorRenderer.java +++ b/tool/src/java/org/sakaiproject/assignment2/tool/producers/renderers/AsnnSubmitEditorRenderer.java @@ -1,237 +1,245 @@ package org.sakaiproject.assignment2.tool.producers.renderers; import java.util.HashMap; import java.util.Map; import org.sakaiproject.assignment2.model.Assignment2; import org.sakaiproject.assignment2.model.AssignmentSubmission; import org.sakaiproject.assignment2.model.AssignmentSubmissionVersion; import org.sakaiproject.assignment2.model.constants.AssignmentConstants; import org.sakaiproject.assignment2.tool.params.FilePickerHelperViewParams; import org.sakaiproject.assignment2.tool.producers.AddAttachmentHelperProducer; import org.sakaiproject.assignment2.tool.producers.evolvers.AttachmentInputEvolver; import uk.org.ponder.beanutil.entity.EntityBeanLocator; import uk.org.ponder.messageutil.MessageLocator; import uk.org.ponder.rsf.components.UIBoundBoolean; import uk.org.ponder.rsf.components.UIBoundString; import uk.org.ponder.rsf.components.UICommand; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIELBinding; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIInput; import uk.org.ponder.rsf.components.UIInputMany; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIJointContainer; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.components.UIVerbatim; import uk.org.ponder.rsf.components.decorators.DecoratorList; import uk.org.ponder.rsf.components.decorators.UIFreeAttributeDecorator; import uk.org.ponder.rsf.evolvers.TextInputEvolver; import uk.org.ponder.rsf.producers.BasicProducer; /** * Renders the area of the Student Submit pages where the student does the * actual work of putting in the submission text and uploading any attachments * that are part of the submission. * * This does have to detect the type of assignment: Non-electronic, text, * text and attachments, attachments only. In the future this may be * modularized to allow new pluggable assignment types. * * In the non-electronic or non-submission assignment type, this will really * just be a check box that says you've completed it and a "Save and Return" * button. * * @author sgithens * */ public class AsnnSubmitEditorRenderer implements BasicProducer { // Dependency private MessageLocator messageLocator; public void setMessageLocator(MessageLocator messageLocator) { this.messageLocator = messageLocator; } // Dependency private TextInputEvolver richTextEvolver; public void setRichTextEvolver(TextInputEvolver richTextEvolver) { this.richTextEvolver = richTextEvolver; } // Dependency private AttachmentInputEvolver attachmentInputEvolver; public void setAttachmentInputEvolver(AttachmentInputEvolver attachmentInputEvolver){ this.attachmentInputEvolver = attachmentInputEvolver; } private EntityBeanLocator asnnSubmissionVersionLocator; public void setAsnnSubmissionVersion(EntityBeanLocator asnnSubmissionVersion) { this.asnnSubmissionVersionLocator = asnnSubmissionVersion; } /** * * @param parent * @param clientID * @param assignmentSubmission * @param preview * @param asvOTP */ public void fillComponents(UIContainer parent, String clientID, AssignmentSubmission assignmentSubmission, boolean preview, boolean studentPreviewSubmission) { // Various Widgets we may need to decorate later. UICommand submit_button = null; UICommand preview_button = null; UICommand save_button = null; Assignment2 assignment = assignmentSubmission.getAssignment(); UIJointContainer joint = new UIJointContainer(parent, clientID, "asnn2-submit-editor-widget:"); String asOTP = "AssignmentSubmission."; String asOTPKey = ""; if (assignmentSubmission != null && assignmentSubmission.getId() != null) { asOTPKey += assignmentSubmission.getId(); } else { asOTPKey += EntityBeanLocator.NEW_PREFIX + "1"; } asOTP = asOTP + asOTPKey; String asvOTP = "AssignmentSubmissionVersion."; String asvOTPKey = ""; if (assignmentSubmission != null && assignmentSubmission.getCurrentSubmissionVersion() != null - && assignmentSubmission.getCurrentSubmissionVersion().isDraft() == Boolean.TRUE) { + && assignmentSubmission.getCurrentSubmissionVersion().isDraft()) { asvOTPKey += assignmentSubmission.getCurrentSubmissionVersion().getId(); } else { asvOTPKey += EntityBeanLocator.NEW_PREFIX + "1"; } asvOTP = asvOTP + asvOTPKey; //For preview, get a decorated list of disabled="disabled" Map<String, String> disabledAttr = new HashMap<String, String>(); disabledAttr.put("disabled", "disabled"); DecoratorList disabledDecoratorList = new DecoratorList(new UIFreeAttributeDecorator(disabledAttr)); UIForm form = UIForm.make(joint, "form"); //Fill in with submission type specific instructions UIOutput.make(form, "submission_instructions", messageLocator.getMessage("assignment2.student-submit.instructions." + assignment.getSubmissionType())); if (assignment.isHonorPledge()) { UIVerbatim.make(form, "required", messageLocator.getMessage("assignment2.student-submit.required")); } //Rich Text Input String hackSubmissionText = ""; if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_INLINE_ONLY || assignment.getSubmissionType() == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH){ UIOutput.make(form, "submit_text"); if (studentPreviewSubmission) { // TODO FIXME Make this a UIVerbatim for (Object versionObj: asnnSubmissionVersionLocator.getDeliveredBeans().values()) { AssignmentSubmissionVersion version = (AssignmentSubmissionVersion) versionObj; hackSubmissionText = version.getSubmittedText(); UIVerbatim make = UIVerbatim.make(form, "text:", hackSubmissionText); } //UIOutput.make(form, "text:", asnnSubmissionVersionLocator.getDeliveredBeans().size()+""); //UIOutput.make(form, "text:", null,asvOTP + ".submittedText" ); //text_disabled.decorators = disabledDecoratorList; } else if (!preview) { UIInput text = UIInput.make(form, "text:", asvOTP + ".submittedText"); text.mustapply = Boolean.TRUE; richTextEvolver.evolveTextInput(text); } else { //disable textarea UIInput text = UIInput.make(form, "text:", asvOTP + ".submittedText"); UIInput text_disabled = UIInput.make(form, "text_disabled",asvOTP + ".submittedText"); text_disabled.decorators = disabledDecoratorList; } } //Attachment Stuff + // the editor will only display attachments for the current version if + // it is a draft. otherwise, the user is working on a new submission if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_ATTACH_ONLY || assignment.getSubmissionType() == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH){ UIOutput.make(form, "submit_attachments"); if (!preview) { //Attachments + String[] attachmentRefs; + if (assignmentSubmission.getCurrentSubmissionVersion().isDraft()) { + attachmentRefs = assignmentSubmission.getCurrentSubmissionVersion().getSubmittedAttachmentRefs(); + } else { + attachmentRefs = new String[] {}; + } UIInputMany attachmentInput = UIInputMany.make(form, "attachment_list:", asvOTP + ".submittedAttachmentRefs", - assignmentSubmission.getCurrentSubmissionVersion().getSubmittedAttachmentRefs()); + attachmentRefs); attachmentInputEvolver.evolveAttachment(attachmentInput); if (!studentPreviewSubmission) { UIInternalLink.make(form, "add_submission_attachments", UIMessage.make("assignment2.student-submit.add_attachments"), new FilePickerHelperViewParams(AddAttachmentHelperProducer.VIEWID, Boolean.TRUE, Boolean.TRUE, 500, 700, asvOTPKey)); } UIOutput.make(form, "no_attachments_yet", messageLocator.getMessage("assignment2.student-submit.no_attachments")); } } // attachment only situations will not return any values in the OTP map; thus, // we won't enter the processing loop in processActionSubmit (and nothing will be saved) // this will force rsf to bind the otp mapping if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_ATTACH_ONLY) { UIInput.make(form, "submitted_text_for_attach_only", asvOTP + ".submittedText"); } if (assignment.isHonorPledge()) { UIOutput.make(joint, "honor_pledge_fieldset"); UIMessage.make(joint, "honor_pledge_label", "assignment2.student-submit.honor_pledge_text"); UIBoundBoolean honorPledgeCheckbox = UIBoundBoolean.make(form, "honor_pledge", "#{AssignmentSubmissionBean.honorPledge}"); if (studentPreviewSubmission) { honorPledgeCheckbox.decorators = disabledDecoratorList; } } form.parameters.add( new UIELBinding("#{AssignmentSubmissionBean.ASOTPKey}", asOTPKey)); form.parameters.add( new UIELBinding("#{AssignmentSubmissionBean.assignmentId}", assignment.getId())); /* * According to the spec, if a student is editing a submision they will * see the Submit,Preview, and Save&Exit buttons. If they are previewing * a submission they will see Submit,Edit, and Save&Exit. */ if (studentPreviewSubmission) { submit_button = UICommand.make(form, "submit_button", UIMessage.make("assignment2.student-submit.submit"), "AssignmentSubmissionBean.processActionSubmit"); save_button = UICommand.make(form, "save_draft_button", UIMessage.make("assignment2.student-submit.save_draft"), "AssignmentSubmissionBean.processActionSaveDraft"); UICommand edit_button = UICommand.make(form, "back_to_edit_button", UIMessage.make("assignment2.student-submit.back_to_edit"), "AssignmentSubmissionBean.processActionBackToEdit"); edit_button.addParameter(new UIELBinding(asvOTP + ".submittedText", hackSubmissionText)); } else { submit_button = UICommand.make(form, "submit_button", UIMessage.make("assignment2.student-submit.submit"), "AssignmentSubmissionBean.processActionSubmit"); preview_button = UICommand.make(form, "preview_button", UIMessage.make("assignment2.student-submit.preview"), "AssignmentSubmissionBean.processActionPreview"); save_button = UICommand.make(form, "save_draft_button", UIMessage.make("assignment2.student-submit.save_draft"), "AssignmentSubmissionBean.processActionSaveDraft"); } // ASNN-288 //UICommand cancel_button = UICommand.make(form, "cancel_button", UIMessage.make("assignment2.student-submit.cancel"), //"#{AssignmentSubmissionBean.processActionCancel}"); if (preview) { submit_button.decorators = disabledDecoratorList; preview_button.decorators = disabledDecoratorList; save_button.decorators = disabledDecoratorList; //cancel_button.decorators = disabledDecoratorList; } } public void fillComponents(UIContainer parent, String clientID) { } }
false
true
public void fillComponents(UIContainer parent, String clientID, AssignmentSubmission assignmentSubmission, boolean preview, boolean studentPreviewSubmission) { // Various Widgets we may need to decorate later. UICommand submit_button = null; UICommand preview_button = null; UICommand save_button = null; Assignment2 assignment = assignmentSubmission.getAssignment(); UIJointContainer joint = new UIJointContainer(parent, clientID, "asnn2-submit-editor-widget:"); String asOTP = "AssignmentSubmission."; String asOTPKey = ""; if (assignmentSubmission != null && assignmentSubmission.getId() != null) { asOTPKey += assignmentSubmission.getId(); } else { asOTPKey += EntityBeanLocator.NEW_PREFIX + "1"; } asOTP = asOTP + asOTPKey; String asvOTP = "AssignmentSubmissionVersion."; String asvOTPKey = ""; if (assignmentSubmission != null && assignmentSubmission.getCurrentSubmissionVersion() != null && assignmentSubmission.getCurrentSubmissionVersion().isDraft() == Boolean.TRUE) { asvOTPKey += assignmentSubmission.getCurrentSubmissionVersion().getId(); } else { asvOTPKey += EntityBeanLocator.NEW_PREFIX + "1"; } asvOTP = asvOTP + asvOTPKey; //For preview, get a decorated list of disabled="disabled" Map<String, String> disabledAttr = new HashMap<String, String>(); disabledAttr.put("disabled", "disabled"); DecoratorList disabledDecoratorList = new DecoratorList(new UIFreeAttributeDecorator(disabledAttr)); UIForm form = UIForm.make(joint, "form"); //Fill in with submission type specific instructions UIOutput.make(form, "submission_instructions", messageLocator.getMessage("assignment2.student-submit.instructions." + assignment.getSubmissionType())); if (assignment.isHonorPledge()) { UIVerbatim.make(form, "required", messageLocator.getMessage("assignment2.student-submit.required")); } //Rich Text Input String hackSubmissionText = ""; if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_INLINE_ONLY || assignment.getSubmissionType() == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH){ UIOutput.make(form, "submit_text"); if (studentPreviewSubmission) { // TODO FIXME Make this a UIVerbatim for (Object versionObj: asnnSubmissionVersionLocator.getDeliveredBeans().values()) { AssignmentSubmissionVersion version = (AssignmentSubmissionVersion) versionObj; hackSubmissionText = version.getSubmittedText(); UIVerbatim make = UIVerbatim.make(form, "text:", hackSubmissionText); } //UIOutput.make(form, "text:", asnnSubmissionVersionLocator.getDeliveredBeans().size()+""); //UIOutput.make(form, "text:", null,asvOTP + ".submittedText" ); //text_disabled.decorators = disabledDecoratorList; } else if (!preview) { UIInput text = UIInput.make(form, "text:", asvOTP + ".submittedText"); text.mustapply = Boolean.TRUE; richTextEvolver.evolveTextInput(text); } else { //disable textarea UIInput text = UIInput.make(form, "text:", asvOTP + ".submittedText"); UIInput text_disabled = UIInput.make(form, "text_disabled",asvOTP + ".submittedText"); text_disabled.decorators = disabledDecoratorList; } } //Attachment Stuff if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_ATTACH_ONLY || assignment.getSubmissionType() == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH){ UIOutput.make(form, "submit_attachments"); if (!preview) { //Attachments UIInputMany attachmentInput = UIInputMany.make(form, "attachment_list:", asvOTP + ".submittedAttachmentRefs", assignmentSubmission.getCurrentSubmissionVersion().getSubmittedAttachmentRefs()); attachmentInputEvolver.evolveAttachment(attachmentInput); if (!studentPreviewSubmission) { UIInternalLink.make(form, "add_submission_attachments", UIMessage.make("assignment2.student-submit.add_attachments"), new FilePickerHelperViewParams(AddAttachmentHelperProducer.VIEWID, Boolean.TRUE, Boolean.TRUE, 500, 700, asvOTPKey)); } UIOutput.make(form, "no_attachments_yet", messageLocator.getMessage("assignment2.student-submit.no_attachments")); } } // attachment only situations will not return any values in the OTP map; thus, // we won't enter the processing loop in processActionSubmit (and nothing will be saved) // this will force rsf to bind the otp mapping if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_ATTACH_ONLY) { UIInput.make(form, "submitted_text_for_attach_only", asvOTP + ".submittedText"); } if (assignment.isHonorPledge()) { UIOutput.make(joint, "honor_pledge_fieldset"); UIMessage.make(joint, "honor_pledge_label", "assignment2.student-submit.honor_pledge_text"); UIBoundBoolean honorPledgeCheckbox = UIBoundBoolean.make(form, "honor_pledge", "#{AssignmentSubmissionBean.honorPledge}"); if (studentPreviewSubmission) { honorPledgeCheckbox.decorators = disabledDecoratorList; } } form.parameters.add( new UIELBinding("#{AssignmentSubmissionBean.ASOTPKey}", asOTPKey)); form.parameters.add( new UIELBinding("#{AssignmentSubmissionBean.assignmentId}", assignment.getId())); /* * According to the spec, if a student is editing a submision they will * see the Submit,Preview, and Save&Exit buttons. If they are previewing * a submission they will see Submit,Edit, and Save&Exit. */ if (studentPreviewSubmission) { submit_button = UICommand.make(form, "submit_button", UIMessage.make("assignment2.student-submit.submit"), "AssignmentSubmissionBean.processActionSubmit"); save_button = UICommand.make(form, "save_draft_button", UIMessage.make("assignment2.student-submit.save_draft"), "AssignmentSubmissionBean.processActionSaveDraft"); UICommand edit_button = UICommand.make(form, "back_to_edit_button", UIMessage.make("assignment2.student-submit.back_to_edit"), "AssignmentSubmissionBean.processActionBackToEdit"); edit_button.addParameter(new UIELBinding(asvOTP + ".submittedText", hackSubmissionText)); } else { submit_button = UICommand.make(form, "submit_button", UIMessage.make("assignment2.student-submit.submit"), "AssignmentSubmissionBean.processActionSubmit"); preview_button = UICommand.make(form, "preview_button", UIMessage.make("assignment2.student-submit.preview"), "AssignmentSubmissionBean.processActionPreview"); save_button = UICommand.make(form, "save_draft_button", UIMessage.make("assignment2.student-submit.save_draft"), "AssignmentSubmissionBean.processActionSaveDraft"); } // ASNN-288 //UICommand cancel_button = UICommand.make(form, "cancel_button", UIMessage.make("assignment2.student-submit.cancel"), //"#{AssignmentSubmissionBean.processActionCancel}"); if (preview) { submit_button.decorators = disabledDecoratorList; preview_button.decorators = disabledDecoratorList; save_button.decorators = disabledDecoratorList; //cancel_button.decorators = disabledDecoratorList; } }
public void fillComponents(UIContainer parent, String clientID, AssignmentSubmission assignmentSubmission, boolean preview, boolean studentPreviewSubmission) { // Various Widgets we may need to decorate later. UICommand submit_button = null; UICommand preview_button = null; UICommand save_button = null; Assignment2 assignment = assignmentSubmission.getAssignment(); UIJointContainer joint = new UIJointContainer(parent, clientID, "asnn2-submit-editor-widget:"); String asOTP = "AssignmentSubmission."; String asOTPKey = ""; if (assignmentSubmission != null && assignmentSubmission.getId() != null) { asOTPKey += assignmentSubmission.getId(); } else { asOTPKey += EntityBeanLocator.NEW_PREFIX + "1"; } asOTP = asOTP + asOTPKey; String asvOTP = "AssignmentSubmissionVersion."; String asvOTPKey = ""; if (assignmentSubmission != null && assignmentSubmission.getCurrentSubmissionVersion() != null && assignmentSubmission.getCurrentSubmissionVersion().isDraft()) { asvOTPKey += assignmentSubmission.getCurrentSubmissionVersion().getId(); } else { asvOTPKey += EntityBeanLocator.NEW_PREFIX + "1"; } asvOTP = asvOTP + asvOTPKey; //For preview, get a decorated list of disabled="disabled" Map<String, String> disabledAttr = new HashMap<String, String>(); disabledAttr.put("disabled", "disabled"); DecoratorList disabledDecoratorList = new DecoratorList(new UIFreeAttributeDecorator(disabledAttr)); UIForm form = UIForm.make(joint, "form"); //Fill in with submission type specific instructions UIOutput.make(form, "submission_instructions", messageLocator.getMessage("assignment2.student-submit.instructions." + assignment.getSubmissionType())); if (assignment.isHonorPledge()) { UIVerbatim.make(form, "required", messageLocator.getMessage("assignment2.student-submit.required")); } //Rich Text Input String hackSubmissionText = ""; if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_INLINE_ONLY || assignment.getSubmissionType() == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH){ UIOutput.make(form, "submit_text"); if (studentPreviewSubmission) { // TODO FIXME Make this a UIVerbatim for (Object versionObj: asnnSubmissionVersionLocator.getDeliveredBeans().values()) { AssignmentSubmissionVersion version = (AssignmentSubmissionVersion) versionObj; hackSubmissionText = version.getSubmittedText(); UIVerbatim make = UIVerbatim.make(form, "text:", hackSubmissionText); } //UIOutput.make(form, "text:", asnnSubmissionVersionLocator.getDeliveredBeans().size()+""); //UIOutput.make(form, "text:", null,asvOTP + ".submittedText" ); //text_disabled.decorators = disabledDecoratorList; } else if (!preview) { UIInput text = UIInput.make(form, "text:", asvOTP + ".submittedText"); text.mustapply = Boolean.TRUE; richTextEvolver.evolveTextInput(text); } else { //disable textarea UIInput text = UIInput.make(form, "text:", asvOTP + ".submittedText"); UIInput text_disabled = UIInput.make(form, "text_disabled",asvOTP + ".submittedText"); text_disabled.decorators = disabledDecoratorList; } } //Attachment Stuff // the editor will only display attachments for the current version if // it is a draft. otherwise, the user is working on a new submission if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_ATTACH_ONLY || assignment.getSubmissionType() == AssignmentConstants.SUBMIT_INLINE_AND_ATTACH){ UIOutput.make(form, "submit_attachments"); if (!preview) { //Attachments String[] attachmentRefs; if (assignmentSubmission.getCurrentSubmissionVersion().isDraft()) { attachmentRefs = assignmentSubmission.getCurrentSubmissionVersion().getSubmittedAttachmentRefs(); } else { attachmentRefs = new String[] {}; } UIInputMany attachmentInput = UIInputMany.make(form, "attachment_list:", asvOTP + ".submittedAttachmentRefs", attachmentRefs); attachmentInputEvolver.evolveAttachment(attachmentInput); if (!studentPreviewSubmission) { UIInternalLink.make(form, "add_submission_attachments", UIMessage.make("assignment2.student-submit.add_attachments"), new FilePickerHelperViewParams(AddAttachmentHelperProducer.VIEWID, Boolean.TRUE, Boolean.TRUE, 500, 700, asvOTPKey)); } UIOutput.make(form, "no_attachments_yet", messageLocator.getMessage("assignment2.student-submit.no_attachments")); } } // attachment only situations will not return any values in the OTP map; thus, // we won't enter the processing loop in processActionSubmit (and nothing will be saved) // this will force rsf to bind the otp mapping if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_ATTACH_ONLY) { UIInput.make(form, "submitted_text_for_attach_only", asvOTP + ".submittedText"); } if (assignment.isHonorPledge()) { UIOutput.make(joint, "honor_pledge_fieldset"); UIMessage.make(joint, "honor_pledge_label", "assignment2.student-submit.honor_pledge_text"); UIBoundBoolean honorPledgeCheckbox = UIBoundBoolean.make(form, "honor_pledge", "#{AssignmentSubmissionBean.honorPledge}"); if (studentPreviewSubmission) { honorPledgeCheckbox.decorators = disabledDecoratorList; } } form.parameters.add( new UIELBinding("#{AssignmentSubmissionBean.ASOTPKey}", asOTPKey)); form.parameters.add( new UIELBinding("#{AssignmentSubmissionBean.assignmentId}", assignment.getId())); /* * According to the spec, if a student is editing a submision they will * see the Submit,Preview, and Save&Exit buttons. If they are previewing * a submission they will see Submit,Edit, and Save&Exit. */ if (studentPreviewSubmission) { submit_button = UICommand.make(form, "submit_button", UIMessage.make("assignment2.student-submit.submit"), "AssignmentSubmissionBean.processActionSubmit"); save_button = UICommand.make(form, "save_draft_button", UIMessage.make("assignment2.student-submit.save_draft"), "AssignmentSubmissionBean.processActionSaveDraft"); UICommand edit_button = UICommand.make(form, "back_to_edit_button", UIMessage.make("assignment2.student-submit.back_to_edit"), "AssignmentSubmissionBean.processActionBackToEdit"); edit_button.addParameter(new UIELBinding(asvOTP + ".submittedText", hackSubmissionText)); } else { submit_button = UICommand.make(form, "submit_button", UIMessage.make("assignment2.student-submit.submit"), "AssignmentSubmissionBean.processActionSubmit"); preview_button = UICommand.make(form, "preview_button", UIMessage.make("assignment2.student-submit.preview"), "AssignmentSubmissionBean.processActionPreview"); save_button = UICommand.make(form, "save_draft_button", UIMessage.make("assignment2.student-submit.save_draft"), "AssignmentSubmissionBean.processActionSaveDraft"); } // ASNN-288 //UICommand cancel_button = UICommand.make(form, "cancel_button", UIMessage.make("assignment2.student-submit.cancel"), //"#{AssignmentSubmissionBean.processActionCancel}"); if (preview) { submit_button.decorators = disabledDecoratorList; preview_button.decorators = disabledDecoratorList; save_button.decorators = disabledDecoratorList; //cancel_button.decorators = disabledDecoratorList; } }
diff --git a/poem/src/main/java/org/melati/poem/CachedQuery.java b/poem/src/main/java/org/melati/poem/CachedQuery.java index 8471389fe..fbd505a5f 100755 --- a/poem/src/main/java/org/melati/poem/CachedQuery.java +++ b/poem/src/main/java/org/melati/poem/CachedQuery.java @@ -1,140 +1,140 @@ /* * $Source$ * $Revision$ * * Copyright (C) 2000 William Chesters * * Part of Melati (http://melati.org), a framework for the rapid * development of clean, maintainable web applications. * * Melati is free software; Permission is granted to copy, distribute * and/or modify this software under the terms either: * * a) 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, * * or * * b) any version of the Melati Software License, as published * at http://melati.org * * You should have received a copy of the GNU General Public License and * the Melati Software License along with this program; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the * GNU General Public License and visit http://melati.org to obtain the * Melati Software License. * * Feel free to contact the Developers of Melati (http://melati.org), * if you would like to work out a different arrangement than the options * outlined here. It is our intention to allow Melati to be used by as * wide an audience as possible. * * 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. * * Contact details for copyright holder: * * William Chesters <[email protected]> * http://paneris.org/~williamc * Obrechtstraat 114, 2517VX Den Haag, The Netherlands */ package org.melati.poem; import org.melati.util.*; import java.sql.*; import java.util.*; public abstract class CachedQuery { protected PreparedStatementFactory statements = null; protected Vector rows = null; private long tableSerial; protected Table table; private String query; private Table otherTables[]; private long otherTablesSerial[]; public CachedQuery(final Table table, final String query, final Table otherTables[]) { this.table = table; this.query = query; this.otherTables = otherTables; if (otherTables != null) otherTablesSerial = new long[otherTables.length]; } public CachedQuery(final Table table, final String query) { this(table,query,null); } protected PreparedStatementFactory statements() { if (statements == null) statements = new PreparedStatementFactory( table.getDatabase(), query); return statements; } protected abstract Object extract(ResultSet rs) throws SQLException; protected void compute() { Vector rows = this.rows; SessionToken token = PoemThread.sessionToken(); if (rows == null || somethingHasChanged(token.transaction)) { rows = new Vector(); try { ResultSet rs = statements().resultSet(token); try { while (rs.next()) rows.addElement(extract(rs)); } finally { try { rs.close(); } catch (Exception e) {} } } catch (SQLException e) { - throw new SQLSeriousPoemException(e); + throw new SQLSeriousPoemException(e); } this.rows = rows; updateSerials(token.transaction); } } private boolean somethingHasChanged(PoemTransaction transaction) { if (table.serial(transaction) != tableSerial) return true; if (otherTables != null) { for (int i = 0; i < otherTables.length; i++) { if (otherTables[i].serial(transaction) != otherTablesSerial[i]) return true; } } return false; } private void updateSerials(PoemTransaction transaction) { tableSerial = table.serial(transaction); if (otherTables != null) { for (int i=0; i<otherTables.length; i++) { otherTablesSerial[i] = otherTables[i].serial(transaction); } } } public Table getTable() { return table; } public boolean outOfDate() { return somethingHasChanged(PoemThread.transaction()); } }
true
true
protected void compute() { Vector rows = this.rows; SessionToken token = PoemThread.sessionToken(); if (rows == null || somethingHasChanged(token.transaction)) { rows = new Vector(); try { ResultSet rs = statements().resultSet(token); try { while (rs.next()) rows.addElement(extract(rs)); } finally { try { rs.close(); } catch (Exception e) {} } } catch (SQLException e) { throw new SQLSeriousPoemException(e); } this.rows = rows; updateSerials(token.transaction); } }
protected void compute() { Vector rows = this.rows; SessionToken token = PoemThread.sessionToken(); if (rows == null || somethingHasChanged(token.transaction)) { rows = new Vector(); try { ResultSet rs = statements().resultSet(token); try { while (rs.next()) rows.addElement(extract(rs)); } finally { try { rs.close(); } catch (Exception e) {} } } catch (SQLException e) { throw new SQLSeriousPoemException(e); } this.rows = rows; updateSerials(token.transaction); } }
diff --git a/src/state/TaskForce.java b/src/state/TaskForce.java index 855ab2b..9d21462 100644 --- a/src/state/TaskForce.java +++ b/src/state/TaskForce.java @@ -1,269 +1,270 @@ package state; import graphic.Camera; import graphic.Render; import graphic.UIListener; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.geom.Vector2f; public class TaskForce implements UIListener, Comparable<TaskForce> { enum Type { SHIPS, AGENTS } // Internals ========================================================================================================== private String name; private LinkedList<Star> destinations; ///< Route of stars to follow. The first star corresponds to the last star arrival. private int turnsTotal; ///< Number of turns that it takes to move to the next destination. private int turnsTraveled; ///< Number of turns that have been moved towards that destination already. private float speed; ///< Minimun common speed for the stacks. private Empire owner; ///< Empire that owns this TaskForce. private Type type; Map<Design, Integer> stacks; ///< Stacks composing this TaskForce (individual ships and types). // Public Methods ===================================================================================================== TaskForce( String name, Star orbiting, Empire empire, Type type ) { // Base values this.speed = 5; this.owner = empire; this.type = type; this.turnsTraveled = 0; this.turnsTotal = 0; this.name = name; this.stacks = new HashMap<Design, Integer>(); this.destinations = new LinkedList<Star>(); this.destinations.add(orbiting); orbiting.arrive(this); } /** * Truncates the taskforce route up to a specific star. * @param destination Point at which the route is truncated. If the star was not part of the route, nothing happens. * @return True if the route changed. */ public boolean removeFromRoute(Star destination) { // Find if destination is already included. int index = destinations.indexOf(destination); if(index <= 0) return false; while(destinations.size() > index) destinations.removeLast(); return true; } /// @return True if the route changed. public boolean addToRoute(Star destination) { // Check if destination is reachable if(Lane.getDistance(destinations.getLast(), destination) <= 0) return false; destinations.addLast(destination); return true; } void addShips(Design kind, int number) { Integer current = stacks.get(kind); if(current != null) current = 0; stacks.put(kind, current + number); } void turn() { // If no destinations, do nothing. if(destinations.isEmpty()) return; // Check if we need to leave the current star. if(destinations.size() > 1 && turnsTraveled == 0) destinations.getFirst().leave(this); // Move the task force one turn forward. turnsTraveled++; // If we arrived at a star, put ourselves in orbit. if(turnsTraveled == turnsTotal) { turnsTraveled = 0; destinations.removeFirst(); destinations.getFirst().arrive(this); if(destinations.size() > 1) turnsTotal = (int) Math.ceil(Lane.getDistance(destinations.getFirst(), destinations.get(1)) / speed); } } public void render(GameContainer gc, Graphics g, int flags) { g.setColor(owner.color()); if((flags & Render.SELECTED) != 0) { g.setColor(Color.white); // Paint small dots for all our route, but only if the fleet is selected. - Iterator<Star> i = destinations.descendingIterator(); + Iterator<Star> i = destinations.iterator(); Star to = i.next(); Vector2f dir = new Vector2f(); Vector2f zero = new Vector2f(); while(i.hasNext()) { - Star from = i.next(); + Star from = to; + to = i.next(); dir.set(to.getPos()); dir.sub(from.getPos()); int segments = (int) Math.ceil(Lane.getDistance(from, to) / speed); for(int s=1; s<segments; s++) { drawRoutePoint(dir.copy().scale(1.0f * s / segments).add(from.getPos()), g, zero); } } } // Paint the fleet icon. if(turnsTraveled == 0) { // Paint orbiting the star. In this case, each taskforce is separated by a 30 degree angle. Vector2f pos = new Vector2f(20.0f, 0.0f); pos.setTheta(-30 * destinations.getFirst().getDock(this) - 30); drawIcon(destinations.getFirst().getPos(), g, pos); } else { // Paint on route. // drawIcon(dir, g, new Vector2f()); } } private void drawIcon(Vector2f world, Graphics g, Vector2f screenDisp) { Camera.instance().pushLocalTransformation(g, world); g.fillRect(screenDisp.x-4, screenDisp.y-4, 9, 9); g.popTransform(); } private void drawRoutePoint(Vector2f world, Graphics g, Vector2f screenDisp) { Camera.instance().pushLocalTransformation(g, world); g.fillRect(screenDisp.x-2, screenDisp.y-2, 5, 5); g.popTransform(); } @Override public boolean screenCLick(float x, float y, int button) { Vector2f screen = new Vector2f(20.0f, 0.0f); if(turnsTraveled == 0) { // Paint orbiting the star. In this case, each taskforce is separated by a 30 degree angle. screen.setTheta(-30 * destinations.getFirst().getDock(this) - 30); screen.add(Camera.instance().worldToScreen(destinations.getFirst().getPos())); } else { // TODO Click of a force in orbit. return false; } // Compare against mouse screen position. Vector2f local = new Vector2f(x, y).sub(screen); return (local.x * local.x <= 25 && local.y * local.y <= 25); } /** * Task forces are ordered in the following way: * 1.- A task force which orbits a colony of the same empire always goes first. * 2.- Task forces are then ordered by empire, on a fixed order. * 3.- Task forces are ordered by type. * * Apart from these characteristics, task forces are considered equivalent for ordering purposes, so this method is inconsistent with equals() */ @Override public int compareTo(TaskForce o) { // Check if one or other is owner of the star. int aux = 0; Colony col = destinations.getFirst().getColony(); if(col != null) { if(col.owner() == owner) aux += 1; if(col.owner() == o.owner) aux -= 1; if(aux != 0) return aux; } // Check if they belong to different empires. aux = this.owner.name().compareTo(o.owner.name()); if(aux != 0) return aux; // Check their types. return type.ordinal() - o.type.ordinal(); } // void paint(QPainter* painter, QStyleOptionGraphicsItem*, QWidget*) // { // // Draw route to final destination. // painter.save(); // if(true)//isSelected()) // { // // Draw lines. // QPointF last = QPoint(0,0); // painter.setPen(QPen(Qt::red, 1, Qt::DashLine)); // foreach(Star* s, to) // { // EchoDebug(String("Drawing from (%1,%2) to (%3,%4)").arg(last.x()).arg(last.y()).arg(s.pos().x()).arg(s.pos().y())); // painter.drawLine(last, s.pos() - pos()); // last = s.pos() - pos(); // } // } // painter.restore(); // // // Set star position and draw it. // painter.setBrush(owner.color()); // painter.drawRect(-5, -5, 10, 10); // if(isSelected()) // painter.drawRect(-7, -7, 14, 14); // // } // // QRectF boundingRect() // { // return QRectF(-5, -5, 10, 10); // } // void mousePressEvent(QGraphicsSceneMouseEvent* event) // { // TODO // if(isSelected()) // { // // When a star is clicked, the route needs to be changed for this TaskForce. // Star* star = dynamic_cast<Star*>(scene().itemAt(event.scenePos(), )); // if(star) // { // if(event.button() == Qt::LeftButton) // addToRoute(star); // else // removeFromRoute(star); // event.accept(); // } // } // } }
false
true
public void render(GameContainer gc, Graphics g, int flags) { g.setColor(owner.color()); if((flags & Render.SELECTED) != 0) { g.setColor(Color.white); // Paint small dots for all our route, but only if the fleet is selected. Iterator<Star> i = destinations.descendingIterator(); Star to = i.next(); Vector2f dir = new Vector2f(); Vector2f zero = new Vector2f(); while(i.hasNext()) { Star from = i.next(); dir.set(to.getPos()); dir.sub(from.getPos()); int segments = (int) Math.ceil(Lane.getDistance(from, to) / speed); for(int s=1; s<segments; s++) { drawRoutePoint(dir.copy().scale(1.0f * s / segments).add(from.getPos()), g, zero); } } } // Paint the fleet icon. if(turnsTraveled == 0) { // Paint orbiting the star. In this case, each taskforce is separated by a 30 degree angle. Vector2f pos = new Vector2f(20.0f, 0.0f); pos.setTheta(-30 * destinations.getFirst().getDock(this) - 30); drawIcon(destinations.getFirst().getPos(), g, pos); } else { // Paint on route. // drawIcon(dir, g, new Vector2f()); } }
public void render(GameContainer gc, Graphics g, int flags) { g.setColor(owner.color()); if((flags & Render.SELECTED) != 0) { g.setColor(Color.white); // Paint small dots for all our route, but only if the fleet is selected. Iterator<Star> i = destinations.iterator(); Star to = i.next(); Vector2f dir = new Vector2f(); Vector2f zero = new Vector2f(); while(i.hasNext()) { Star from = to; to = i.next(); dir.set(to.getPos()); dir.sub(from.getPos()); int segments = (int) Math.ceil(Lane.getDistance(from, to) / speed); for(int s=1; s<segments; s++) { drawRoutePoint(dir.copy().scale(1.0f * s / segments).add(from.getPos()), g, zero); } } } // Paint the fleet icon. if(turnsTraveled == 0) { // Paint orbiting the star. In this case, each taskforce is separated by a 30 degree angle. Vector2f pos = new Vector2f(20.0f, 0.0f); pos.setTheta(-30 * destinations.getFirst().getDock(this) - 30); drawIcon(destinations.getFirst().getPos(), g, pos); } else { // Paint on route. // drawIcon(dir, g, new Vector2f()); } }
diff --git a/runtime/src/com/sun/xml/bind/v2/model/impl/ModelBuilder.java b/runtime/src/com/sun/xml/bind/v2/model/impl/ModelBuilder.java index 02872ac8..aeb2f139 100644 --- a/runtime/src/com/sun/xml/bind/v2/model/impl/ModelBuilder.java +++ b/runtime/src/com/sun/xml/bind/v2/model/impl/ModelBuilder.java @@ -1,291 +1,291 @@ package com.sun.xml.bind.v2.model.impl; import java.util.HashMap; import java.util.Map; import java.util.HashSet; import java.util.Set; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; import com.sun.xml.bind.v2.model.annotation.AnnotationReader; import com.sun.xml.bind.v2.model.annotation.Locatable; import com.sun.xml.bind.v2.model.core.ClassInfo; import com.sun.xml.bind.v2.model.core.ErrorHandler; import com.sun.xml.bind.v2.model.core.LeafInfo; import com.sun.xml.bind.v2.model.core.NonElement; import com.sun.xml.bind.v2.model.core.PropertyInfo; import com.sun.xml.bind.v2.model.core.Ref; import com.sun.xml.bind.v2.model.core.RegistryInfo; import com.sun.xml.bind.v2.model.core.TypeInfo; import com.sun.xml.bind.v2.model.core.TypeInfoSet; import com.sun.xml.bind.v2.model.core.PropertyKind; import com.sun.xml.bind.v2.model.nav.Navigator; import com.sun.xml.bind.v2.runtime.IllegalAnnotationException; /** * Builds a {@link TypeInfoSet} (a set of JAXB properties) * by using {@link ElementInfoImpl} and {@link ClassInfoImpl}. * from annotated Java classes. * * <p> * This class uses {@link Navigator} and {@link AnnotationReader} to * work with arbitrary annotation source and arbitrary Java model. * For this purpose this class is parameterized. * * @author Kohsuke Kawaguchi ([email protected]) */ public class ModelBuilder<T,C,F,M> { /** * {@link TypeInfo}s that are built will go into this set. */ final TypeInfoSetImpl<T,C,F,M> typeInfoSet; public final AnnotationReader<T,C,F,M> reader; public final Navigator<T,C,F,M> nav; /** * Used to detect collisions among global type names. */ private final Map<QName,TypeInfo> typeNames = new HashMap<QName, TypeInfo>(); /** * JAXB doesn't want to use namespaces unless we are told to, but WS-I BP * conformace requires JAX-RPC to always use a non-empty namespace URI. * (see http://www.ws-i.org/Profiles/BasicProfile-1.0-2004-04-16.html#WSDLTYPES R2105) * * <p> * To work around this issue, we allow the use of the empty namespaces to be * replaced by a particular designated namespace URI. * * <p> * This field keeps the value of that replacing namespace URI. * When there's no replacement, this field is set to "". */ public final String defaultNsUri; /** * Packages whose registries are already added. */ private final Set<String> registries = new HashSet<String>(); /** * @see #setErrorHandler */ private ErrorHandler errorHandler; private boolean hadError; private final ErrorHandler proxyErrorHandler = new ErrorHandler() { public void error(IllegalAnnotationException e) { reportError(e); } }; public ModelBuilder( AnnotationReader<T,C,F,M> reader, Navigator<T,C,F,M> navigator, String defaultNamespaceRemap ) { this.reader = reader; this.nav = navigator; if(defaultNamespaceRemap==null) defaultNamespaceRemap = ""; this.defaultNsUri = defaultNamespaceRemap; reader.setErrorHandler(proxyErrorHandler); typeInfoSet = createTypeInfoSet(); } protected TypeInfoSetImpl<T,C,F,M> createTypeInfoSet() { return new TypeInfoSetImpl(nav,reader,BuiltinLeafInfoImpl.createLeaves(nav)); } /** * Builds a JAXB {@link ClassInfo} model from a given class declaration * and adds that to this model owner. * * <p> * Return type is either {@link ClassInfo} or {@link LeafInfo} (for types like * {@link String} or {@link Enum}-derived ones) */ public NonElement<T,C> getClassInfo( C clazz, Locatable upstream ) { assert clazz!=null; NonElement<T,C> r = typeInfoSet.getClassInfo(clazz); if(r!=null) return r; if(nav.isEnum(clazz)) { EnumLeafInfoImpl<T,C,F,M> li = createEnumLeafInfo(clazz,upstream); typeInfoSet.add(li); r = li; } else { ClassInfoImpl<T,C,F,M> ci = createClassInfo(clazz,upstream); typeInfoSet.add(ci); // compute the closure by eagerly expanding references for( PropertyInfo<T,C> p : ci.getProperties() ) { if(p.kind()== PropertyKind.REFERENCE) { // make sure that we have a registry for this package String pkg = nav.getPackageName(ci.getClazz()); if(registries.add(pkg)) { // insert the package's object factory - ClassDeclT c = nav.findClass(pkg + ".ObjectFactory",ci.getClazz()); + C c = nav.findClass(pkg + ".ObjectFactory",ci.getClazz()); if(c!=null) addRegistry(c,(Locatable)p); } } - for( TypeInfo<TypeT,ClassDeclT> t : p.ref() ) + for( TypeInfo<T,C> t : p.ref() ) ; // just compute a reference should be suffice } ci.getBaseClass(); r = ci; } addTypeName(r); return r; } /** * Checks the uniqueness of the type name. */ private void addTypeName(NonElement<T, C> r) { QName t = r.getTypeName(); if(t==null) return; TypeInfo old = typeNames.put(t,r); if(old!=null) { // collision reportError(new IllegalAnnotationException( Messages.CONFLICTING_XML_TYPE_MAPPING.format(r.getTypeName()), old, r )); } } /** * Have the builder recognize the type (if it hasn't done so yet), * and returns a {@link NonElement} that represents it. * * @return * always non-null. */ public NonElement<T,C> getTypeInfo(T t,Locatable upstream) { NonElement<T,C> r = typeInfoSet.getTypeInfo(t); if(r!=null) return r; if(nav.isArray(t)) { // no need for checking byte[], because above typeInfoset.getTypeInfo() would return non-null ArrayInfoImpl<T,C,F,M> ai = createArrayInfo(upstream, t); addTypeName(ai); typeInfoSet.add(ai); return ai; } C c = nav.asDecl(t); assert c!=null : t.toString()+" must be a leaf, but we failed to recognize it."; return getClassInfo(c,upstream); } /** * This method is used to add a root reference to a model. */ public NonElement<T,C> getTypeInfo(Ref<T,C> ref) { // TODO: handle XmlValueList assert !ref.valueList; C c = nav.asDecl(ref.type); if(c!=null && reader.getClassAnnotation(XmlRegistry.class,c,null/*TODO: is this right?*/)!=null) { if(registries.add(nav.getPackageName(c))) addRegistry(c,null); return null; // TODO: is this correct? } else return getTypeInfo(ref.type,null); } protected EnumLeafInfoImpl<T,C,F,M> createEnumLeafInfo(C clazz,Locatable upstream) { return new EnumLeafInfoImpl<T,C,F,M>(this,upstream,clazz,nav.use(clazz)); } protected ClassInfoImpl<T,C,F,M> createClassInfo( C clazz, Locatable upstream ) { return new ClassInfoImpl<T,C,F,M>(this,upstream,clazz); } protected ElementInfoImpl<T,C,F,M> createElementInfo( RegistryInfoImpl<T,C,F,M> registryInfo, M m) throws IllegalAnnotationException { return new ElementInfoImpl<T,C,F,M>(this,registryInfo,m); } protected ArrayInfoImpl<T,C,F,M> createArrayInfo(Locatable upstream, T arrayType) { return new ArrayInfoImpl<T, C, F, M>(this,upstream,arrayType); } /** * Visits a class with {@link XmlRegistry} and records all the element mappings * in it. */ public RegistryInfo<T,C> addRegistry(C registryClass, Locatable upstream ) { return new RegistryInfoImpl<T,C,F,M>(this,upstream,registryClass); } private boolean linked; /** * Called after all the classes are added to the type set * to "link" them together. * * <p> * Don't expose implementation classes in the signature. * * @return * fully built {@link TypeInfoSet} that represents the model, * or null if there was an error. */ public TypeInfoSet<T,C,F,M> link() { assert !linked; linked = true; for( ElementInfoImpl ei : typeInfoSet.getAllElements() ) ei.link(); for( ClassInfoImpl ci : typeInfoSet.beans().values() ) ci.link(); for( EnumLeafInfoImpl li : typeInfoSet.enums().values() ) li.link(); if(hadError) return null; else return typeInfoSet; } // // // error handling // // /** * Sets the error handler that receives errors discovered during the model building. * * @param errorHandler * can be null. */ public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } public final void reportError(IllegalAnnotationException e) { hadError = true; if(errorHandler!=null) errorHandler.error(e); } }
false
true
public NonElement<T,C> getClassInfo( C clazz, Locatable upstream ) { assert clazz!=null; NonElement<T,C> r = typeInfoSet.getClassInfo(clazz); if(r!=null) return r; if(nav.isEnum(clazz)) { EnumLeafInfoImpl<T,C,F,M> li = createEnumLeafInfo(clazz,upstream); typeInfoSet.add(li); r = li; } else { ClassInfoImpl<T,C,F,M> ci = createClassInfo(clazz,upstream); typeInfoSet.add(ci); // compute the closure by eagerly expanding references for( PropertyInfo<T,C> p : ci.getProperties() ) { if(p.kind()== PropertyKind.REFERENCE) { // make sure that we have a registry for this package String pkg = nav.getPackageName(ci.getClazz()); if(registries.add(pkg)) { // insert the package's object factory ClassDeclT c = nav.findClass(pkg + ".ObjectFactory",ci.getClazz()); if(c!=null) addRegistry(c,(Locatable)p); } } for( TypeInfo<TypeT,ClassDeclT> t : p.ref() ) ; // just compute a reference should be suffice } ci.getBaseClass(); r = ci; } addTypeName(r); return r; }
public NonElement<T,C> getClassInfo( C clazz, Locatable upstream ) { assert clazz!=null; NonElement<T,C> r = typeInfoSet.getClassInfo(clazz); if(r!=null) return r; if(nav.isEnum(clazz)) { EnumLeafInfoImpl<T,C,F,M> li = createEnumLeafInfo(clazz,upstream); typeInfoSet.add(li); r = li; } else { ClassInfoImpl<T,C,F,M> ci = createClassInfo(clazz,upstream); typeInfoSet.add(ci); // compute the closure by eagerly expanding references for( PropertyInfo<T,C> p : ci.getProperties() ) { if(p.kind()== PropertyKind.REFERENCE) { // make sure that we have a registry for this package String pkg = nav.getPackageName(ci.getClazz()); if(registries.add(pkg)) { // insert the package's object factory C c = nav.findClass(pkg + ".ObjectFactory",ci.getClazz()); if(c!=null) addRegistry(c,(Locatable)p); } } for( TypeInfo<T,C> t : p.ref() ) ; // just compute a reference should be suffice } ci.getBaseClass(); r = ci; } addTypeName(r); return r; }
diff --git a/src/main/java/com/couchbase/client/vbucket/config/DefaultConfigFactory.java b/src/main/java/com/couchbase/client/vbucket/config/DefaultConfigFactory.java index 410a43d8..ce807577 100644 --- a/src/main/java/com/couchbase/client/vbucket/config/DefaultConfigFactory.java +++ b/src/main/java/com/couchbase/client/vbucket/config/DefaultConfigFactory.java @@ -1,203 +1,203 @@ /** * Copyright (C) 2009-2013 Couchbase, 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 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 DEALING * IN THE SOFTWARE. */ package com.couchbase.client.vbucket.config; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import net.spy.memcached.HashAlgorithm; import net.spy.memcached.HashAlgorithmRegistry; import net.spy.memcached.compat.SpyObject; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; /** * A DefaultConfigFactory. */ public class DefaultConfigFactory extends SpyObject implements ConfigFactory { @Override public Config create(File filename) { if (filename == null || "".equals(filename.getName())) { throw new IllegalArgumentException("Filename is empty."); } StringBuilder sb = new StringBuilder(); try { FileInputStream fis = new FileInputStream(filename); BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); String str; while ((str = reader.readLine()) != null) { sb.append(str); } } catch (IOException e) { throw new ConfigParsingException("Exception reading input file: " + filename, e); } return create(sb.toString()); } @Override public Config create(String data) { try { JSONObject jsonObject = new JSONObject(data); return parseJSON(jsonObject); } catch (JSONException e) { throw new ConfigParsingException("Exception parsing JSON data: " + data, e); } } @Override public Config create(JSONObject jsonObject) { try { return parseJSON(jsonObject); } catch (JSONException e) { throw new ConfigParsingException("Exception parsing JSON data: " + jsonObject, e); } } private Config parseJSON(JSONObject jsonObject) throws JSONException { // the incoming config could be cache or EP object types, JSON envelope // picked apart if (!jsonObject.has("vBucketServerMap")) { return parseCacheJSON(jsonObject); } return parseEpJSON(jsonObject); } private Config parseCacheJSON(JSONObject jsonObject) throws JSONException { JSONArray nodes = jsonObject.getJSONArray("nodes"); if (nodes.length() <= 0) { throw new ConfigParsingException("Empty nodes list."); } int serversCount = nodes.length(); CacheConfig config = new CacheConfig(serversCount); populateServers(config, nodes); return config; } /* ep is for ep-engine, a.k.a. couchbase */ private Config parseEpJSON(JSONObject jsonObject) throws JSONException { JSONObject vbMap = jsonObject.getJSONObject("vBucketServerMap"); String algorithm = vbMap.getString("hashAlgorithm"); HashAlgorithm hashAlgorithm = HashAlgorithmRegistry.lookupHashAlgorithm(algorithm); if (hashAlgorithm == null) { throw new IllegalArgumentException("Unhandled hash algorithm type: " + algorithm); } int replicasCount = vbMap.getInt("numReplicas"); if (replicasCount > VBucket.MAX_REPLICAS) { throw new ConfigParsingException("Expected number <= " + VBucket.MAX_REPLICAS + " for replicas."); } JSONArray servers = vbMap.getJSONArray("serverList"); if (servers.length() <= 0) { throw new ConfigParsingException("Empty servers list."); } int serversCount = servers.length(); JSONArray vbuckets = vbMap.getJSONArray("vBucketMap"); int vbucketsCount = vbuckets.length(); if (vbucketsCount == 0 || (vbucketsCount & (vbucketsCount - 1)) != 0) { - throw new ConfigParsingException("Number of buckets must be a power of " + throw new ConfigParsingException("Number of vBuckets must be a power of " + "two, > 0 and <= " + VBucket.MAX_BUCKETS); } List<String> populateServers = populateServers(servers); List<VBucket> populateVbuckets = populateVbuckets(vbuckets); List<URL> couchServers = populateCouchServers(jsonObject.getJSONArray("nodes")); DefaultConfig config = new DefaultConfig(hashAlgorithm, serversCount, replicasCount, vbucketsCount, populateServers, populateVbuckets, couchServers); return config; } private List<URL> populateCouchServers(JSONArray nodes) throws JSONException{ List<URL> nodeNames = new ArrayList<URL>(); for (int i = 0; i < nodes.length(); i++) { JSONObject node = nodes.getJSONObject(i); if (node.has("couchApiBase")) { try { nodeNames.add(new URL(node.getString("couchApiBase"))); } catch (MalformedURLException e) { throw new JSONException("Got bad couchApiBase URL from config"); } } } return nodeNames; } private List<String> populateServers(JSONArray servers) throws JSONException { List<String> serverNames = new ArrayList<String>(); for (int i = 0; i < servers.length(); i++) { String server = servers.getString(i); serverNames.add(server); } return serverNames; } private void populateServers(CacheConfig config, JSONArray nodes) throws JSONException { List<String> serverNames = new ArrayList<String>(); for (int i = 0; i < nodes.length(); i++) { JSONObject node = nodes.getJSONObject(i); String webHostPort = node.getString("hostname"); String[] splitHostPort = webHostPort.split(":"); JSONObject portsList = node.getJSONObject("ports"); int port = portsList.getInt("direct"); serverNames.add(splitHostPort[0] + ":" + port); } config.setServers(serverNames); } private List<VBucket> populateVbuckets(JSONArray jsonVbuckets) throws JSONException { List<VBucket> vBuckets = new ArrayList<VBucket>(); for (int i = 0; i < jsonVbuckets.length(); i++) { JSONArray rows = jsonVbuckets.getJSONArray(i); int master = rows.getInt(0); int[] replicas = new int[VBucket.MAX_REPLICAS]; for (int j = 1; j < rows.length(); j++) { replicas[j - 1] = rows.getInt(j); } vBuckets.add(new VBucket(master, replicas)); } return vBuckets; } }
true
true
private Config parseEpJSON(JSONObject jsonObject) throws JSONException { JSONObject vbMap = jsonObject.getJSONObject("vBucketServerMap"); String algorithm = vbMap.getString("hashAlgorithm"); HashAlgorithm hashAlgorithm = HashAlgorithmRegistry.lookupHashAlgorithm(algorithm); if (hashAlgorithm == null) { throw new IllegalArgumentException("Unhandled hash algorithm type: " + algorithm); } int replicasCount = vbMap.getInt("numReplicas"); if (replicasCount > VBucket.MAX_REPLICAS) { throw new ConfigParsingException("Expected number <= " + VBucket.MAX_REPLICAS + " for replicas."); } JSONArray servers = vbMap.getJSONArray("serverList"); if (servers.length() <= 0) { throw new ConfigParsingException("Empty servers list."); } int serversCount = servers.length(); JSONArray vbuckets = vbMap.getJSONArray("vBucketMap"); int vbucketsCount = vbuckets.length(); if (vbucketsCount == 0 || (vbucketsCount & (vbucketsCount - 1)) != 0) { throw new ConfigParsingException("Number of buckets must be a power of " + "two, > 0 and <= " + VBucket.MAX_BUCKETS); } List<String> populateServers = populateServers(servers); List<VBucket> populateVbuckets = populateVbuckets(vbuckets); List<URL> couchServers = populateCouchServers(jsonObject.getJSONArray("nodes")); DefaultConfig config = new DefaultConfig(hashAlgorithm, serversCount, replicasCount, vbucketsCount, populateServers, populateVbuckets, couchServers); return config; }
private Config parseEpJSON(JSONObject jsonObject) throws JSONException { JSONObject vbMap = jsonObject.getJSONObject("vBucketServerMap"); String algorithm = vbMap.getString("hashAlgorithm"); HashAlgorithm hashAlgorithm = HashAlgorithmRegistry.lookupHashAlgorithm(algorithm); if (hashAlgorithm == null) { throw new IllegalArgumentException("Unhandled hash algorithm type: " + algorithm); } int replicasCount = vbMap.getInt("numReplicas"); if (replicasCount > VBucket.MAX_REPLICAS) { throw new ConfigParsingException("Expected number <= " + VBucket.MAX_REPLICAS + " for replicas."); } JSONArray servers = vbMap.getJSONArray("serverList"); if (servers.length() <= 0) { throw new ConfigParsingException("Empty servers list."); } int serversCount = servers.length(); JSONArray vbuckets = vbMap.getJSONArray("vBucketMap"); int vbucketsCount = vbuckets.length(); if (vbucketsCount == 0 || (vbucketsCount & (vbucketsCount - 1)) != 0) { throw new ConfigParsingException("Number of vBuckets must be a power of " + "two, > 0 and <= " + VBucket.MAX_BUCKETS); } List<String> populateServers = populateServers(servers); List<VBucket> populateVbuckets = populateVbuckets(vbuckets); List<URL> couchServers = populateCouchServers(jsonObject.getJSONArray("nodes")); DefaultConfig config = new DefaultConfig(hashAlgorithm, serversCount, replicasCount, vbucketsCount, populateServers, populateVbuckets, couchServers); return config; }
diff --git a/plugins/org.eclipse.viatra2.emf.incquery.runtime/src/org/eclipse/viatra2/emf/incquery/runtime/internal/matcherbuilder/EPMBodyToPSystem.java b/plugins/org.eclipse.viatra2.emf.incquery.runtime/src/org/eclipse/viatra2/emf/incquery/runtime/internal/matcherbuilder/EPMBodyToPSystem.java index f144092a..f155db74 100644 --- a/plugins/org.eclipse.viatra2.emf.incquery.runtime/src/org/eclipse/viatra2/emf/incquery/runtime/internal/matcherbuilder/EPMBodyToPSystem.java +++ b/plugins/org.eclipse.viatra2.emf.incquery.runtime/src/org/eclipse/viatra2/emf/incquery/runtime/internal/matcherbuilder/EPMBodyToPSystem.java @@ -1,265 +1,265 @@ /******************************************************************************* * Copyright (c) 2004-2010 Gabor Bergmann and Daniel Varro * 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: * Gabor Bergmann - initial API and implementation *******************************************************************************/ package org.eclipse.viatra2.emf.incquery.runtime.internal.matcherbuilder; import java.util.List; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.Buildable; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.RetePatternBuildException; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.psystem.PSystem; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.psystem.PVariable; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.psystem.basicdeferred.Equality; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.psystem.basicdeferred.ExportedParameter; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.psystem.basicdeferred.NegativePatternCall; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.psystem.basicenumerables.PositivePatternCall; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.psystem.basicenumerables.TypeBinary; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.psystem.basicenumerables.TypeTernary; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.construction.psystem.basicenumerables.TypeUnary; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.matcher.IPatternMatcherContext; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.matcher.IPatternMatcherContext.EdgeInterpretation; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.tuple.FlatTuple; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.tuple.Tuple; import org.eclipse.viatra2.patternlanguage.core.helper.CorePatternLanguageHelper; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.BoolValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.Constraint; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.DoubleValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.IntValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PathExpressionConstraint; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PathExpressionHead; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PathExpressionTail; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.Pattern; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PatternBody; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.PatternCompositionConstraint; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.StringValue; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.Type; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.ValueReference; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.Variable; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.VariableReference; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.VariableValue; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.ClassType; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.EClassifierConstraint; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.EnumValue; import org.eclipse.viatra2.patternlanguage.eMFPatternLanguage.ReferenceType; /** * @author Bergmann Gábor * */ public class EPMBodyToPSystem<StubHandle, Collector> { protected Pattern pattern; protected PatternBody body; protected IPatternMatcherContext<Pattern> context; protected Buildable<Pattern, StubHandle, Collector> buildable; protected PSystem<Pattern, StubHandle, Collector> pSystem; String patternFQN; /** * @param pattern * @param body * @param builder * @param buildable */ public EPMBodyToPSystem(Pattern pattern, PatternBody body, IPatternMatcherContext<Pattern> context, Buildable<Pattern, StubHandle, Collector> buildable) { super(); this.pattern = pattern; this.body = body; this.context = context; this.buildable = buildable; patternFQN = CorePatternLanguageHelper.getFullyQualifiedName(pattern).toString(); } public PSystem<Pattern, StubHandle, Collector> toPSystem() throws RetePatternBuildException { try { if (this.pSystem == null) { this.pSystem = new PSystem<Pattern, StubHandle, Collector>(context, buildable, pattern); // TODO // preProcessAssignments(); preProcessParameters(); gatherBodyConstraints(); gatherInequalityAssertions(); } return pSystem; } catch (RetePatternBuildException e) { e.setPatternDescription(pattern); throw e; } } public PVariable[] symbolicParameterArray() throws RetePatternBuildException { toPSystem(); EList<Variable> symParameters = pattern.getParameters(); int arity = symParameters.size(); PVariable[] result = new PVariable[arity]; for (int i=0; i<arity; ++i) result[i] = getPNode(symParameters.get(i)); return result; } protected PVariable getPNode(String name) { return pSystem.getOrCreateVariableByName(name); } protected PVariable getPNode(Variable variable) { return getPNode(variable.getName()); } protected PVariable getPNode(VariableReference variable) { return getPNode(variable.getVar()); } protected Tuple getPNodeTuple(List<VariableReference> variables) { PVariable[] pNodeArray = getPNodeArray(variables); return new FlatTuple(pNodeArray); } public PVariable[] getPNodeArray(List<VariableReference> variables) { int k = 0; PVariable[] pNodeArray = new PVariable[variables.size()]; for (VariableReference varRef : variables) { pNodeArray[k++] = getPNode(varRef); } return pNodeArray; } protected PVariable getPNode(ValueReference reference) throws RetePatternBuildException { if (reference instanceof VariableValue) return getPNode(((VariableValue) reference).getValue()); else if (reference instanceof IntValue) return pSystem.newConstantVariable(((IntValue) reference).getValue()); else if (reference instanceof StringValue) return pSystem.newConstantVariable(((StringValue) reference).getValue()); else if (reference instanceof EnumValue) // EMF-specific return pSystem.newConstantVariable(((EnumValue) reference).getLiteral().getInstance()); else if (reference instanceof DoubleValue) { Double dVal = ((DoubleValue) reference).getValue(); return pSystem.newConstantVariable(new Double(dVal)); } else if (reference instanceof BoolValue) { Boolean b = ((BoolValue) reference).isValue(); return pSystem.newConstantVariable(b); } else throw new RetePatternBuildException( "Unsupported value reference of type {1} from EPackage {2} currently unsupported by pattern builder in pattern {3}.", new String[]{ reference.eClass().getEPackage().getNsURI(), reference.eClass().getName(), }, pattern); } protected PVariable newVirtual() { return pSystem.newVirtualVariable(); } // protected Tuple getPNodeTuple(List<? extends ValueReference> references) throws RetePatternBuildException { // PVariable[] pNodeArray = getPNodeArray(references); // return new FlatTuple(pNodeArray); // } // public PVariable[] getPNodeArray(List<? extends ValueReference> references) throws RetePatternBuildException { // int k = 0; // PVariable[] pNodeArray = new PVariable[references.size()]; // for (ValueReference varRef : references) { // pNodeArray[k++] = getPNode(varRef); // } // return pNodeArray; // } private void preProcessParameters() { EList<Variable> parameters = pattern.getParameters(); for (Variable variable : parameters) { new ExportedParameter<Pattern, StubHandle>(pSystem, getPNode(variable), variable.getName()); } } private void gatherBodyConstraints() throws RetePatternBuildException { EList<Constraint> constraints = body.getConstraints(); for (Constraint constraint : constraints) { gatherConstraint(constraint); } } /** * @param constraint * @throws RetePatternBuildException */ protected void gatherConstraint(Constraint constraint) throws RetePatternBuildException { if (constraint instanceof EClassifierConstraint) { // EMF-specific EClassifierConstraint constraint2 = (EClassifierConstraint) constraint; //TODO Gabor, please check the following line EClassifier classname = ((ClassType)constraint2.getType()).getClassname(); PVariable pNode = getPNode(constraint2.getVar()); new TypeUnary<Pattern, StubHandle>(pSystem, pNode, classname); } else if (constraint instanceof PatternCompositionConstraint) { PatternCompositionConstraint constraint2 = (PatternCompositionConstraint) constraint; Pattern patternRef = constraint2.getPatternRef(); Tuple pNodeTuple = getPNodeTuple(constraint2.getParameters()); if (constraint2.isNegative()) - new NegativePatternCall<Pattern, StubHandle>(pSystem, pNodeTuple, pattern); + new NegativePatternCall<Pattern, StubHandle>(pSystem, pNodeTuple, patternRef); else - new PositivePatternCall<Pattern, StubHandle>(pSystem, pNodeTuple, pattern); + new PositivePatternCall<Pattern, StubHandle>(pSystem, pNodeTuple, patternRef); } else if (constraint instanceof PathExpressionConstraint) { // TODO advanced features here PathExpressionConstraint pathExpression = (PathExpressionConstraint) constraint; PathExpressionHead head = pathExpression.getHead(); PVariable currentSrc = getPNode(head.getSrc()); PVariable finalDst = getPNode(head.getDst()); Type currentPathSegmentType = head.getType(); // IGNORED PathExpressionTail currentTail = head.getTail(); while (currentTail != null) { currentPathSegmentType = currentTail.getType(); currentTail = currentTail.getTail(); PVariable intermediate = newVirtual(); gatherPathSegment(currentPathSegmentType, currentSrc, intermediate); currentSrc = intermediate; } new Equality<Pattern, StubHandle>(pSystem, currentSrc, finalDst); // TODO OTHER CONSTRAINT TYPES, most notably CheckConstraint } else { throw new RetePatternBuildException( "Unsupported constraint type {1} in pattern {2}.", new String[]{constraint.eClass().getName(), patternFQN}, pattern); } } protected void gatherPathSegment(Type segmentType, PVariable src, PVariable trg) throws RetePatternBuildException { if (segmentType instanceof ReferenceType) { // EMF-specific EStructuralFeature typeObject = ((ReferenceType) segmentType).getRefname(); if (context.edgeInterpretation() == EdgeInterpretation.TERNARY) { new TypeTernary<Pattern, StubHandle>(pSystem, context, newVirtual(), src, trg, typeObject); } else { new TypeBinary<Pattern, StubHandle>(pSystem, context, src, trg, typeObject); } } else throw new RetePatternBuildException( "Unsupported path segment type {1} in pattern {2}.", new String[]{segmentType.eClass().getName(), patternFQN}, pattern); } private void gatherInequalityAssertions() { // TODO CHECK IF SHAREABLE, ETC. } }
false
true
protected void gatherConstraint(Constraint constraint) throws RetePatternBuildException { if (constraint instanceof EClassifierConstraint) { // EMF-specific EClassifierConstraint constraint2 = (EClassifierConstraint) constraint; //TODO Gabor, please check the following line EClassifier classname = ((ClassType)constraint2.getType()).getClassname(); PVariable pNode = getPNode(constraint2.getVar()); new TypeUnary<Pattern, StubHandle>(pSystem, pNode, classname); } else if (constraint instanceof PatternCompositionConstraint) { PatternCompositionConstraint constraint2 = (PatternCompositionConstraint) constraint; Pattern patternRef = constraint2.getPatternRef(); Tuple pNodeTuple = getPNodeTuple(constraint2.getParameters()); if (constraint2.isNegative()) new NegativePatternCall<Pattern, StubHandle>(pSystem, pNodeTuple, pattern); else new PositivePatternCall<Pattern, StubHandle>(pSystem, pNodeTuple, pattern); } else if (constraint instanceof PathExpressionConstraint) { // TODO advanced features here PathExpressionConstraint pathExpression = (PathExpressionConstraint) constraint; PathExpressionHead head = pathExpression.getHead(); PVariable currentSrc = getPNode(head.getSrc()); PVariable finalDst = getPNode(head.getDst()); Type currentPathSegmentType = head.getType(); // IGNORED PathExpressionTail currentTail = head.getTail(); while (currentTail != null) { currentPathSegmentType = currentTail.getType(); currentTail = currentTail.getTail(); PVariable intermediate = newVirtual(); gatherPathSegment(currentPathSegmentType, currentSrc, intermediate); currentSrc = intermediate; } new Equality<Pattern, StubHandle>(pSystem, currentSrc, finalDst); // TODO OTHER CONSTRAINT TYPES, most notably CheckConstraint } else { throw new RetePatternBuildException( "Unsupported constraint type {1} in pattern {2}.", new String[]{constraint.eClass().getName(), patternFQN}, pattern); } }
protected void gatherConstraint(Constraint constraint) throws RetePatternBuildException { if (constraint instanceof EClassifierConstraint) { // EMF-specific EClassifierConstraint constraint2 = (EClassifierConstraint) constraint; //TODO Gabor, please check the following line EClassifier classname = ((ClassType)constraint2.getType()).getClassname(); PVariable pNode = getPNode(constraint2.getVar()); new TypeUnary<Pattern, StubHandle>(pSystem, pNode, classname); } else if (constraint instanceof PatternCompositionConstraint) { PatternCompositionConstraint constraint2 = (PatternCompositionConstraint) constraint; Pattern patternRef = constraint2.getPatternRef(); Tuple pNodeTuple = getPNodeTuple(constraint2.getParameters()); if (constraint2.isNegative()) new NegativePatternCall<Pattern, StubHandle>(pSystem, pNodeTuple, patternRef); else new PositivePatternCall<Pattern, StubHandle>(pSystem, pNodeTuple, patternRef); } else if (constraint instanceof PathExpressionConstraint) { // TODO advanced features here PathExpressionConstraint pathExpression = (PathExpressionConstraint) constraint; PathExpressionHead head = pathExpression.getHead(); PVariable currentSrc = getPNode(head.getSrc()); PVariable finalDst = getPNode(head.getDst()); Type currentPathSegmentType = head.getType(); // IGNORED PathExpressionTail currentTail = head.getTail(); while (currentTail != null) { currentPathSegmentType = currentTail.getType(); currentTail = currentTail.getTail(); PVariable intermediate = newVirtual(); gatherPathSegment(currentPathSegmentType, currentSrc, intermediate); currentSrc = intermediate; } new Equality<Pattern, StubHandle>(pSystem, currentSrc, finalDst); // TODO OTHER CONSTRAINT TYPES, most notably CheckConstraint } else { throw new RetePatternBuildException( "Unsupported constraint type {1} in pattern {2}.", new String[]{constraint.eClass().getName(), patternFQN}, pattern); } }
diff --git a/email2/src/com/android/email/provider/AttachmentProvider.java b/email2/src/com/android/email/provider/AttachmentProvider.java index e0133156c..71955851e 100644 --- a/email2/src/com/android/email/provider/AttachmentProvider.java +++ b/email2/src/com/android/email/provider/AttachmentProvider.java @@ -1,334 +1,334 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.email.provider; import com.android.emailcommon.Logging; import com.android.emailcommon.internet.MimeUtility; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.Attachment; import com.android.emailcommon.provider.EmailContent.AttachmentColumns; import com.android.emailcommon.utility.AttachmentUtilities; import com.android.emailcommon.utility.AttachmentUtilities.Columns; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Binder; import android.os.ParcelFileDescriptor; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; /* * A simple ContentProvider that allows file access to Email's attachments. * * The URI scheme is as follows. For raw file access: * content://com.android.email.attachmentprovider/acct#/attach#/RAW * * And for access to thumbnails: * content://com.android.email.attachmentprovider/acct#/attach#/THUMBNAIL/width#/height# * * The on-disk (storage) schema is as follows. * * Attachments are stored at: <database-path>/account#.db_att/item# * Thumbnails are stored at: <cache-path>/thmb_account#_item# * * Using the standard application context, account #10 and attachment # 20, this would be: * /data/data/com.android.email/databases/10.db_att/20 * /data/data/com.android.email/cache/thmb_10_20 */ public class AttachmentProvider extends ContentProvider { private static final String[] MIME_TYPE_PROJECTION = new String[] { AttachmentColumns.MIME_TYPE, AttachmentColumns.FILENAME }; private static final int MIME_TYPE_COLUMN_MIME_TYPE = 0; private static final int MIME_TYPE_COLUMN_FILENAME = 1; private static final String[] PROJECTION_QUERY = new String[] { AttachmentColumns.FILENAME, AttachmentColumns.SIZE, AttachmentColumns.CONTENT_URI }; @Override public boolean onCreate() { /* * We use the cache dir as a temporary directory (since Android doesn't give us one) so * on startup we'll clean up any .tmp files from the last run. */ File[] files = getContext().getCacheDir().listFiles(); for (File file : files) { String filename = file.getName(); if (filename.endsWith(".tmp") || filename.startsWith("thmb_")) { file.delete(); } } return true; } /** * Returns the mime type for a given attachment. There are three possible results: * - If thumbnail Uri, always returns "image/png" (even if there's no attachment) * - If the attachment does not exist, returns null * - Returns the mime type of the attachment */ @Override public String getType(Uri uri) { long callingId = Binder.clearCallingIdentity(); try { List<String> segments = uri.getPathSegments(); String id = segments.get(1); String format = segments.get(2); if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) { return "image/png"; } else { uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id)); Cursor c = getContext().getContentResolver().query(uri, MIME_TYPE_PROJECTION, null, null, null); try { if (c.moveToFirst()) { String mimeType = c.getString(MIME_TYPE_COLUMN_MIME_TYPE); String fileName = c.getString(MIME_TYPE_COLUMN_FILENAME); mimeType = AttachmentUtilities.inferMimeType(fileName, mimeType); return mimeType; } } finally { c.close(); } return null; } } finally { Binder.restoreCallingIdentity(callingId); } } /** * Open an attachment file. There are two "formats" - "raw", which returns an actual file, * and "thumbnail", which attempts to generate a thumbnail image. * * Thumbnails are cached for easy space recovery and cleanup. * * TODO: The thumbnail format returns null for its failure cases, instead of throwing * FileNotFoundException, and should be fixed for consistency. * * @throws FileNotFoundException */ @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { // If this is a write, the caller must have the EmailProvider permission, which is // based on signature only if (mode.equals("w")) { Context context = getContext(); - if (context.checkCallingPermission(EmailContent.PROVIDER_PERMISSION) + if (context.checkCallingOrSelfPermission(EmailContent.PROVIDER_PERMISSION) != PackageManager.PERMISSION_GRANTED) { throw new FileNotFoundException(); } List<String> segments = uri.getPathSegments(); String accountId = segments.get(0); String id = segments.get(1); File saveIn = AttachmentUtilities.getAttachmentDirectory(context, Long.parseLong(accountId)); if (!saveIn.exists()) { saveIn.mkdirs(); } File newFile = new File(saveIn, id); return ParcelFileDescriptor.open( newFile, ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE); } long callingId = Binder.clearCallingIdentity(); try { List<String> segments = uri.getPathSegments(); String accountId = segments.get(0); String id = segments.get(1); String format = segments.get(2); if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) { int width = Integer.parseInt(segments.get(3)); int height = Integer.parseInt(segments.get(4)); String filename = "thmb_" + accountId + "_" + id; File dir = getContext().getCacheDir(); File file = new File(dir, filename); if (!file.exists()) { Uri attachmentUri = AttachmentUtilities. getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id)); Cursor c = query(attachmentUri, new String[] { Columns.DATA }, null, null, null); if (c != null) { try { if (c.moveToFirst()) { attachmentUri = Uri.parse(c.getString(0)); } else { return null; } } finally { c.close(); } } String type = getContext().getContentResolver().getType(attachmentUri); try { InputStream in = getContext().getContentResolver().openInputStream(attachmentUri); Bitmap thumbnail = createThumbnail(type, in); if (thumbnail == null) { return null; } thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true); FileOutputStream out = new FileOutputStream(file); thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); out.close(); in.close(); } catch (IOException ioe) { Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " + ioe.getMessage()); return null; } catch (OutOfMemoryError oome) { Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " + oome.getMessage()); return null; } } return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } else { return ParcelFileDescriptor.open( new File(getContext().getDatabasePath(accountId + ".db_att"), id), ParcelFileDescriptor.MODE_READ_ONLY); } } finally { Binder.restoreCallingIdentity(callingId); } } @Override public int delete(Uri uri, String arg1, String[] arg2) { return 0; } @Override public Uri insert(Uri uri, ContentValues values) { return null; } /** * Returns a cursor based on the data in the attachments table, or null if the attachment * is not recorded in the table. * * Supports REST Uri only, for a single row - selection, selection args, and sortOrder are * ignored (non-null values should probably throw an exception....) */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { long callingId = Binder.clearCallingIdentity(); try { if (projection == null) { projection = new String[] { Columns._ID, Columns.DATA, }; } List<String> segments = uri.getPathSegments(); String accountId = segments.get(0); String id = segments.get(1); String format = segments.get(2); String name = null; int size = -1; String contentUri = null; uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id)); Cursor c = getContext().getContentResolver().query(uri, PROJECTION_QUERY, null, null, null); try { if (c.moveToFirst()) { name = c.getString(0); size = c.getInt(1); contentUri = c.getString(2); } else { return null; } } finally { c.close(); } MatrixCursor ret = new MatrixCursor(projection); Object[] values = new Object[projection.length]; for (int i = 0, count = projection.length; i < count; i++) { String column = projection[i]; if (Columns._ID.equals(column)) { values[i] = id; } else if (Columns.DATA.equals(column)) { values[i] = contentUri; } else if (Columns.DISPLAY_NAME.equals(column)) { values[i] = name; } else if (Columns.SIZE.equals(column)) { values[i] = size; } } ret.addRow(values); return ret; } finally { Binder.restoreCallingIdentity(callingId); } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } private Bitmap createThumbnail(String type, InputStream data) { if(MimeUtility.mimeTypeMatches(type, "image/*")) { return createImageThumbnail(data); } return null; } private Bitmap createImageThumbnail(InputStream data) { try { Bitmap bitmap = BitmapFactory.decodeStream(data); return bitmap; } catch (OutOfMemoryError oome) { Log.d(Logging.LOG_TAG, "createImageThumbnail failed with " + oome.getMessage()); return null; } catch (Exception e) { Log.d(Logging.LOG_TAG, "createImageThumbnail failed with " + e.getMessage()); return null; } } /** * Need this to suppress warning in unit tests. */ @Override public void shutdown() { // Don't call super.shutdown(), which emits a warning... } }
true
true
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { // If this is a write, the caller must have the EmailProvider permission, which is // based on signature only if (mode.equals("w")) { Context context = getContext(); if (context.checkCallingPermission(EmailContent.PROVIDER_PERMISSION) != PackageManager.PERMISSION_GRANTED) { throw new FileNotFoundException(); } List<String> segments = uri.getPathSegments(); String accountId = segments.get(0); String id = segments.get(1); File saveIn = AttachmentUtilities.getAttachmentDirectory(context, Long.parseLong(accountId)); if (!saveIn.exists()) { saveIn.mkdirs(); } File newFile = new File(saveIn, id); return ParcelFileDescriptor.open( newFile, ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE); } long callingId = Binder.clearCallingIdentity(); try { List<String> segments = uri.getPathSegments(); String accountId = segments.get(0); String id = segments.get(1); String format = segments.get(2); if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) { int width = Integer.parseInt(segments.get(3)); int height = Integer.parseInt(segments.get(4)); String filename = "thmb_" + accountId + "_" + id; File dir = getContext().getCacheDir(); File file = new File(dir, filename); if (!file.exists()) { Uri attachmentUri = AttachmentUtilities. getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id)); Cursor c = query(attachmentUri, new String[] { Columns.DATA }, null, null, null); if (c != null) { try { if (c.moveToFirst()) { attachmentUri = Uri.parse(c.getString(0)); } else { return null; } } finally { c.close(); } } String type = getContext().getContentResolver().getType(attachmentUri); try { InputStream in = getContext().getContentResolver().openInputStream(attachmentUri); Bitmap thumbnail = createThumbnail(type, in); if (thumbnail == null) { return null; } thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true); FileOutputStream out = new FileOutputStream(file); thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); out.close(); in.close(); } catch (IOException ioe) { Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " + ioe.getMessage()); return null; } catch (OutOfMemoryError oome) { Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " + oome.getMessage()); return null; } } return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } else { return ParcelFileDescriptor.open( new File(getContext().getDatabasePath(accountId + ".db_att"), id), ParcelFileDescriptor.MODE_READ_ONLY); } } finally { Binder.restoreCallingIdentity(callingId); } }
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { // If this is a write, the caller must have the EmailProvider permission, which is // based on signature only if (mode.equals("w")) { Context context = getContext(); if (context.checkCallingOrSelfPermission(EmailContent.PROVIDER_PERMISSION) != PackageManager.PERMISSION_GRANTED) { throw new FileNotFoundException(); } List<String> segments = uri.getPathSegments(); String accountId = segments.get(0); String id = segments.get(1); File saveIn = AttachmentUtilities.getAttachmentDirectory(context, Long.parseLong(accountId)); if (!saveIn.exists()) { saveIn.mkdirs(); } File newFile = new File(saveIn, id); return ParcelFileDescriptor.open( newFile, ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE); } long callingId = Binder.clearCallingIdentity(); try { List<String> segments = uri.getPathSegments(); String accountId = segments.get(0); String id = segments.get(1); String format = segments.get(2); if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) { int width = Integer.parseInt(segments.get(3)); int height = Integer.parseInt(segments.get(4)); String filename = "thmb_" + accountId + "_" + id; File dir = getContext().getCacheDir(); File file = new File(dir, filename); if (!file.exists()) { Uri attachmentUri = AttachmentUtilities. getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id)); Cursor c = query(attachmentUri, new String[] { Columns.DATA }, null, null, null); if (c != null) { try { if (c.moveToFirst()) { attachmentUri = Uri.parse(c.getString(0)); } else { return null; } } finally { c.close(); } } String type = getContext().getContentResolver().getType(attachmentUri); try { InputStream in = getContext().getContentResolver().openInputStream(attachmentUri); Bitmap thumbnail = createThumbnail(type, in); if (thumbnail == null) { return null; } thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true); FileOutputStream out = new FileOutputStream(file); thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); out.close(); in.close(); } catch (IOException ioe) { Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " + ioe.getMessage()); return null; } catch (OutOfMemoryError oome) { Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " + oome.getMessage()); return null; } } return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } else { return ParcelFileDescriptor.open( new File(getContext().getDatabasePath(accountId + ".db_att"), id), ParcelFileDescriptor.MODE_READ_ONLY); } } finally { Binder.restoreCallingIdentity(callingId); } }
diff --git a/tds/src/main/java/thredds/server/wcs/v1_0_0_1/WcsRequestParser.java b/tds/src/main/java/thredds/server/wcs/v1_0_0_1/WcsRequestParser.java index c5595ca31..2368dcdcb 100644 --- a/tds/src/main/java/thredds/server/wcs/v1_0_0_1/WcsRequestParser.java +++ b/tds/src/main/java/thredds/server/wcs/v1_0_0_1/WcsRequestParser.java @@ -1,373 +1,374 @@ /* * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package thredds.server.wcs.v1_0_0_1; import thredds.wcs.v1_0_0_1.*; import thredds.wcs.Request; import thredds.servlet.ServletUtil; import thredds.servlet.DatasetHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ucar.nc2.dt.GridDataset; import ucar.nc2.units.DateRange; import ucar.nc2.units.DateType; import java.util.List; import java.util.ArrayList; import java.io.IOException; import java.net.URI; import java.text.ParseException; /** * Parse an incoming WCS 1.0.0+ request. * * @author edavis * @since 4.0 */ public class WcsRequestParser { private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger( WcsRequestParser.class ); public static WcsRequest parseRequest( String version, URI serverURI, HttpServletRequest req, HttpServletResponse res ) throws WcsException, IOException { GridDataset gridDataset = null; try { // These are handled in WcsServlet. Don't need to validate here. // String serviceParam = ServletUtil.getParameterIgnoreCase( req, "Service" ); // String versionParam = ServletUtil.getParameterIgnoreCase( req, "Version" ); // String acceptVersionsParam = ServletUtil.getParameterIgnoreCase( req, "AcceptVersions" ); // General request info Request.Operation operation; String datasetPath = req.getPathInfo(); boolean isRemote = false; if ( datasetPath == null ) { datasetPath = ServletUtil.getParameterIgnoreCase( req, "dataset" ); isRemote = ( datasetPath != null ); } if ( datasetPath == null ) { log.debug( "parseRequest(): Request did not specify dataset." ); throw new WcsException( WcsException.Code.CoverageNotDefined, "", "Request did not specify dataset. See \"" + req.getContextPath() + "/catalog.xml\" for available datasets." ); } gridDataset = openDataset( req, res, datasetPath, isRemote ); if ( gridDataset == null ) { log.debug( "parseRequest(): Failed to open dataset (???)."); throw new WcsException( WcsException.Code.CoverageNotDefined, "", "Failed to open dataset."); } WcsDataset wcsDataset = new WcsDataset( gridDataset, datasetPath); // Determine the request operation. String requestParam = ServletUtil.getParameterIgnoreCase( req, "Request" ); try { operation = Request.Operation.valueOf( requestParam ); } catch ( IllegalArgumentException e ) { log.debug( "parseRequest(): Unsupported operation request [" + requestParam + "]."); throw new WcsException( WcsException.Code.InvalidParameterValue, "Request", "Unsupported operation request [" + requestParam + "]." ); } // Handle "GetCapabilities" request. if ( operation.equals( Request.Operation.GetCapabilities ) ) { String sectionParam = ServletUtil.getParameterIgnoreCase( req, "Section" ); String updateSequenceParam = ServletUtil.getParameterIgnoreCase( req, "UpdateSequence" ); if ( sectionParam == null) sectionParam = ""; GetCapabilities.Section section = null; try { section = GetCapabilities.Section.getSection( sectionParam); } catch ( IllegalArgumentException e ) { log.debug( "parseRequest(): Unsupported GetCapabilities section requested [" + sectionParam + "]." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "Section", "Unsupported GetCapabilities section requested [" + sectionParam + "]." ); } return new GetCapabilities( operation, version, wcsDataset, serverURI, section, updateSequenceParam, null); } // Handle "DescribeCoverage" request. else if ( operation.equals( Request.Operation.DescribeCoverage ) ) { String coverageIdListParam = ServletUtil.getParameterIgnoreCase( req, "Coverage" ); if ( coverageIdListParam == null ) { log.debug( "parseRequest(): GetCapabilities request requires \"Coverage\" parameter." ); throw new WcsException( WcsException.Code.MissingParameterValue, "Coverage", "GetCapabilities request requires \"Coverage\" parameter." ); } return new DescribeCoverage( operation, version, wcsDataset, splitCommaSeperatedList( coverageIdListParam )); } // Handle "GetCoverage" request. else if ( operation.equals( Request.Operation.GetCoverage ) ) { String coverageId = ServletUtil.getParameterIgnoreCase( req, "Coverage" ); String crs = ServletUtil.getParameterIgnoreCase( req, "CRS" ); String responseCRS = ServletUtil.getParameterIgnoreCase( req, "RESPONSE_CRS" ); String bbox = ServletUtil.getParameterIgnoreCase( req, "BBOX" ); String time = ServletUtil.getParameterIgnoreCase( req, "TIME" ); // ToDo The name of this parameter is dependent on the coverage (see WcsCoverage.getRangeSetAxisName()). String parameter = ServletUtil.getParameterIgnoreCase( req, "Vertical" ); String formatString = ServletUtil.getParameterIgnoreCase( req, "FORMAT" ); // Assign and validate PARAMETER ("Vertical") parameter. WcsCoverage.VerticalRange verticalRange = parseRangeSetAxisValues( parameter ); Request.Format format = parseFormat( formatString ); return new GetCoverage( operation, version, wcsDataset, coverageId, crs, responseCRS, parseBoundingBox( bbox), parseTime( time ), verticalRange, format); } else { log.debug( "parseRequest(): Invalid request operation [" + requestParam + "]."); } - throw new WcsException( WcsException.Code.InvalidParameterValue, "Request", "Invalid requested operation [" + requestParam + "]." ); - } + throw new WcsException( WcsException.Code.InvalidParameterValue, "Request", "Invalid requested operation [" + requestParam + "]." ); + } catch ( WcsException e ) { - gridDataset.close(); + if ( gridDataset != null ) + gridDataset.close(); throw e; } } private static Request.BoundingBox parseBoundingBox( String bboxString ) throws WcsException { if ( bboxString == null || bboxString.equals( "" ) ) return null; String[] bboxSplit = bboxString.split( "," ); if ( bboxSplit.length != 4 ) { log.debug( "parseBoundingBox(): BBOX [" + bboxString + "] not limited to X and Y." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "BBOX", "BBOX [" + bboxString + "] has more values [" + bboxSplit.length + "] than expected [4]." ); } double minx = Double.parseDouble( bboxSplit[0] ); double miny = Double.parseDouble( bboxSplit[1] ); double maxx = Double.parseDouble( bboxSplit[2] ); double maxy = Double.parseDouble( bboxSplit[3] ); double[] minP = new double[2]; minP[0] = Double.parseDouble( bboxSplit[0] ); minP[1] = Double.parseDouble( bboxSplit[1] ); double[] maxP = new double[2]; maxP[0] = Double.parseDouble( bboxSplit[2] ); maxP[1] = Double.parseDouble( bboxSplit[3] ); if ( minP[0] > maxP[0] || minP[1] > maxP[1]) throw new WcsException( WcsException.Code.InvalidParameterValue, "BBOX", "BBOX [" + bboxString + "] minimum point larger than maximum point."); return new Request.BoundingBox( minP, maxP); } private static DateRange parseTime( String time ) throws WcsException { if ( time == null || time.equals( "" ) ) return null; DateRange dateRange; try { if ( time.indexOf( "," ) != -1 ) { log.debug( "parseTime(): Unsupported time parameter (list) [" + time + "]." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "TIME", "Not currently supporting time list." ); //String[] timeList = time.split( "," ); //dateRange = new DateRange( date, date, null, null ); } else if ( time.indexOf( "/" ) != -1 ) { String[] timeRange = time.split( "/" ); if ( timeRange.length != 2 ) { log.debug( "parseTime(): Unsupported time parameter (time range with resolution) [" + time + "]." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "TIME", "Not currently supporting time range with resolution." ); } dateRange = new DateRange( new DateType( timeRange[0], null, null ), new DateType( timeRange[1], null, null ), null, null ); } else { DateType date = new DateType( time, null, null ); dateRange = new DateRange( date, date, null, null ); } } catch ( ParseException e ) { log.debug( "parseTime(): Failed to parse time parameter [" + time + "]: " + e.getMessage() ); throw new WcsException( WcsException.Code.InvalidParameterValue, "TIME", "Invalid time format [" + time + "]." ); } return dateRange; } private static WcsCoverage.VerticalRange parseRangeSetAxisValues( String rangeSetAxisSelectionString ) throws WcsException { if ( rangeSetAxisSelectionString == null || rangeSetAxisSelectionString.equals( "" ) ) return null; WcsCoverage.VerticalRange range; if ( rangeSetAxisSelectionString.indexOf( "," ) != -1 ) { log.debug( "parseRangeSetAxisValues(): Vertical value list not supported [" + rangeSetAxisSelectionString + "]." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "Vertical", "Not currently supporting list of Vertical values (just range, i.e., \"min/max\")." ); } else if ( rangeSetAxisSelectionString.indexOf( "/" ) != -1 ) { String[] rangeSplit = rangeSetAxisSelectionString.split( "/" ); if ( rangeSplit.length != 2 ) { log.debug( "parseRangeSetAxisValues(): Unsupported Vertical value (range with resolution) [" + rangeSetAxisSelectionString + "]." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "Vertical", "Not currently supporting vertical range with resolution." ); } double minValue = 0; double maxValue = 0; try { minValue = Double.parseDouble( rangeSplit[0] ); maxValue = Double.parseDouble( rangeSplit[1] ); } catch ( NumberFormatException e ) { log.debug( "parseRangeSetAxisValues(): Failed to parse Vertical range min or max [" + rangeSetAxisSelectionString + "]: " + e.getMessage() ); throw new WcsException( WcsException.Code.InvalidParameterValue, "Vertical", "Failed to parse Vertical range min or max." ); } if ( minValue > maxValue ) { log.debug( "parseRangeSetAxisValues(): Vertical range must be \"min/max\" [" + rangeSetAxisSelectionString + "]." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "Vertical", "Vertical range must be \"min/max\"." ); } range = new WcsCoverage.VerticalRange( minValue, maxValue, 1 ); } else { double value = 0; try { value = Double.parseDouble( rangeSetAxisSelectionString ); } catch ( NumberFormatException e ) { log.debug( "parseRangeSetAxisValues(): Failed to parse Vertical value [" + rangeSetAxisSelectionString + "]: " + e.getMessage() ); throw new WcsException( WcsException.Code.InvalidParameterValue, "Vertical", "Failed to parse Vertical value." ); } range = new WcsCoverage.VerticalRange( value, 1 ); } if ( range == null ) { log.debug( "parseRangeSetAxisValues(): Invalid Vertical range requested [" + rangeSetAxisSelectionString + "]." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "Vertical", "Invalid Vertical range requested." ); } return range; } private static Request.Format parseFormat( String formatString ) throws WcsException { // Assign and validate FORMAT parameter. if ( formatString == null ) { log.debug( "parseFormat(): FORMAT parameter required." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "FORMAT", "FORMAT parameter required." ); } Request.Format format; try { format = Request.Format.valueOf( formatString.trim() ); } catch ( IllegalArgumentException e ) { String msg = "Unknown format value [" + formatString + "]."; log.debug( "parseFormat(): " + msg ); throw new WcsException( WcsException.Code.InvalidParameterValue, "FORMAT", msg ); } return format; } private static List<String> splitCommaSeperatedList( String identifiers ) { List<String> idList = new ArrayList<String>(); String[] idArray = identifiers.split( ","); for ( int i = 0; i < idArray.length; i++ ) { idList.add( idArray[i].trim()); } return idList; } private static GridDataset openDataset( HttpServletRequest req, HttpServletResponse res, String datasetPath, boolean isRemote ) throws WcsException { GridDataset dataset; try { dataset = isRemote ? ucar.nc2.dt.grid.GridDataset.open( datasetPath ) : DatasetHandler.openGridDataset( req, res, datasetPath ); } catch ( IOException e ) { log.debug( "openDataset(): Failed to open dataset [" + datasetPath + "]: " + e.getMessage() ); throw new WcsException( "Failed to open dataset, [" + datasetPath + "]." ); } if ( dataset == null ) { log.debug( "openDataset(): Unknown dataset [" + datasetPath + "]." ); throw new WcsException( "Unknown dataset, [" + datasetPath + "]." ); } return dataset; } }
false
true
public static WcsRequest parseRequest( String version, URI serverURI, HttpServletRequest req, HttpServletResponse res ) throws WcsException, IOException { GridDataset gridDataset = null; try { // These are handled in WcsServlet. Don't need to validate here. // String serviceParam = ServletUtil.getParameterIgnoreCase( req, "Service" ); // String versionParam = ServletUtil.getParameterIgnoreCase( req, "Version" ); // String acceptVersionsParam = ServletUtil.getParameterIgnoreCase( req, "AcceptVersions" ); // General request info Request.Operation operation; String datasetPath = req.getPathInfo(); boolean isRemote = false; if ( datasetPath == null ) { datasetPath = ServletUtil.getParameterIgnoreCase( req, "dataset" ); isRemote = ( datasetPath != null ); } if ( datasetPath == null ) { log.debug( "parseRequest(): Request did not specify dataset." ); throw new WcsException( WcsException.Code.CoverageNotDefined, "", "Request did not specify dataset. See \"" + req.getContextPath() + "/catalog.xml\" for available datasets." ); } gridDataset = openDataset( req, res, datasetPath, isRemote ); if ( gridDataset == null ) { log.debug( "parseRequest(): Failed to open dataset (???)."); throw new WcsException( WcsException.Code.CoverageNotDefined, "", "Failed to open dataset."); } WcsDataset wcsDataset = new WcsDataset( gridDataset, datasetPath); // Determine the request operation. String requestParam = ServletUtil.getParameterIgnoreCase( req, "Request" ); try { operation = Request.Operation.valueOf( requestParam ); } catch ( IllegalArgumentException e ) { log.debug( "parseRequest(): Unsupported operation request [" + requestParam + "]."); throw new WcsException( WcsException.Code.InvalidParameterValue, "Request", "Unsupported operation request [" + requestParam + "]." ); } // Handle "GetCapabilities" request. if ( operation.equals( Request.Operation.GetCapabilities ) ) { String sectionParam = ServletUtil.getParameterIgnoreCase( req, "Section" ); String updateSequenceParam = ServletUtil.getParameterIgnoreCase( req, "UpdateSequence" ); if ( sectionParam == null) sectionParam = ""; GetCapabilities.Section section = null; try { section = GetCapabilities.Section.getSection( sectionParam); } catch ( IllegalArgumentException e ) { log.debug( "parseRequest(): Unsupported GetCapabilities section requested [" + sectionParam + "]." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "Section", "Unsupported GetCapabilities section requested [" + sectionParam + "]." ); } return new GetCapabilities( operation, version, wcsDataset, serverURI, section, updateSequenceParam, null); } // Handle "DescribeCoverage" request. else if ( operation.equals( Request.Operation.DescribeCoverage ) ) { String coverageIdListParam = ServletUtil.getParameterIgnoreCase( req, "Coverage" ); if ( coverageIdListParam == null ) { log.debug( "parseRequest(): GetCapabilities request requires \"Coverage\" parameter." ); throw new WcsException( WcsException.Code.MissingParameterValue, "Coverage", "GetCapabilities request requires \"Coverage\" parameter." ); } return new DescribeCoverage( operation, version, wcsDataset, splitCommaSeperatedList( coverageIdListParam )); } // Handle "GetCoverage" request. else if ( operation.equals( Request.Operation.GetCoverage ) ) { String coverageId = ServletUtil.getParameterIgnoreCase( req, "Coverage" ); String crs = ServletUtil.getParameterIgnoreCase( req, "CRS" ); String responseCRS = ServletUtil.getParameterIgnoreCase( req, "RESPONSE_CRS" ); String bbox = ServletUtil.getParameterIgnoreCase( req, "BBOX" ); String time = ServletUtil.getParameterIgnoreCase( req, "TIME" ); // ToDo The name of this parameter is dependent on the coverage (see WcsCoverage.getRangeSetAxisName()). String parameter = ServletUtil.getParameterIgnoreCase( req, "Vertical" ); String formatString = ServletUtil.getParameterIgnoreCase( req, "FORMAT" ); // Assign and validate PARAMETER ("Vertical") parameter. WcsCoverage.VerticalRange verticalRange = parseRangeSetAxisValues( parameter ); Request.Format format = parseFormat( formatString ); return new GetCoverage( operation, version, wcsDataset, coverageId, crs, responseCRS, parseBoundingBox( bbox), parseTime( time ), verticalRange, format); } else { log.debug( "parseRequest(): Invalid request operation [" + requestParam + "]."); } throw new WcsException( WcsException.Code.InvalidParameterValue, "Request", "Invalid requested operation [" + requestParam + "]." ); } catch ( WcsException e ) { gridDataset.close(); throw e; } }
public static WcsRequest parseRequest( String version, URI serverURI, HttpServletRequest req, HttpServletResponse res ) throws WcsException, IOException { GridDataset gridDataset = null; try { // These are handled in WcsServlet. Don't need to validate here. // String serviceParam = ServletUtil.getParameterIgnoreCase( req, "Service" ); // String versionParam = ServletUtil.getParameterIgnoreCase( req, "Version" ); // String acceptVersionsParam = ServletUtil.getParameterIgnoreCase( req, "AcceptVersions" ); // General request info Request.Operation operation; String datasetPath = req.getPathInfo(); boolean isRemote = false; if ( datasetPath == null ) { datasetPath = ServletUtil.getParameterIgnoreCase( req, "dataset" ); isRemote = ( datasetPath != null ); } if ( datasetPath == null ) { log.debug( "parseRequest(): Request did not specify dataset." ); throw new WcsException( WcsException.Code.CoverageNotDefined, "", "Request did not specify dataset. See \"" + req.getContextPath() + "/catalog.xml\" for available datasets." ); } gridDataset = openDataset( req, res, datasetPath, isRemote ); if ( gridDataset == null ) { log.debug( "parseRequest(): Failed to open dataset (???)."); throw new WcsException( WcsException.Code.CoverageNotDefined, "", "Failed to open dataset."); } WcsDataset wcsDataset = new WcsDataset( gridDataset, datasetPath); // Determine the request operation. String requestParam = ServletUtil.getParameterIgnoreCase( req, "Request" ); try { operation = Request.Operation.valueOf( requestParam ); } catch ( IllegalArgumentException e ) { log.debug( "parseRequest(): Unsupported operation request [" + requestParam + "]."); throw new WcsException( WcsException.Code.InvalidParameterValue, "Request", "Unsupported operation request [" + requestParam + "]." ); } // Handle "GetCapabilities" request. if ( operation.equals( Request.Operation.GetCapabilities ) ) { String sectionParam = ServletUtil.getParameterIgnoreCase( req, "Section" ); String updateSequenceParam = ServletUtil.getParameterIgnoreCase( req, "UpdateSequence" ); if ( sectionParam == null) sectionParam = ""; GetCapabilities.Section section = null; try { section = GetCapabilities.Section.getSection( sectionParam); } catch ( IllegalArgumentException e ) { log.debug( "parseRequest(): Unsupported GetCapabilities section requested [" + sectionParam + "]." ); throw new WcsException( WcsException.Code.InvalidParameterValue, "Section", "Unsupported GetCapabilities section requested [" + sectionParam + "]." ); } return new GetCapabilities( operation, version, wcsDataset, serverURI, section, updateSequenceParam, null); } // Handle "DescribeCoverage" request. else if ( operation.equals( Request.Operation.DescribeCoverage ) ) { String coverageIdListParam = ServletUtil.getParameterIgnoreCase( req, "Coverage" ); if ( coverageIdListParam == null ) { log.debug( "parseRequest(): GetCapabilities request requires \"Coverage\" parameter." ); throw new WcsException( WcsException.Code.MissingParameterValue, "Coverage", "GetCapabilities request requires \"Coverage\" parameter." ); } return new DescribeCoverage( operation, version, wcsDataset, splitCommaSeperatedList( coverageIdListParam )); } // Handle "GetCoverage" request. else if ( operation.equals( Request.Operation.GetCoverage ) ) { String coverageId = ServletUtil.getParameterIgnoreCase( req, "Coverage" ); String crs = ServletUtil.getParameterIgnoreCase( req, "CRS" ); String responseCRS = ServletUtil.getParameterIgnoreCase( req, "RESPONSE_CRS" ); String bbox = ServletUtil.getParameterIgnoreCase( req, "BBOX" ); String time = ServletUtil.getParameterIgnoreCase( req, "TIME" ); // ToDo The name of this parameter is dependent on the coverage (see WcsCoverage.getRangeSetAxisName()). String parameter = ServletUtil.getParameterIgnoreCase( req, "Vertical" ); String formatString = ServletUtil.getParameterIgnoreCase( req, "FORMAT" ); // Assign and validate PARAMETER ("Vertical") parameter. WcsCoverage.VerticalRange verticalRange = parseRangeSetAxisValues( parameter ); Request.Format format = parseFormat( formatString ); return new GetCoverage( operation, version, wcsDataset, coverageId, crs, responseCRS, parseBoundingBox( bbox), parseTime( time ), verticalRange, format); } else { log.debug( "parseRequest(): Invalid request operation [" + requestParam + "]."); } throw new WcsException( WcsException.Code.InvalidParameterValue, "Request", "Invalid requested operation [" + requestParam + "]." ); } catch ( WcsException e ) { if ( gridDataset != null ) gridDataset.close(); throw e; } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/provisional/tasklist/AbstractRepositoryConnector.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/provisional/tasklist/AbstractRepositoryConnector.java index b78c4c665..70dfc34c9 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/provisional/tasklist/AbstractRepositoryConnector.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/provisional/tasklist/AbstractRepositoryConnector.java @@ -1,597 +1,597 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 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 *******************************************************************************/ package org.eclipse.mylar.provisional.tasklist; import java.io.File; import java.io.IOException; import java.net.Proxy; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.IJobChangeListener; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.wizard.IWizard; import org.eclipse.mylar.internal.core.util.MylarStatusHandler; import org.eclipse.mylar.internal.core.util.ZipFileUtil; import org.eclipse.mylar.internal.tasklist.RepositoryAttachment; import org.eclipse.mylar.internal.tasklist.RepositoryTaskAttribute; import org.eclipse.mylar.internal.tasklist.RepositoryTaskData; import org.eclipse.mylar.internal.tasklist.ui.wizards.AbstractRepositorySettingsPage; import org.eclipse.mylar.provisional.core.MylarPlugin; import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryTask.RepositoryTaskSyncState; import org.eclipse.ui.PlatformUI; /** * Encapsulates synchronization policy. * * @author Mik Kersten * @author Rob Elves */ public abstract class AbstractRepositoryConnector { private static final String MESSAGE_ATTACHMENTS_NOT_SUPPORTED = "Attachments not supported by connector: "; private static final int RETRY_DELAY = 3000; private static final int MAX_QUERY_ATTEMPTS = 3; public static final String MYLAR_CONTEXT_DESCRIPTION = "mylar/context/zip"; private static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; private static final String ZIPFILE_EXTENSION = ".zip"; protected List<String> supportedVersions; protected boolean forceSyncExecForTesting = false; private boolean updateLocalCopy = false; private final MutexRule rule = new MutexRule(); /** * @return null if not supported */ public abstract IAttachmentHandler getAttachmentHandler(); /** * @return null if not supported */ public abstract IOfflineTaskHandler getOfflineTaskHandler(); public abstract String getRepositoryUrlFromTaskUrl(String url); public abstract boolean canCreateTaskFromKey(); public abstract boolean canCreateNewTask(); public String[] repositoryPropertyNames() { return new String[] { TaskRepositoryManager.PROPERTY_VERSION, TaskRepositoryManager.PROPERTY_TIMEZONE, TaskRepositoryManager.PROPERTY_ENCODING }; } /** * Implementors must execute query synchronously. * * @param query * @param monitor * @param queryStatus * set an exception on queryStatus.getChildren[0] to indicate * failure */ public abstract List<AbstractQueryHit> performQuery(AbstractRepositoryQuery query, IProgressMonitor monitor, MultiStatus queryStatus); public abstract String getLabel(); /** * @return the unique type of the repository, e.g. "bugzilla" */ public abstract String getRepositoryType(); /** * @param id * identifier, e.g. "123" bug Bugzilla bug 123 * @return null if task could not be created */ public abstract ITask createTaskFromExistingKey(TaskRepository repository, String id); public abstract AbstractRepositorySettingsPage getSettingsPage(); public abstract IWizard getNewQueryWizard(TaskRepository repository); public abstract void openEditQueryDialog(AbstractRepositoryQuery query); public abstract IWizard getAddExistingTaskWizard(TaskRepository repository); public abstract IWizard getNewTaskWizard(TaskRepository taskRepository); public abstract List<String> getSupportedVersions(); protected abstract void updateTaskState(AbstractRepositoryTask repositoryTask); /** * returns all tasks if date is null or an error occurs */ public abstract Set<AbstractRepositoryTask> getChangedSinceLastSync(TaskRepository repository, Set<AbstractRepositoryTask> tasks) throws Exception; /** * Implementors of this repositoryOperations must perform it locally without * going to the server since it is used for frequent repositoryOperations * such as decoration. * * @return an emtpy set if no contexts */ public final Set<RepositoryAttachment> getContextAttachments(TaskRepository repository, AbstractRepositoryTask task) { Set<RepositoryAttachment> contextAttachments = new HashSet<RepositoryAttachment>(); if (task.getTaskData() != null) { for (RepositoryAttachment attachment : task.getTaskData().getAttachments()) { if (attachment.getDescription().equals(MYLAR_CONTEXT_DESCRIPTION)) { contextAttachments.add(attachment); } } } return contextAttachments; } // TODO: move public final boolean hasRepositoryContext(TaskRepository repository, AbstractRepositoryTask task) { if (repository == null || task == null) { return false; } else { Set<RepositoryAttachment> remoteContextAttachments = getContextAttachments(repository, task); return (remoteContextAttachments != null && remoteContextAttachments.size() > 0); } } public final void attachContext(TaskRepository repository, AbstractRepositoryTask task, String longComment) throws CoreException { if (!repository.hasCredentials()) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), MylarTaskListPlugin.TITLE_DIALOG, "Repository credentials missing or invalid."); return; } else { MylarPlugin.getContextManager().saveContext(task.getHandleIdentifier()); File sourceContextFile = MylarPlugin.getContextManager().getFileForContext(task.getHandleIdentifier()); if (sourceContextFile != null && sourceContextFile.exists()) { try { List<File> filesToZip = new ArrayList<File>(); filesToZip.add(sourceContextFile); File destinationFile = File.createTempFile(sourceContextFile.getName(), ZIPFILE_EXTENSION); destinationFile.deleteOnExit(); ZipFileUtil.createZipFile(destinationFile, filesToZip, new NullProgressMonitor()); IAttachmentHandler handler = getAttachmentHandler(); if (handler != null) { // TODO: 'faking' outgoing state task.setSyncState(RepositoryTaskSyncState.OUTGOING); handler.uploadAttachment(repository, task, longComment, MYLAR_CONTEXT_DESCRIPTION, destinationFile, APPLICATION_OCTET_STREAM, false, null); task.setTaskData(null); synchronize(task, true, null); } else { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), MylarTaskListPlugin.TITLE_DIALOG, MESSAGE_ATTACHMENTS_NOT_SUPPORTED + getLabel()); } } catch (Exception e) { MylarStatusHandler.fail(e, "Could not export task context as zip file", true); } } } } public final void retrieveContext(TaskRepository repository, AbstractRepositoryTask task, RepositoryAttachment attachment) throws CoreException, IOException { boolean wasActive = false; if (task.isActive()) { wasActive = true; MylarTaskListPlugin.getTaskListManager().deactivateTask(task); } File destinationContextFile = MylarPlugin.getContextManager().getFileForContext(task.getHandleIdentifier()); File destinationZipFile = new File(destinationContextFile.getPath() + ZIPFILE_EXTENSION); Proxy proxySettings = MylarTaskListPlugin.getDefault().getProxySettings(); IAttachmentHandler attachmentHandler = getAttachmentHandler(); if (attachmentHandler != null) { attachmentHandler.downloadAttachment(repository, task, attachment.getId(), destinationZipFile, proxySettings); ZipFileUtil.unzipFiles(destinationZipFile, MylarPlugin.getDefault().getDataDirectory()); if (destinationContextFile.exists()) { MylarTaskListPlugin.getTaskListManager().getTaskList().notifyLocalInfoChanged(task); if (wasActive) { MylarTaskListPlugin.getTaskListManager().activateTask(task); } } } else { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), MylarTaskListPlugin.TITLE_DIALOG, MESSAGE_ATTACHMENTS_NOT_SUPPORTED + getLabel()); } } // Precondition of note: offline file is removed upon submit to repository // resulting in a synchronized state. /** * @return true if call results in change of syc state */ public synchronized boolean updateOfflineState(final AbstractRepositoryTask repositoryTask, final RepositoryTaskData newTaskData, boolean forceSync) { RepositoryTaskSyncState startState = repositoryTask.getSyncState(); RepositoryTaskSyncState status = repositoryTask.getSyncState(); if (newTaskData == null) { MylarStatusHandler.log("Download of " + repositoryTask.getDescription() + " from " + repositoryTask.getRepositoryUrl() + " failed.", this); return false; } RepositoryTaskData offlineTaskData = repositoryTask.getTaskData(); // loadOfflineTaskData(repositoryTask) if (newTaskData.hasLocalChanges()) { // Special case for saving changes to local task data status = RepositoryTaskSyncState.OUTGOING; } else { switch (status) { case OUTGOING: if (!forceSync) { // Never overwrite local task data unless forced return false; } case CONFLICT: // use a parameter rather than this null check if (offlineTaskData != null) { // TODO: pull this ui out of here if (!forceSyncExecForTesting) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { updateLocalCopy = MessageDialog .openQuestion( null, "Update Local Copy", "Local copy of Report " + repositoryTask.getDescription() + " on " + repositoryTask.getRepositoryUrl() + " has changes.\nWould you like to override local changes? \n\nNote: if you select No, only the new comment will be saved with the updated bug, all other changes will be lost."); } }); } else { updateLocalCopy = true; } if (!updateLocalCopy) { newTaskData.setNewComment(offlineTaskData.getNewComment()); newTaskData.setHasLocalChanges(true); status = RepositoryTaskSyncState.CONFLICT; } else { newTaskData.setHasLocalChanges(false); if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } } } else { newTaskData.setHasLocalChanges(false); status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case INCOMING: if (!forceSync && checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case SYNCHRONIZED: if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } break; } repositoryTask.setModifiedDateStamp(newTaskData.getLastModified()); } // if (offlineTaskData != null) { // removeOfflineTaskData(offlineTaskData); // } repositoryTask.setTaskData(newTaskData); repositoryTask.setSyncState(status); saveOffline(newTaskData); if(status == RepositoryTaskSyncState.INCOMING) { repositoryTask.setNotified(false); } - return startState == repositoryTask.getSyncState(); + return startState != repositoryTask.getSyncState(); // } catch (final CoreException e) { // if (forceSync) { // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { // public void run() { // ErrorDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), // "Error Downloading Report", "Unable to synchronize " + // repositoryTask.getDescription(), // e.getStatus()); // } // }); // } // // else { // // MylarStatusHandler.fail(e, "Unable to synchronize " + // // repositoryTask.getDescription() // // + " on " + repository.getUrl(), false); // // } // return; // } } /** public for testing purposes */ public boolean checkHasIncoming(AbstractRepositoryTask repositoryTask, RepositoryTaskData newData) { RepositoryTaskAttribute modifiedDateAttribute = newData.getAttribute(RepositoryTaskAttribute.DATE_MODIFIED); if (repositoryTask.getLastModifiedDateStamp() != null && modifiedDateAttribute != null && modifiedDateAttribute.getValue() != null) { Date newModifiedDate = getOfflineTaskHandler().getDateForAttributeType( RepositoryTaskAttribute.DATE_MODIFIED, modifiedDateAttribute.getValue()); Date oldModifiedDate = getOfflineTaskHandler().getDateForAttributeType( RepositoryTaskAttribute.DATE_MODIFIED, repositoryTask.getLastModifiedDateStamp()); if (oldModifiedDate != null && newModifiedDate != null) { if (newModifiedDate.compareTo(oldModifiedDate) <= 0) { // leave in SYNCHRONIZED state return false; } } } return true; // THE FOLLOWING CODE CAN BE USED AFTER MIGRATION TO 0.6.0 IS COMPLETE // RepositoryTaskAttribute modifiedDateAttribute = // newData.getAttribute(RepositoryTaskAttribute.DATE_MODIFIED); // if (repositoryTask.getLastModifiedDateStamp() != null && // modifiedDateAttribute != null && modifiedDateAttribute.getValue() != // null) { // if(repositoryTask.getLastModifiedDateStamp().trim().compareTo(modifiedDateAttribute.getValue().trim()) // == 0) { // return false; // } // } // return true; } /** * Sychronize a single task. Note that if you have a collection of tasks to * synchronize with this connector then you should call synchronize(Set<Set<AbstractRepositoryTask> * repositoryTasks, ...) * * @param listener * can be null */ public final Job synchronize(AbstractRepositoryTask repositoryTask, boolean forceSynch, IJobChangeListener listener) { Set<AbstractRepositoryTask> toSync = new HashSet<AbstractRepositoryTask>(); toSync.add(repositoryTask); return synchronize(toSync, forceSynch, listener); } /** * @param listener * can be null */ private Job synchronize(Set<AbstractRepositoryTask> repositoryTasks, boolean forceSynch, final IJobChangeListener listener) { final SynchronizeTaskJob synchronizeJob = new SynchronizeTaskJob(this, repositoryTasks); synchronizeJob.setForceSynch(forceSynch); synchronizeJob.setPriority(Job.DECORATE); synchronizeJob.setRule(rule); if (listener != null) { synchronizeJob.addJobChangeListener(listener); } if (!forceSyncExecForTesting) { synchronizeJob.schedule(); } else { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { synchronizeJob.run(new NullProgressMonitor()); if (listener != null) { listener.done(null); } } }); } return synchronizeJob; } /** * For synchronizing a single query. Use synchronize(Set, * IJobChangeListener) if synchronizing multiple queries at a time. */ public final Job synchronize(final AbstractRepositoryQuery repositoryQuery, IJobChangeListener listener) { HashSet<AbstractRepositoryQuery> items = new HashSet<AbstractRepositoryQuery>(); items.add(repositoryQuery); return synchronize(items, listener, Job.LONG, 0, true); } public final Job synchronize(final Set<AbstractRepositoryQuery> repositoryQueries, IJobChangeListener listener, int priority, long delay, boolean syncTasks) { SynchronizeQueryJob job = new SynchronizeQueryJob(this, repositoryQueries); job.setSynchTasks(syncTasks); if (listener != null) { job.addJobChangeListener(listener); } job.setPriority(priority); job.schedule(delay); return job; } /** * Synchronizes only those tasks that have changed since the last time the * given repository was synchronized. Calls to this method set * TaskRepository.syncTime to now if sync was successful for all tasks. */ public final void synchronizeChanged(final TaskRepository repository) { TaskList taskList = MylarTaskListPlugin.getTaskListManager().getTaskList(); Set<AbstractRepositoryTask> repositoryTasks = Collections.unmodifiableSet(taskList .getRepositoryTasks(repository.getUrl())); final Set<AbstractRepositoryTask> tasksToSync = new HashSet<AbstractRepositoryTask>(); Set<AbstractRepositoryTask> changedTasks = null; int attempts = 0; while (attempts < MAX_QUERY_ATTEMPTS && changedTasks == null) { attempts++; try { changedTasks = getChangedSinceLastSync(repository, repositoryTasks); } catch (UnknownHostException e) { // ignore, indicates working offline return; } catch (Exception e) { if (attempts == MAX_QUERY_ATTEMPTS) { Date now = new Date(); MylarStatusHandler.log(e, "Could not determine modified tasks for " + repository.getUrl() + ". [" + now.toString() + "]"); return; } try { Thread.sleep(RETRY_DELAY); } catch (InterruptedException e1) { return; } } } for (AbstractRepositoryTask task : changedTasks) { if (task.getSyncState() == RepositoryTaskSyncState.SYNCHRONIZED) { tasksToSync.add(task); // MylarStatusHandler.log("Changed: "+repository.getUrl()+" ** // "+task.getDescription(), this); } } if (tasksToSync.size() == 0) { return; } synchronize(tasksToSync, false, new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { Date mostRecent = new Date(0); String mostRecentTimeStamp = repository.getSyncTimeStamp(); for (AbstractRepositoryTask task : tasksToSync) { Date taskModifiedDate; if (getOfflineTaskHandler() != null && task.getTaskData() != null && task.getTaskData().getLastModified() != null) { taskModifiedDate = getOfflineTaskHandler().getDateForAttributeType( RepositoryTaskAttribute.DATE_MODIFIED, task.getTaskData().getLastModified()); } else { continue; } if (taskModifiedDate != null && taskModifiedDate.after(mostRecent)) { mostRecent = taskModifiedDate; mostRecentTimeStamp = task.getTaskData().getLastModified(); } } // TODO: Get actual time stamp of query from repository rather // than above hack MylarTaskListPlugin.getRepositoryManager().setSyncTime(repository, mostRecentTimeStamp); } }); } /** * Force the given task to be refreshed from the repository */ public final void forceRefresh(AbstractRepositoryTask task) { Set<AbstractRepositoryTask> toRefresh = new HashSet<AbstractRepositoryTask>(); toRefresh.add(task); synchronize(toRefresh, true, null); } /** * For testing */ public final void setForceSyncExec(boolean forceSyncExec) { this.forceSyncExecForTesting = forceSyncExec; } /** non-final for testing purposes */ protected void removeOfflineTaskData(RepositoryTaskData bug) { if (bug == null) return; ArrayList<RepositoryTaskData> bugList = new ArrayList<RepositoryTaskData>(); bugList.add(bug); MylarTaskListPlugin.getDefault().getOfflineReportsFile().remove(bugList); } // /** non-final for testing purposes */ // protected RepositoryTaskData loadOfflineTaskData(AbstractRepositoryTask // repositoryTask) { // // String url = // AbstractRepositoryTask.getRepositoryUrl(repositoryTask.getHandleIdentifier()); // String id = // AbstractRepositoryTask.getTaskId(repositoryTask.getHandleIdentifier()); // try { // return OfflineTaskManager.findBug(url, Integer.parseInt(id)); // } catch (Exception e) { // return null; // } // // } /** non-final for testing purposes */ public void saveOffline(RepositoryTaskData taskData) { try { MylarTaskListPlugin.getDefault().getOfflineReportsFile().add(taskData); } catch (CoreException e) { MylarStatusHandler.fail(e, e.getMessage(), false); } } public void openRemoteTask(String repositoryUrl, String idString) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), MylarTaskListPlugin.TITLE_DIALOG, "Not supported by connector: " + getLabel()); } private class MutexRule implements ISchedulingRule { public boolean isConflicting(ISchedulingRule rule) { return rule == this; } public boolean contains(ISchedulingRule rule) { return rule == this; } } }
true
true
public synchronized boolean updateOfflineState(final AbstractRepositoryTask repositoryTask, final RepositoryTaskData newTaskData, boolean forceSync) { RepositoryTaskSyncState startState = repositoryTask.getSyncState(); RepositoryTaskSyncState status = repositoryTask.getSyncState(); if (newTaskData == null) { MylarStatusHandler.log("Download of " + repositoryTask.getDescription() + " from " + repositoryTask.getRepositoryUrl() + " failed.", this); return false; } RepositoryTaskData offlineTaskData = repositoryTask.getTaskData(); // loadOfflineTaskData(repositoryTask) if (newTaskData.hasLocalChanges()) { // Special case for saving changes to local task data status = RepositoryTaskSyncState.OUTGOING; } else { switch (status) { case OUTGOING: if (!forceSync) { // Never overwrite local task data unless forced return false; } case CONFLICT: // use a parameter rather than this null check if (offlineTaskData != null) { // TODO: pull this ui out of here if (!forceSyncExecForTesting) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { updateLocalCopy = MessageDialog .openQuestion( null, "Update Local Copy", "Local copy of Report " + repositoryTask.getDescription() + " on " + repositoryTask.getRepositoryUrl() + " has changes.\nWould you like to override local changes? \n\nNote: if you select No, only the new comment will be saved with the updated bug, all other changes will be lost."); } }); } else { updateLocalCopy = true; } if (!updateLocalCopy) { newTaskData.setNewComment(offlineTaskData.getNewComment()); newTaskData.setHasLocalChanges(true); status = RepositoryTaskSyncState.CONFLICT; } else { newTaskData.setHasLocalChanges(false); if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } } } else { newTaskData.setHasLocalChanges(false); status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case INCOMING: if (!forceSync && checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case SYNCHRONIZED: if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } break; } repositoryTask.setModifiedDateStamp(newTaskData.getLastModified()); } // if (offlineTaskData != null) { // removeOfflineTaskData(offlineTaskData); // } repositoryTask.setTaskData(newTaskData); repositoryTask.setSyncState(status); saveOffline(newTaskData); if(status == RepositoryTaskSyncState.INCOMING) { repositoryTask.setNotified(false); } return startState == repositoryTask.getSyncState(); // } catch (final CoreException e) { // if (forceSync) { // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { // public void run() { // ErrorDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), // "Error Downloading Report", "Unable to synchronize " + // repositoryTask.getDescription(), // e.getStatus()); // } // }); // } // // else { // // MylarStatusHandler.fail(e, "Unable to synchronize " + // // repositoryTask.getDescription() // // + " on " + repository.getUrl(), false); // // } // return; // } }
public synchronized boolean updateOfflineState(final AbstractRepositoryTask repositoryTask, final RepositoryTaskData newTaskData, boolean forceSync) { RepositoryTaskSyncState startState = repositoryTask.getSyncState(); RepositoryTaskSyncState status = repositoryTask.getSyncState(); if (newTaskData == null) { MylarStatusHandler.log("Download of " + repositoryTask.getDescription() + " from " + repositoryTask.getRepositoryUrl() + " failed.", this); return false; } RepositoryTaskData offlineTaskData = repositoryTask.getTaskData(); // loadOfflineTaskData(repositoryTask) if (newTaskData.hasLocalChanges()) { // Special case for saving changes to local task data status = RepositoryTaskSyncState.OUTGOING; } else { switch (status) { case OUTGOING: if (!forceSync) { // Never overwrite local task data unless forced return false; } case CONFLICT: // use a parameter rather than this null check if (offlineTaskData != null) { // TODO: pull this ui out of here if (!forceSyncExecForTesting) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { updateLocalCopy = MessageDialog .openQuestion( null, "Update Local Copy", "Local copy of Report " + repositoryTask.getDescription() + " on " + repositoryTask.getRepositoryUrl() + " has changes.\nWould you like to override local changes? \n\nNote: if you select No, only the new comment will be saved with the updated bug, all other changes will be lost."); } }); } else { updateLocalCopy = true; } if (!updateLocalCopy) { newTaskData.setNewComment(offlineTaskData.getNewComment()); newTaskData.setHasLocalChanges(true); status = RepositoryTaskSyncState.CONFLICT; } else { newTaskData.setHasLocalChanges(false); if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } } } else { newTaskData.setHasLocalChanges(false); status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case INCOMING: if (!forceSync && checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case SYNCHRONIZED: if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } break; } repositoryTask.setModifiedDateStamp(newTaskData.getLastModified()); } // if (offlineTaskData != null) { // removeOfflineTaskData(offlineTaskData); // } repositoryTask.setTaskData(newTaskData); repositoryTask.setSyncState(status); saveOffline(newTaskData); if(status == RepositoryTaskSyncState.INCOMING) { repositoryTask.setNotified(false); } return startState != repositoryTask.getSyncState(); // } catch (final CoreException e) { // if (forceSync) { // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { // public void run() { // ErrorDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), // "Error Downloading Report", "Unable to synchronize " + // repositoryTask.getDescription(), // e.getStatus()); // } // }); // } // // else { // // MylarStatusHandler.fail(e, "Unable to synchronize " + // // repositoryTask.getDescription() // // + " on " + repository.getUrl(), false); // // } // return; // } }
diff --git a/libraries/phyloviewer-gwt-client/src/main/java/org/iplantc/phyloviewer/client/tree/viewer/DetailView.java b/libraries/phyloviewer-gwt-client/src/main/java/org/iplantc/phyloviewer/client/tree/viewer/DetailView.java index 75fdcc62..79fdbe7b 100644 --- a/libraries/phyloviewer-gwt-client/src/main/java/org/iplantc/phyloviewer/client/tree/viewer/DetailView.java +++ b/libraries/phyloviewer-gwt-client/src/main/java/org/iplantc/phyloviewer/client/tree/viewer/DetailView.java @@ -1,664 +1,673 @@ /** * Copyright (c) 2009, iPlant Collaborative, Texas Advanced Computing Center This software is licensed * under the CC-GNU GPL version 2.0 or later. License: http://creativecommons.org/licenses/GPL/2.0/ */ package org.iplantc.phyloviewer.client.tree.viewer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.iplantc.core.broadcaster.shared.BroadcastCommand; import org.iplantc.core.broadcaster.shared.Broadcaster; import org.iplantc.phyloviewer.client.events.BranchClickEvent; import org.iplantc.phyloviewer.client.events.BranchClickHandler; import org.iplantc.phyloviewer.client.events.LabelClickEvent; import org.iplantc.phyloviewer.client.events.LabelClickHandler; import org.iplantc.phyloviewer.client.events.NavigationMouseHandler; import org.iplantc.phyloviewer.client.events.NodeClickEvent; import org.iplantc.phyloviewer.client.events.NodeClickHandler; import org.iplantc.phyloviewer.client.events.NodeSelectionEvent; import org.iplantc.phyloviewer.client.events.NodeSelectionHandler; import org.iplantc.phyloviewer.client.events.SelectionMouseHandler; import org.iplantc.phyloviewer.client.services.SearchServiceAsyncImpl; import org.iplantc.phyloviewer.client.tree.viewer.IntersectTree.Hit; import org.iplantc.phyloviewer.client.tree.viewer.render.SearchHighlighter; import org.iplantc.phyloviewer.client.tree.viewer.render.canvas.Graphics; import org.iplantc.phyloviewer.shared.layout.ILayoutData; import org.iplantc.phyloviewer.shared.math.Box2D; import org.iplantc.phyloviewer.shared.math.Matrix33; import org.iplantc.phyloviewer.shared.math.Vector2; import org.iplantc.phyloviewer.shared.model.IDocument; import org.iplantc.phyloviewer.shared.model.INode; import org.iplantc.phyloviewer.shared.model.ITree; import org.iplantc.phyloviewer.shared.render.CameraCladogram; import org.iplantc.phyloviewer.shared.render.RenderPreferences; import org.iplantc.phyloviewer.shared.render.RenderTree; import org.iplantc.phyloviewer.shared.render.RenderTreeCladogram; import org.iplantc.phyloviewer.shared.scene.Drawable; import org.iplantc.phyloviewer.shared.scene.DrawableContainer; import com.google.gwt.core.client.Duration; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DoubleClickHandler; import com.google.gwt.event.dom.client.HandlesAllMouseEvents; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.dom.client.MouseDownEvent; import com.google.gwt.event.dom.client.MouseDownHandler; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseMoveHandler; import com.google.gwt.event.shared.EventBus; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.HandlerRegistration; public class DetailView extends AnimatedView implements Broadcaster { private int renderCount; private double[] renderTime = new double[60]; private boolean drawRenderStats = false; private Graphics graphics = null; private RenderTree renderer = new RenderTreeCladogram(); private SearchHighlighter highlighter = null; private boolean panX = false; private boolean panY = true; private SearchServiceAsyncImpl searchService; private Map<EventHandler,List<HandlerRegistration>> handlerRegistrations = new HashMap<EventHandler,List<HandlerRegistration>>(); private NavigationMouseHandler navigationMouseHandler; private SelectionMouseHandler selectionMouseHandler; BroadcastCommand broadcastCommand; Hit lastHit; public DetailView(int width, int height, SearchServiceAsyncImpl searchService) { this.setStylePrimaryName("detailView"); this.searchService = searchService; this.setCamera(new CameraCladogram()); graphics = new Graphics(width, height); this.add(graphics.getWidget()); this.addMouseMoveHandler(new MouseMoveHandler() { @Override public void onMouseMove(MouseMoveEvent arg0) { IntersectTree intersector = createIntersector(arg0.getX(), arg0.getY()); intersector.intersect(); Hit hit = intersector.getClosestHit(); int x = arg0.getClientX(); int y = arg0.getClientY(); - if(lastHit == null && hit != null) + if(lastHit != null && hit != null) + { + // Check the drawables and make sure they are the same. + if(lastHit.getDrawable() != hit.getDrawable()) + { + handleMouseOut(lastHit, x, y); + handleMouseOver(hit, x, y); + } + } + else if(lastHit == null && hit != null) { handleMouseOver(hit, x, y); } else if(lastHit != null && hit == null) { handleMouseOut(lastHit, x, y); } lastHit = hit; } }); this.addMouseDownHandler(new MouseDownHandler() { @Override public void onMouseDown(MouseDownEvent arg0) { if(arg0.getNativeButton() == 1) { Hit hit = lastHit; int x = arg0.getClientX(); int y = arg0.getClientY(); handleMouseClick(hit, x, y); } } }); } public void render() { try { if(this.isReady()) { Duration duration = new Duration(); renderer.renderTree(graphics, getCamera()); if(drawRenderStats) { renderStats(duration.elapsedMillis()); } } } catch(Exception e) { Logger.getLogger("").log(Level.WARNING, "An exception was caught in DetailView.render: " + e.getMessage()); } } public void resize(int width, int height) { graphics.resize(width, height); } public void setPannable(boolean x, boolean y) { this.panX = x; this.panY = y; } public boolean isXPannable() { return this.panX; } public boolean isYPannable() { return this.panY; } @Override public int getHeight() { return graphics.getHeight(); } @Override public int getWidth() { return graphics.getWidth(); } protected RenderTree getRenderer() { return renderer; } public void setRenderer(RenderTree renderer) { this.renderer = renderer; } @Override public void setDocument(IDocument document) { super.setDocument(document); this.getCamera().reset(); if(highlighter != null) { highlighter.dispose(); } ITree tree = this.getTree(); if(tree != null && renderer != null && this.searchService != null) { highlighter = new SearchHighlighter(this, this.searchService, tree, renderer.getRenderPreferences()); } if(renderer != null) { renderer.setDocument(document); } } @Override public boolean isReady() { boolean documentReady = this.getDocument() != null && this.getDocument().isReady(); boolean ready = documentReady && graphics != null && getCamera() != null; return ready; } private void renderStats(double time) { renderCount++; int index = renderCount % 60; renderTime[index] = time; String text = renderCount + " frames, last: " + Math.round(1.0 / time * 1000) + " FPS"; if(renderCount >= 60) { double totalTime = 0; for(double t : renderTime) { totalTime += t; } double fps = (60.0 / totalTime) * 1000; text += " average: " + Math.round(fps) + " FPS"; } graphics.getCanvas().setFillStyle("red"); graphics.getCanvas().fillText(text, 5, graphics.getCanvas().getHeight() - 5); } public String exportImageURL() { return graphics.getCanvas().toDataURL(); } public void setRenderPreferences(RenderPreferences rp) { super.setRenderPreferences(rp); renderer.setRenderPreferences(rp); } /** * @return the node at the given location, in this View's screen coordinate system */ public INode getNodeAt(int x, int y) { IntersectTree intersector = createIntersector(x, y); intersector.intersect(); Hit hit = intersector.getClosestHit(); return hit != null ? hit.getNode() : null; } /** * Create an intersector * * @param x position in screen coordinates * @param y position in screen coordinates * @return An object to perform intersections. */ private IntersectTree createIntersector(int x, int y) { Vector2 position = getPositionInLayoutSpace(new Vector2(x, y)); // Calculate the maximum size of a pixel side Vector2 v0 = getPositionInLayoutSpace(new Vector2(0, 0)); Vector2 v1 = getPositionInLayoutSpace(new Vector2(1, 1)); Vector2 distanceInObjectSpace = v1.subtract(v0); double distance = Math.max(distanceInObjectSpace.getX(), distanceInObjectSpace.getY()); DrawableContainer container = renderer != null ? renderer.getDrawableContainer() : null; IntersectTree intersector = new IntersectTree(getDocument(), container, position, distance); return intersector; } public Set<INode> getNodesIn(Box2D screenBox) { Set<INode> nodes = Collections.emptySet(); if(getTree() != null) { Box2D range = getBoxInLayoutSpace(screenBox); INode root = getTree().getRootNode(); ILayoutData layout = getLayout(); nodes = IntersectTreeBox.intersect(root, layout, range); } return nodes; } public Vector2 getPositionInLayoutSpace(Vector2 position) { Matrix33 IM = getCamera().getMatrix(getWidth(), getHeight()).inverse(); return IM.transform(position); } public Box2D getBoxInLayoutSpace(Box2D box) { Vector2 min = getPositionInLayoutSpace(box.getMin()); Vector2 max = getPositionInLayoutSpace(box.getMax()); return new Box2D(min, max); } public void setSelectionMode() { unregisterAllHandlers(); // remove any other mouse handlers this.addMouseHandler(selectionMouseHandler); // selectionMouseHandler will handle this view's // mouse events removeStyleName("navigation"); addStyleName("selection"); } public void setNavigationMode() { unregisterAllHandlers(); this.addMouseHandler(navigationMouseHandler); removeStyleName("selection"); addStyleName("navigation"); } public void setDefaults() { navigationMouseHandler = new NavigationMouseHandler(this); selectionMouseHandler = new SelectionMouseHandler(this); selectionMouseHandler.addSelectionHandler(new HighlightSelectionHandler()); selectionMouseHandler.addSelectionHandler(refireHandler); setSelectionMode(); this.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if(event.getCharCode() == 's') { setSelectionMode(); } else if(event.getCharCode() == 'n') { setNavigationMode(); } } }); this.setDrawRenderStats(true); } private void addMouseHandler(HandlesAllMouseEvents handler) { List<HandlerRegistration> registrations = handlerRegistrations.get(handler); if(registrations == null) { registrations = new ArrayList<HandlerRegistration>(); handlerRegistrations.put(handler, registrations); } // add this handler for all supported events registrations.add(this.addMouseDownHandler(handler)); registrations.add(this.addMouseUpHandler(handler)); registrations.add(this.addMouseOutHandler(handler)); registrations.add(this.addMouseOverHandler(handler)); registrations.add(this.addMouseMoveHandler(handler)); registrations.add(this.addMouseWheelHandler(handler)); if(handler instanceof ClickHandler) { registrations.add(this.addClickHandler((ClickHandler)handler)); } if(handler instanceof DoubleClickHandler) { registrations.add(this.addDoubleClickHandler((DoubleClickHandler)handler)); } } /** * Removes all handler registrations for the given handler */ private void unregister(EventHandler handler) { List<HandlerRegistration> registrations = handlerRegistrations.get(handler); if(registrations != null) { for(HandlerRegistration registration : registrations) { registration.removeHandler(); } } registrations.clear(); } private void unregisterAllHandlers() { for(EventHandler handler : handlerRegistrations.keySet()) { unregister(handler); } } /** * Highlights the selected nodes in this view */ private class HighlightSelectionHandler implements NodeSelectionHandler { @Override public void onNodeSelection(NodeSelectionEvent event) { getRenderPreferences().clearAllHighlights(); for(INode node : event.getSelectedNodes()) { getRenderPreferences().highlightNode(node); } requestRender(); } } @Override protected void initEventListeners() { super.initEventListeners(); EventBus eventBus = getEventBus(); if(eventBus != null) { eventBus.addHandler(NodeClickEvent.TYPE, new NodeClickHandler() { @Override public void onNodeClick(NodeClickEvent event) { broadcastEvent("node_clicked", event.getNodeId(), event.getClientX(), event.getClientY()); } }); eventBus.addHandler(BranchClickEvent.TYPE, new BranchClickHandler() { @Override public void onBranchClick(BranchClickEvent event) { broadcastEvent("branch_clicked", event.getNodeId(), event.getClientX(), event.getClientY()); } }); eventBus.addHandler(LabelClickEvent.TYPE, new LabelClickHandler() { @Override public void onLabelClick(LabelClickEvent event) { broadcastEvent("label_clicked", event.getNodeId(), event.getClientX(), event.getClientY()); } }); } } private void broadcastEvent(String type, int id, int clientX, int clientY) { if(broadcastCommand != null) { String json = "{\"event\":\"" + type + "\",\"id\":\"" + id + "\",\"mouse\":{\"x\":" + clientX + ",\"y\":" + clientY + "}}"; broadcastCommand.broadcast(json); } } @Override public void setBroadcastCommand(BroadcastCommand cmdBroadcast) { this.broadcastCommand = cmdBroadcast; } /** * Clear all highlighted nodes. */ public void clearHighlights() { RenderTree renderer = this.getRenderer(); if(renderer != null) { RenderPreferences prefs = renderer.getRenderPreferences(); if(prefs != null) { prefs.clearAllHighlights(); this.requestRender(); } } } /** * Highlight given node * @param node id */ public void highlightNode(Integer id) { RenderTree renderer = this.getRenderer(); if(renderer != null) { RenderPreferences prefs = renderer.getRenderPreferences(); if(prefs != null) { prefs.highlightNode(id); this.requestRender(); } } } /** * Highlight node and subtree for given id. * @param node id */ public void highlightSubtree(Integer id) { RenderTree renderer = this.getRenderer(); if(renderer != null) { RenderPreferences prefs = renderer.getRenderPreferences(); if(prefs != null) { prefs.highlightSubtree(id); this.requestRender(); } } } /** * Highlight branch to given node id. * @param node id */ public void highlightBranch(Integer id) { RenderTree renderer = this.getRenderer(); if(renderer != null) { RenderPreferences prefs = renderer.getRenderPreferences(); if(prefs != null) { prefs.highlightBranch(id); this.requestRender(); } } } public boolean isDrawRenderStats() { return drawRenderStats; } public void setDrawRenderStats(boolean drawRenderStats) { this.drawRenderStats = drawRenderStats; } private void handleMouseClick(Hit hit, int x, int y) { if(hit != null && hit.getDrawable() != null) { Drawable.Context context = hit.getDrawable().getContext(); if(Drawable.Context.CONTEXT_NODE == context) { dispatch(new NodeClickEvent(hit.getNodeId(), x, y)); } else if(Drawable.Context.CONTEXT_BRANCH == context) { dispatch(new BranchClickEvent(hit.getNodeId(), x, y)); } else if(Drawable.Context.CONTEXT_LABEL == context) { dispatch(new LabelClickEvent(hit.getNodeId(), x, y)); } } } private void handleMouseOver(Hit hit, int x, int y) { if(hit != null && hit.getDrawable() != null) { Drawable.Context context = hit.getDrawable().getContext(); if(Drawable.Context.CONTEXT_NODE == context) { broadcastEvent("node_mouse_over", hit.getNodeId(), x, y); } else if(Drawable.Context.CONTEXT_BRANCH == context) { broadcastEvent("branch_mouse_over", hit.getNodeId(), x, y); } else if(Drawable.Context.CONTEXT_LABEL == context) { broadcastEvent("label_mouse_over", hit.getNodeId(), x, y); } } } private void handleMouseOut(Hit hit, int x, int y) { if(hit != null && hit.getDrawable() != null) { Drawable.Context context = hit.getDrawable().getContext(); if(Drawable.Context.CONTEXT_NODE == context) { broadcastEvent("node_mouse_out", hit.getNodeId(), x, y); } else if(Drawable.Context.CONTEXT_BRANCH == context) { broadcastEvent("branch_mouse_out", hit.getNodeId(), x, y); } else if(Drawable.Context.CONTEXT_LABEL == context) { broadcastEvent("label_mouse_out", hit.getNodeId(), x, y); } } } }
true
true
public DetailView(int width, int height, SearchServiceAsyncImpl searchService) { this.setStylePrimaryName("detailView"); this.searchService = searchService; this.setCamera(new CameraCladogram()); graphics = new Graphics(width, height); this.add(graphics.getWidget()); this.addMouseMoveHandler(new MouseMoveHandler() { @Override public void onMouseMove(MouseMoveEvent arg0) { IntersectTree intersector = createIntersector(arg0.getX(), arg0.getY()); intersector.intersect(); Hit hit = intersector.getClosestHit(); int x = arg0.getClientX(); int y = arg0.getClientY(); if(lastHit == null && hit != null) { handleMouseOver(hit, x, y); } else if(lastHit != null && hit == null) { handleMouseOut(lastHit, x, y); } lastHit = hit; } }); this.addMouseDownHandler(new MouseDownHandler() { @Override public void onMouseDown(MouseDownEvent arg0) { if(arg0.getNativeButton() == 1) { Hit hit = lastHit; int x = arg0.getClientX(); int y = arg0.getClientY(); handleMouseClick(hit, x, y); } } }); }
public DetailView(int width, int height, SearchServiceAsyncImpl searchService) { this.setStylePrimaryName("detailView"); this.searchService = searchService; this.setCamera(new CameraCladogram()); graphics = new Graphics(width, height); this.add(graphics.getWidget()); this.addMouseMoveHandler(new MouseMoveHandler() { @Override public void onMouseMove(MouseMoveEvent arg0) { IntersectTree intersector = createIntersector(arg0.getX(), arg0.getY()); intersector.intersect(); Hit hit = intersector.getClosestHit(); int x = arg0.getClientX(); int y = arg0.getClientY(); if(lastHit != null && hit != null) { // Check the drawables and make sure they are the same. if(lastHit.getDrawable() != hit.getDrawable()) { handleMouseOut(lastHit, x, y); handleMouseOver(hit, x, y); } } else if(lastHit == null && hit != null) { handleMouseOver(hit, x, y); } else if(lastHit != null && hit == null) { handleMouseOut(lastHit, x, y); } lastHit = hit; } }); this.addMouseDownHandler(new MouseDownHandler() { @Override public void onMouseDown(MouseDownEvent arg0) { if(arg0.getNativeButton() == 1) { Hit hit = lastHit; int x = arg0.getClientX(); int y = arg0.getClientY(); handleMouseClick(hit, x, y); } } }); }
diff --git a/src/dk/markedsbooking/loppemarkeder/util/ReadURL.java b/src/dk/markedsbooking/loppemarkeder/util/ReadURL.java index 692e7e5..4ce64a7 100644 --- a/src/dk/markedsbooking/loppemarkeder/util/ReadURL.java +++ b/src/dk/markedsbooking/loppemarkeder/util/ReadURL.java @@ -1,91 +1,91 @@ package dk.markedsbooking.loppemarkeder.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import dk.markedsbooking.loppemarkeder.MainActivity; import dk.markedsbooking.loppemarkeder.dummy.MarkedContent; import dk.markedsbooking.loppemarkeder.model.MarkedItem; import android.os.AsyncTask; import android.util.Log; public class ReadURL extends AsyncTask<String, Void, String>{ @Override public String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } try { JSONObject jObject = new JSONObject(response); String aJsonString = jObject.getString("markedItemInstanceList"); Log.i(MainActivity.class.getName(), "aJsonString "+aJsonString); JSONArray jsonArray = new JSONArray(aJsonString); Log.i(MainActivity.class.getName(), "Number of entries " + jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); //2013-04-10T04:00:00Z Date fromDate = formatter.parse(jsonObject.getString("fromDate")); Date toDate = null; - if (jsonObject.getString("toDate") == null) { + if (jsonObject.getString("toDate") != null) { toDate = formatter.parse(jsonObject.getString("toDate")); } Long id = jsonObject.getLong("id"); String name = jsonObject.getString("name"); String address = jsonObject.getString("address"); String dateExtraInfo = jsonObject.getString("dateExtraInfo"); String entreInfo =jsonObject.getString("entreInfo"); double latitude = jsonObject.getDouble("latitude"); double longitude = jsonObject.getDouble("longitude"); String markedInformation = jsonObject.getString("markedInformation"); String markedRules= jsonObject.getString("markedRules"); Log.i(MainActivity.class.getName(), "name " +name); Log.i(MainActivity.class.getName(), "id "+ jsonObject.getLong("id")); Log.i(MainActivity.class.getName(), "fromDate "+ jsonObject.getString("fromDate")); Log.i(MainActivity.class.getName(), "date "+ fromDate); MarkedContent.addMarkedItem(new MarkedItem(""+id, name, fromDate, toDate, dateExtraInfo, entreInfo, markedRules, markedInformation, latitude, longitude,address )); } } catch (Exception e) { e.printStackTrace(); } return response; } }
true
true
public String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } try { JSONObject jObject = new JSONObject(response); String aJsonString = jObject.getString("markedItemInstanceList"); Log.i(MainActivity.class.getName(), "aJsonString "+aJsonString); JSONArray jsonArray = new JSONArray(aJsonString); Log.i(MainActivity.class.getName(), "Number of entries " + jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); //2013-04-10T04:00:00Z Date fromDate = formatter.parse(jsonObject.getString("fromDate")); Date toDate = null; if (jsonObject.getString("toDate") == null) { toDate = formatter.parse(jsonObject.getString("toDate")); } Long id = jsonObject.getLong("id"); String name = jsonObject.getString("name"); String address = jsonObject.getString("address"); String dateExtraInfo = jsonObject.getString("dateExtraInfo"); String entreInfo =jsonObject.getString("entreInfo"); double latitude = jsonObject.getDouble("latitude"); double longitude = jsonObject.getDouble("longitude"); String markedInformation = jsonObject.getString("markedInformation"); String markedRules= jsonObject.getString("markedRules"); Log.i(MainActivity.class.getName(), "name " +name); Log.i(MainActivity.class.getName(), "id "+ jsonObject.getLong("id")); Log.i(MainActivity.class.getName(), "fromDate "+ jsonObject.getString("fromDate")); Log.i(MainActivity.class.getName(), "date "+ fromDate); MarkedContent.addMarkedItem(new MarkedItem(""+id, name, fromDate, toDate, dateExtraInfo, entreInfo, markedRules, markedInformation, latitude, longitude,address )); } } catch (Exception e) { e.printStackTrace(); } return response; }
public String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } try { JSONObject jObject = new JSONObject(response); String aJsonString = jObject.getString("markedItemInstanceList"); Log.i(MainActivity.class.getName(), "aJsonString "+aJsonString); JSONArray jsonArray = new JSONArray(aJsonString); Log.i(MainActivity.class.getName(), "Number of entries " + jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); //2013-04-10T04:00:00Z Date fromDate = formatter.parse(jsonObject.getString("fromDate")); Date toDate = null; if (jsonObject.getString("toDate") != null) { toDate = formatter.parse(jsonObject.getString("toDate")); } Long id = jsonObject.getLong("id"); String name = jsonObject.getString("name"); String address = jsonObject.getString("address"); String dateExtraInfo = jsonObject.getString("dateExtraInfo"); String entreInfo =jsonObject.getString("entreInfo"); double latitude = jsonObject.getDouble("latitude"); double longitude = jsonObject.getDouble("longitude"); String markedInformation = jsonObject.getString("markedInformation"); String markedRules= jsonObject.getString("markedRules"); Log.i(MainActivity.class.getName(), "name " +name); Log.i(MainActivity.class.getName(), "id "+ jsonObject.getLong("id")); Log.i(MainActivity.class.getName(), "fromDate "+ jsonObject.getString("fromDate")); Log.i(MainActivity.class.getName(), "date "+ fromDate); MarkedContent.addMarkedItem(new MarkedItem(""+id, name, fromDate, toDate, dateExtraInfo, entreInfo, markedRules, markedInformation, latitude, longitude,address )); } } catch (Exception e) { e.printStackTrace(); } return response; }
diff --git a/thetvdbapi/src/main/java/com/moviejukebox/thetvdb/tools/TvdbParser.java b/thetvdbapi/src/main/java/com/moviejukebox/thetvdb/tools/TvdbParser.java index 9bede97..4cd13ed 100644 --- a/thetvdbapi/src/main/java/com/moviejukebox/thetvdb/tools/TvdbParser.java +++ b/thetvdbapi/src/main/java/com/moviejukebox/thetvdb/tools/TvdbParser.java @@ -1,452 +1,462 @@ /* * Copyright (c) 2004-2012 YAMJ Members * http://code.google.com/p/moviejukebox/people/list * * Web: http://code.google.com/p/moviejukebox/ * * This software is licensed under a Creative Commons License * See this page: http://code.google.com/p/moviejukebox/wiki/License * * For any reuse or distribution, you must make clear to others the * license terms of this work. */ package com.moviejukebox.thetvdb.tools; import com.moviejukebox.thetvdb.TheTVDB; import com.moviejukebox.thetvdb.model.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.ws.WebServiceException; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class TvdbParser { private static final Logger logger = Logger.getLogger(TvdbParser.class); private static final String TYPE_BANNER = "banner"; private static final String TYPE_FANART = "fanart"; private static final String TYPE_POSTER = "poster"; private static final String BANNER_PATH = "BannerPath"; private static final String VIGNETTE_PATH = "VignettePath"; private static final String THUMBNAIL_PATH = "ThumbnailPath"; private static final int MAX_EPISODE = 24; // The anticipated largest episode number // Hide the constructor protected TvdbParser() { // prevents calls from subclass throw new UnsupportedOperationException(); } /** * Get a list of the actors from the URL * @param urlString * @return */ public static List<Actor> getActors(String urlString) { List<Actor> results = new ArrayList<Actor>(); Actor actor; Document doc; NodeList nlActor; Node nActor; Element eActor; try { doc = DOMHelper.getEventDocFromUrl(urlString); } catch (WebServiceException ex) { return results; } nlActor = doc.getElementsByTagName("Actor"); for (int loop = 0; loop < nlActor.getLength(); loop++) { nActor = nlActor.item(loop); if (nActor.getNodeType() == Node.ELEMENT_NODE) { eActor = (Element) nActor; actor = new Actor(); actor.setId(DOMHelper.getValueFromElement(eActor, "id")); String image = DOMHelper.getValueFromElement(eActor, "Image"); if (!image.isEmpty()) { actor.setImage(TheTVDB.getBannerMirror() + image); } actor.setName(DOMHelper.getValueFromElement(eActor, "Name")); actor.setRole(DOMHelper.getValueFromElement(eActor, "Role")); actor.setSortOrder(DOMHelper.getValueFromElement(eActor, "SortOrder")); results.add(actor); } } Collections.sort(results); return results; } /** * Get all the episodes from the URL * @param urlString * @param season * @return */ public static List<Episode> getAllEpisodes(String urlString, int season) { List<Episode> episodeList = new ArrayList<Episode>(); Episode episode; NodeList nlEpisode; Node nEpisode; Element eEpisode; try { Document doc = DOMHelper.getEventDocFromUrl(urlString); nlEpisode = doc.getElementsByTagName("Episode"); for (int loop = 0; loop < nlEpisode.getLength(); loop++) { nEpisode = nlEpisode.item(loop); if (nEpisode.getNodeType() == Node.ELEMENT_NODE) { eEpisode = (Element) nEpisode; episode = parseNextEpisode(eEpisode); if ((episode != null) && (season == -1 || episode.getSeasonNumber() == season)) { // Add the episode only if the season is -1 (all seasons) or matches the season episodeList.add(episode); } } } } catch (WebServiceException ex) { logger.warn("All Episodes error: " + ex.getMessage()); } return episodeList; } /** * Get a list of banners from the URL * @param urlString * @return */ public static Banners getBanners(String urlString) { Banners banners = new Banners(); Banner banner; NodeList nlBanners; Node nBanner; Element eBanner; try { Document doc = DOMHelper.getEventDocFromUrl(urlString); nlBanners = doc.getElementsByTagName("Banner"); for (int loop = 0; loop < nlBanners.getLength(); loop++) { nBanner = nlBanners.item(loop); if (nBanner.getNodeType() == Node.ELEMENT_NODE) { eBanner = (Element) nBanner; banner = parseNextBanner(eBanner); if (banner != null) { banners.addBanner(banner); } } } } catch (WebServiceException ex) { logger.warn("Banners error: " + ex.getMessage()); } return banners; } /** * Get the episode information from the URL * @param urlString * @return */ public static Episode getEpisode(String urlString) { Episode episode = null; NodeList nlEpisode; Node nEpisode; Element eEpisode; try { Document doc = DOMHelper.getEventDocFromUrl(urlString); nlEpisode = doc.getElementsByTagName("Episode"); for (int loop = 0; loop < nlEpisode.getLength(); loop++) { nEpisode = nlEpisode.item(loop); if (nEpisode.getNodeType() == Node.ELEMENT_NODE) { eEpisode = (Element) nEpisode; episode = parseNextEpisode(eEpisode); if (episode != null) { // We only need the first episode break; } } } } catch (WebServiceException ex) { logger.warn("Series error: " + ex.getMessage()); } return episode; } /** * Get a list of series from the URL * @param urlString * @return */ public static List<Series> getSeriesList(String urlString) { List<Series> seriesList = new ArrayList<Series>(); Series series; NodeList nlSeries; Node nSeries; Element eSeries; Document doc; try { doc = DOMHelper.getEventDocFromUrl(urlString); } catch (WebServiceException ex) { return seriesList; } nlSeries = doc.getElementsByTagName("Series"); for (int loop = 0; loop < nlSeries.getLength(); loop++) { nSeries = nlSeries.item(loop); if (nSeries.getNodeType() == Node.ELEMENT_NODE) { eSeries = (Element) nSeries; series = parseNextSeries(eSeries); if (series != null) { seriesList.add(series); } } } return seriesList; } /** * Parse the error message to return a more user friendly message * @param errorMessage * @return */ public static String parseErrorMessage(String errorMessage) { StringBuilder response = new StringBuilder(); Pattern pattern = Pattern.compile(".*?/series/(\\d*?)/default/(\\d*?)/(\\d*?)/.*?"); Matcher matcher = pattern.matcher(errorMessage); // See if the error message matches the pattern and therefore we can decode it if (matcher.find() && matcher.groupCount() == 3) { int seriesId = Integer.parseInt(matcher.group(1)); int seasonId = Integer.parseInt(matcher.group(2)); int episodeId = Integer.parseInt(matcher.group(3)); response.append("Series Id: ").append(seriesId); response.append(", Season: ").append(seasonId); response.append(", Episode: ").append(episodeId); response.append(": "); if (episodeId == 0) { // We should probably try an scrape season 0/episode 1 response.append("Episode seems to be a misnamed pilot episode."); } else if (episodeId > MAX_EPISODE) { response.append("Episode number seems to be too large."); } else if (seasonId == 0 && episodeId > 1) { response.append("This special episode does not exist."); } else if (errorMessage.toLowerCase().contains("content is not allowed in prolog")) { response.append("Unable to retrieve episode information from TheTVDb, try again later."); } else { response.append("Unknown episode error: ").append(errorMessage); } } else { // Don't recognise the error format, so just return it if (errorMessage.toLowerCase().contains("content is not allowed in prolog")) { response.append("Unable to retrieve episode information from TheTVDb, try again later."); } else { response.append("Episode error: ").append(errorMessage); } } return response.toString(); } /** * Create a List from a delimited string * @param input * @param delim * @return */ private static List<String> parseList(String input, String delim) { List<String> result = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(input, delim); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.length() > 0) { result.add(token); } } return result; } /** * Parse the banner record from the document * @param eBanner * @return * @throws Throwable */ private static Banner parseNextBanner(Element eBanner) { String bannerMirror = TheTVDB.getBannerMirror(); Banner banner = new Banner(); String artwork; artwork = DOMHelper.getValueFromElement(eBanner, BANNER_PATH); if (!artwork.isEmpty()) { banner.setUrl(bannerMirror + artwork); } artwork = DOMHelper.getValueFromElement(eBanner, VIGNETTE_PATH); if (!artwork.isEmpty()) { banner.setVignette(bannerMirror + artwork); } artwork = DOMHelper.getValueFromElement(eBanner, THUMBNAIL_PATH); if (!artwork.isEmpty()) { banner.setThumb(bannerMirror + artwork); } banner.setId(DOMHelper.getValueFromElement(eBanner, "id")); banner.setBannerType(BannerListType.fromString(DOMHelper.getValueFromElement(eBanner, "BannerType"))); banner.setBannerType2(BannerType.fromString(DOMHelper.getValueFromElement(eBanner, "BannerType2"))); banner.setLanguage(DOMHelper.getValueFromElement(eBanner, "Language")); banner.setSeason(DOMHelper.getValueFromElement(eBanner, "Season")); banner.setColours(DOMHelper.getValueFromElement(eBanner, "Colors")); try { banner.setSeriesName(Boolean.parseBoolean(DOMHelper.getValueFromElement(eBanner, "SeriesName"))); } catch (WebServiceException ex) { banner.setSeriesName(false); } return banner; } /** * Parse the document for episode information * @param doc * @return * @throws Throwable */ private static Episode parseNextEpisode(Element eEpisode) { Episode episode = new Episode(); episode.setId(DOMHelper.getValueFromElement(eEpisode, "id")); episode.setCombinedEpisodeNumber(DOMHelper.getValueFromElement(eEpisode, "Combined_episodenumber")); episode.setCombinedSeason(DOMHelper.getValueFromElement(eEpisode, "Combined_season")); episode.setDvdChapter(DOMHelper.getValueFromElement(eEpisode, "DVD_chapter")); episode.setDvdDiscId(DOMHelper.getValueFromElement(eEpisode, "DVD_discid")); episode.setDvdEpisodeNumber(DOMHelper.getValueFromElement(eEpisode, "DVD_episodenumber")); episode.setDvdSeason(DOMHelper.getValueFromElement(eEpisode, "DVD_season")); episode.setDirectors(parseList(DOMHelper.getValueFromElement(eEpisode, "Director"), "|,")); episode.setEpImgFlag(DOMHelper.getValueFromElement(eEpisode, "EpImgFlag")); episode.setEpisodeName(DOMHelper.getValueFromElement(eEpisode, "EpisodeName")); try { episode.setEpisodeNumber(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "EpisodeNumber"))); + } catch (NumberFormatException ex) { + episode.setEpisodeNumber(0); } catch (WebServiceException ex) { episode.setEpisodeNumber(0); } episode.setFirstAired(DOMHelper.getValueFromElement(eEpisode, "FirstAired")); episode.setGuestStars(parseList(DOMHelper.getValueFromElement(eEpisode, "GuestStars"), "|,")); episode.setImdbId(DOMHelper.getValueFromElement(eEpisode, "IMDB_ID")); episode.setLanguage(DOMHelper.getValueFromElement(eEpisode, "Language")); episode.setOverview(DOMHelper.getValueFromElement(eEpisode, "Overview")); episode.setProductionCode(DOMHelper.getValueFromElement(eEpisode, "ProductionCode")); episode.setRating(DOMHelper.getValueFromElement(eEpisode, "Rating")); try { episode.setSeasonNumber(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "SeasonNumber"))); + } catch (NumberFormatException ex) { + episode.setSeasonNumber(0); } catch (WebServiceException ex) { episode.setSeasonNumber(0); } episode.setWriters(parseList(DOMHelper.getValueFromElement(eEpisode, "Writer"), "|,")); episode.setAbsoluteNumber(DOMHelper.getValueFromElement(eEpisode, "absolute_number")); String s = DOMHelper.getValueFromElement(eEpisode, "filename"); if (!s.isEmpty()) { episode.setFilename(TheTVDB.getBannerMirror() + s); } episode.setLastUpdated(DOMHelper.getValueFromElement(eEpisode, "lastupdated")); episode.setSeasonId(DOMHelper.getValueFromElement(eEpisode, "seasonid")); episode.setSeriesId(DOMHelper.getValueFromElement(eEpisode, "seriesid")); try { episode.setAirsAfterSeason(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "airsafter_season"))); + } catch (NumberFormatException ex) { + episode.setAirsAfterSeason(0); } catch (WebServiceException ex) { episode.setAirsAfterSeason(0); } try { episode.setAirsBeforeEpisode(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "airsbefore_episode"))); + } catch (NumberFormatException ex) { + episode.setAirsBeforeEpisode(0); } catch (WebServiceException ex) { episode.setAirsBeforeEpisode(0); } try { episode.setAirsBeforeSeason(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "airsbefore_season"))); + } catch (NumberFormatException ex) { + episode.setAirsBeforeSeason(0); } catch (WebServiceException ex) { episode.setAirsBeforeSeason(0); } return episode; } /** * Parse the series record from the document * @param eSeries * @return * @throws Throwable */ private static Series parseNextSeries(Element eSeries) { String bannerMirror = TheTVDB.getBannerMirror(); Series series = new Series(); series.setId(DOMHelper.getValueFromElement(eSeries, "id")); series.setActors(parseList(DOMHelper.getValueFromElement(eSeries, "Actors"), "|,")); series.setAirsDayOfWeek(DOMHelper.getValueFromElement(eSeries, "Airs_DayOfWeek")); series.setAirsTime(DOMHelper.getValueFromElement(eSeries, "Airs_Time")); series.setContentRating(DOMHelper.getValueFromElement(eSeries, "ContentRating")); series.setFirstAired(DOMHelper.getValueFromElement(eSeries, "FirstAired")); series.setGenres(parseList(DOMHelper.getValueFromElement(eSeries, "Genre"), "|,")); series.setImdbId(DOMHelper.getValueFromElement(eSeries, "IMDB_ID")); series.setLanguage(DOMHelper.getValueFromElement(eSeries, "language")); series.setNetwork(DOMHelper.getValueFromElement(eSeries, "Network")); series.setOverview(DOMHelper.getValueFromElement(eSeries, "Overview")); series.setRating(DOMHelper.getValueFromElement(eSeries, "Rating")); series.setRuntime(DOMHelper.getValueFromElement(eSeries, "Runtime")); series.setSeriesId(DOMHelper.getValueFromElement(eSeries, "SeriesID")); series.setSeriesName(DOMHelper.getValueFromElement(eSeries, "SeriesName")); series.setStatus(DOMHelper.getValueFromElement(eSeries, "Status")); String artwork = DOMHelper.getValueFromElement(eSeries, TYPE_BANNER); if (!artwork.isEmpty()) { series.setBanner(bannerMirror + artwork); } artwork = DOMHelper.getValueFromElement(eSeries, TYPE_FANART); if (!artwork.isEmpty()) { series.setFanart(bannerMirror + artwork); } artwork = DOMHelper.getValueFromElement(eSeries, TYPE_POSTER); if (!artwork.isEmpty()) { series.setPoster(bannerMirror + artwork); } series.setLastUpdated(DOMHelper.getValueFromElement(eSeries, "lastupdated")); series.setZap2ItId(DOMHelper.getValueFromElement(eSeries, "zap2it_id")); return series; } }
false
true
private static Episode parseNextEpisode(Element eEpisode) { Episode episode = new Episode(); episode.setId(DOMHelper.getValueFromElement(eEpisode, "id")); episode.setCombinedEpisodeNumber(DOMHelper.getValueFromElement(eEpisode, "Combined_episodenumber")); episode.setCombinedSeason(DOMHelper.getValueFromElement(eEpisode, "Combined_season")); episode.setDvdChapter(DOMHelper.getValueFromElement(eEpisode, "DVD_chapter")); episode.setDvdDiscId(DOMHelper.getValueFromElement(eEpisode, "DVD_discid")); episode.setDvdEpisodeNumber(DOMHelper.getValueFromElement(eEpisode, "DVD_episodenumber")); episode.setDvdSeason(DOMHelper.getValueFromElement(eEpisode, "DVD_season")); episode.setDirectors(parseList(DOMHelper.getValueFromElement(eEpisode, "Director"), "|,")); episode.setEpImgFlag(DOMHelper.getValueFromElement(eEpisode, "EpImgFlag")); episode.setEpisodeName(DOMHelper.getValueFromElement(eEpisode, "EpisodeName")); try { episode.setEpisodeNumber(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "EpisodeNumber"))); } catch (WebServiceException ex) { episode.setEpisodeNumber(0); } episode.setFirstAired(DOMHelper.getValueFromElement(eEpisode, "FirstAired")); episode.setGuestStars(parseList(DOMHelper.getValueFromElement(eEpisode, "GuestStars"), "|,")); episode.setImdbId(DOMHelper.getValueFromElement(eEpisode, "IMDB_ID")); episode.setLanguage(DOMHelper.getValueFromElement(eEpisode, "Language")); episode.setOverview(DOMHelper.getValueFromElement(eEpisode, "Overview")); episode.setProductionCode(DOMHelper.getValueFromElement(eEpisode, "ProductionCode")); episode.setRating(DOMHelper.getValueFromElement(eEpisode, "Rating")); try { episode.setSeasonNumber(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "SeasonNumber"))); } catch (WebServiceException ex) { episode.setSeasonNumber(0); } episode.setWriters(parseList(DOMHelper.getValueFromElement(eEpisode, "Writer"), "|,")); episode.setAbsoluteNumber(DOMHelper.getValueFromElement(eEpisode, "absolute_number")); String s = DOMHelper.getValueFromElement(eEpisode, "filename"); if (!s.isEmpty()) { episode.setFilename(TheTVDB.getBannerMirror() + s); } episode.setLastUpdated(DOMHelper.getValueFromElement(eEpisode, "lastupdated")); episode.setSeasonId(DOMHelper.getValueFromElement(eEpisode, "seasonid")); episode.setSeriesId(DOMHelper.getValueFromElement(eEpisode, "seriesid")); try { episode.setAirsAfterSeason(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "airsafter_season"))); } catch (WebServiceException ex) { episode.setAirsAfterSeason(0); } try { episode.setAirsBeforeEpisode(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "airsbefore_episode"))); } catch (WebServiceException ex) { episode.setAirsBeforeEpisode(0); } try { episode.setAirsBeforeSeason(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "airsbefore_season"))); } catch (WebServiceException ex) { episode.setAirsBeforeSeason(0); } return episode; }
private static Episode parseNextEpisode(Element eEpisode) { Episode episode = new Episode(); episode.setId(DOMHelper.getValueFromElement(eEpisode, "id")); episode.setCombinedEpisodeNumber(DOMHelper.getValueFromElement(eEpisode, "Combined_episodenumber")); episode.setCombinedSeason(DOMHelper.getValueFromElement(eEpisode, "Combined_season")); episode.setDvdChapter(DOMHelper.getValueFromElement(eEpisode, "DVD_chapter")); episode.setDvdDiscId(DOMHelper.getValueFromElement(eEpisode, "DVD_discid")); episode.setDvdEpisodeNumber(DOMHelper.getValueFromElement(eEpisode, "DVD_episodenumber")); episode.setDvdSeason(DOMHelper.getValueFromElement(eEpisode, "DVD_season")); episode.setDirectors(parseList(DOMHelper.getValueFromElement(eEpisode, "Director"), "|,")); episode.setEpImgFlag(DOMHelper.getValueFromElement(eEpisode, "EpImgFlag")); episode.setEpisodeName(DOMHelper.getValueFromElement(eEpisode, "EpisodeName")); try { episode.setEpisodeNumber(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "EpisodeNumber"))); } catch (NumberFormatException ex) { episode.setEpisodeNumber(0); } catch (WebServiceException ex) { episode.setEpisodeNumber(0); } episode.setFirstAired(DOMHelper.getValueFromElement(eEpisode, "FirstAired")); episode.setGuestStars(parseList(DOMHelper.getValueFromElement(eEpisode, "GuestStars"), "|,")); episode.setImdbId(DOMHelper.getValueFromElement(eEpisode, "IMDB_ID")); episode.setLanguage(DOMHelper.getValueFromElement(eEpisode, "Language")); episode.setOverview(DOMHelper.getValueFromElement(eEpisode, "Overview")); episode.setProductionCode(DOMHelper.getValueFromElement(eEpisode, "ProductionCode")); episode.setRating(DOMHelper.getValueFromElement(eEpisode, "Rating")); try { episode.setSeasonNumber(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "SeasonNumber"))); } catch (NumberFormatException ex) { episode.setSeasonNumber(0); } catch (WebServiceException ex) { episode.setSeasonNumber(0); } episode.setWriters(parseList(DOMHelper.getValueFromElement(eEpisode, "Writer"), "|,")); episode.setAbsoluteNumber(DOMHelper.getValueFromElement(eEpisode, "absolute_number")); String s = DOMHelper.getValueFromElement(eEpisode, "filename"); if (!s.isEmpty()) { episode.setFilename(TheTVDB.getBannerMirror() + s); } episode.setLastUpdated(DOMHelper.getValueFromElement(eEpisode, "lastupdated")); episode.setSeasonId(DOMHelper.getValueFromElement(eEpisode, "seasonid")); episode.setSeriesId(DOMHelper.getValueFromElement(eEpisode, "seriesid")); try { episode.setAirsAfterSeason(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "airsafter_season"))); } catch (NumberFormatException ex) { episode.setAirsAfterSeason(0); } catch (WebServiceException ex) { episode.setAirsAfterSeason(0); } try { episode.setAirsBeforeEpisode(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "airsbefore_episode"))); } catch (NumberFormatException ex) { episode.setAirsBeforeEpisode(0); } catch (WebServiceException ex) { episode.setAirsBeforeEpisode(0); } try { episode.setAirsBeforeSeason(Integer.parseInt(DOMHelper.getValueFromElement(eEpisode, "airsbefore_season"))); } catch (NumberFormatException ex) { episode.setAirsBeforeSeason(0); } catch (WebServiceException ex) { episode.setAirsBeforeSeason(0); } return episode; }
diff --git a/dspace/src/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java b/dspace/src/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java index a94824b3b..0cd5e0082 100644 --- a/dspace/src/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java +++ b/dspace/src/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java @@ -1,617 +1,617 @@ /* * EditCommunities.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.webui.servlet.admin; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.FileUploadRequest; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Bitstream; import org.dspace.content.BitstreamFormat; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.FormatIdentifier; import org.dspace.content.Item; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.Group; /** * Servlet for editing communities and collections, including deletion, * creation, and metadata editing * * @author Robert Tansley * @version $Revision$ */ public class EditCommunitiesServlet extends DSpaceServlet { /** User wants to edit a community */ public static final int START_EDIT_COMMUNITY = 1; /** User wants to delete a community */ public static final int START_DELETE_COMMUNITY = 2; /** User wants to create a community */ public static final int START_CREATE_COMMUNITY = 3; /** User wants to edit a collection */ public static final int START_EDIT_COLLECTION = 4; /** User wants to delete a collection */ public static final int START_DELETE_COLLECTION = 5; /** User wants to create a collection */ public static final int START_CREATE_COLLECTION = 6; /** User commited community edit or creation */ public static final int CONFIRM_EDIT_COMMUNITY = 7; /** User confirmed community deletion*/ public static final int CONFIRM_DELETE_COMMUNITY = 8; /** User commited collection edit or creation */ public static final int CONFIRM_EDIT_COLLECTION = 9; /** User wants to delete a collection */ public static final int CONFIRM_DELETE_COLLECTION = 10; /** Logger */ private static Logger log = Logger.getLogger(EditCommunitiesServlet.class); protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // GET just displays the list of communities and collections showControls(context, request, response); } protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // First, see if we have a multipart request (uploading a logo) String contentType = request.getContentType(); if (contentType != null && contentType.indexOf("multipart/form-data") != -1) { // This is a multipart request, so it's a file upload processUploadLogo(context, request, response); return; } /* * Respond to submitted forms. Each form includes an "action" parameter * indicating what needs to be done (from the constants above.) */ int action = UIUtil.getIntParameter(request, "action"); /* * Most of the forms supply one or both of these values. Since we just * get null if we try and find something with ID -1, we'll just try * and find both here to save hassle later on */ Community community = Community.find(context, UIUtil.getIntParameter(request, "community_id")); Collection collection = Collection.find(context, UIUtil.getIntParameter(request, "collection_id")); // Just about every JSP will need the values we received request.setAttribute("community", community); request.setAttribute("collection", collection); /* * First we check for a "cancel" button - if it's been pressed, we * simply return to the main control page */ if (request.getParameter("submit_cancel") != null) { showControls(context, request, response); return; } // Now proceed according to "action" parameter switch (action) { case START_EDIT_COMMUNITY: // Display the relevant "edit community" page JSPManager.showJSP(request, response, "/admin/edit-community.jsp"); break; case START_DELETE_COMMUNITY: // Show "confirm delete" page JSPManager.showJSP(request, response, "/admin/confirm-delete-community.jsp"); break; case START_CREATE_COMMUNITY: // Display edit community page with empty fields + create button JSPManager.showJSP(request, response, "/admin/edit-community.jsp"); break; case START_EDIT_COLLECTION: // Display the relevant "edit collection" page JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); break; case START_DELETE_COLLECTION: // Show "confirm delete" page JSPManager.showJSP(request, response, "/admin/confirm-delete-collection.jsp"); break; case START_CREATE_COLLECTION: // Display edit collection page with empty fields + create button JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); break; case CONFIRM_EDIT_COMMUNITY: // Edit or creation of a community confirmed processConfirmEditCommunity(context, request, response, community); break; case CONFIRM_DELETE_COMMUNITY: // Delete the community community.delete(); // Show main control page showControls(context, request, response); // Commit changes to DB context.complete(); break; case CONFIRM_EDIT_COLLECTION: // Edit or creation of a collection confirmed processConfirmEditCollection( context, request, response, community, collection); break; case CONFIRM_DELETE_COLLECTION: // Delete the collection community.removeCollection(collection); // Show main control page showControls(context, request, response); // Commit changes to DB context.complete(); break; default: // Erm... weird action value received. log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } } /** * Show list of communities and collections with controls * * @param context Current DSpace context * @param request Current HTTP request * @param response Current HTTP response */ private void showControls(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { Community[] communities = Community.findAll(context); // Build up a map in which the keys are community IDs and the // values are collections - this is so the JSP doesn't have to do // the work Map communityIDToCollection = new HashMap(); for (int i = 0; i < communities.length; i++) { communityIDToCollection.put(new Integer(communities[i].getID()), communities[i].getCollections()); } log.info(LogManager.getHeader(context, "view_editcommunities", "")); // Set attributes for JSP request.setAttribute("communities", communities); request.setAttribute("collections.map", communityIDToCollection); JSPManager.showJSP(request, response, "/admin/list-communities.jsp"); } /** * Create/update community metadata from a posted form * * @param context DSpace context * @param request the HTTP request containing posted info * @param response the HTTP response * @param community the community to update (or null for creation) */ private void processConfirmEditCommunity(Context context, HttpServletRequest request, HttpServletResponse response, Community community) throws ServletException, IOException, SQLException, AuthorizeException { if (request.getParameter("create").equals("true")) { // We need to create a new community community = Community.create(context); // Set attribute request.setAttribute("community", community); } community.setMetadata("name", request.getParameter("name")); community.setMetadata("short_description", request.getParameter("short_description")); String intro = request.getParameter("introductory_text"); if (intro.equals("")) { intro = null; } String copy = request.getParameter("copyright_text"); if (copy.equals("")) { copy = null; } String side = request.getParameter("side_bar_text"); if (side.equals("")) { side = null; } community.setMetadata("introductory_text", intro); community.setMetadata("copyright_text", copy); community.setMetadata("side_bar_text", side); community.update(); // Which button was pressed? String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_set_logo")) { // Change the logo - delete any that might be there first community.setLogo(null); community.update(); // Display "upload logo" page. Necessary attributes already set by // doDSPost() JSPManager.showJSP(request, response, "/admin/upload-logo.jsp"); } else if(button.equals("submit_delete_logo")) { // Simply delete logo community.setLogo(null); community.update(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-community.jsp"); } else { // Button at bottom clicked - show main control page showControls(context, request, response); } // Commit changes to DB context.complete(); } /** * Create/update collection metadata from a posted form * * @param context DSpace context * @param request the HTTP request containing posted info * @param response the HTTP response * @param community the community the collection is in * @param collection the collection to update (or null for creation) */ private void processConfirmEditCollection(Context context, HttpServletRequest request, HttpServletResponse response, Community community, Collection collection) throws ServletException, IOException, SQLException, AuthorizeException { if (request.getParameter("create").equals("true")) { // We need to create a new community collection = community.createCollection(); request.setAttribute("collection", collection); } // Update the basic metadata collection.setMetadata("name", request.getParameter("name")); collection.setMetadata("short_description", request.getParameter("short_description")); String intro = request.getParameter("introductory_text"); if (intro.equals("")) { intro = null; } String copy = request.getParameter("copyright_text"); if (copy.equals("")) { copy = null; } String side = request.getParameter("side_bar_text"); if (side.equals("")) { side = null; } String license = request.getParameter("license"); if (license.equals("")) { license = null; } String provenance = request.getParameter("provenance_description"); if (provenance.equals("")) { provenance = null; } collection.setMetadata("introductory_text", intro); collection.setMetadata("copyright_text", copy); collection.setMetadata("side_bar_text", side); collection.setMetadata("license", license); - collection.setMetadata("provenance_description", license); + collection.setMetadata("provenance_description", provenance); // Which button was pressed? String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_set_logo")) { // Change the logo - delete any that might be there first collection.setLogo(null); // Display "upload logo" page. Necessary attributes already set by // doDSPost() JSPManager.showJSP(request, response, "/admin/upload-logo.jsp"); } else if(button.equals("submit_delete_logo")) { // Simply delete logo collection.setLogo(null); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } else if(button.startsWith("submit_wf_create_")) { int step = Integer.parseInt(button.substring(17)); // Create new group Group newGroup = Group.create(context); newGroup.setName("COLLECTION_" + collection.getID() + "_WFSTEP_" + step); newGroup.update(); collection.setWorkflowGroup(step, newGroup); collection.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/groups?group=" + newGroup.getID())); } else if(button.startsWith("submit_wf_edit_")) { int step = Integer.parseInt(button.substring(15)); // Edit workflow group Group g = collection.getWorkflowGroup(step); response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/groups?group=" + g.getID())); } else if(button.startsWith("submit_wf_delete_")) { // Delete workflow group int step = Integer.parseInt(button.substring(17)); Group g = collection.getWorkflowGroup(step); collection.setWorkflowGroup(step, null); // Have to update to avoid ref. integrity error collection.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } else if(button.equals("submit_create_template")) { // Create a template item collection.createTemplateItem(); // Forward to edit page for new template item Item i = collection.getTemplateItem(); response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/edit_item?item_id=" + i.getID())); } else if(button.equals("submit_edit_template")) { // Forward to edit page for template item Item i = collection.getTemplateItem(); response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/edit_item?item_id=" + i.getID())); } else if(button.equals("submit_delete_template")) { collection.removeTemplateItem(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } else { // Plain old "create/update" button pressed - go back to main page showControls(context, request, response); } // Commit changes to DB collection.update(); context.complete(); } /** * Process the input from the upload logo page * * @param context current DSpace context * @param request current servlet request object * @param response current servlet response object */ private void processUploadLogo(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Wrap multipart request to get the submission info FileUploadRequest wrapper = new FileUploadRequest(request); Community community = Community.find(context, UIUtil.getIntParameter(wrapper, "community_id")); Collection collection = Collection.find(context, UIUtil.getIntParameter(wrapper, "collection_id")); File temp = wrapper.getFile("file"); // Read the temp file as logo InputStream is = new BufferedInputStream(new FileInputStream( temp)); Bitstream logoBS; if (community != null) { logoBS = community.setLogo(is); } else { logoBS = collection.setLogo(is); } // Strip all but the last filename. It would be nice // to know which OS the file came from. String noPath = wrapper.getFilesystemName("file"); while (noPath.indexOf('/') > -1) { noPath = noPath.substring( noPath.indexOf('/') + 1); } while (noPath.indexOf('\\') > -1) { noPath = noPath.substring( noPath.indexOf('\\') + 1); } logoBS.setName(noPath); logoBS.setSource(wrapper.getFilesystemName("file")); // Identify the format BitstreamFormat bf = FormatIdentifier.guessFormat(context, logoBS); logoBS.setFormat(bf); logoBS.update(); if (community != null) { community.update(); // Show community edit page request.setAttribute("community", community); JSPManager.showJSP(request, response, "/admin/edit-community.jsp"); } else { collection.update(); // Show collection edit page request.setAttribute("collection", collection); JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } // Remove temp file temp.delete(); // Update DB context.complete(); } }
true
true
private void processConfirmEditCollection(Context context, HttpServletRequest request, HttpServletResponse response, Community community, Collection collection) throws ServletException, IOException, SQLException, AuthorizeException { if (request.getParameter("create").equals("true")) { // We need to create a new community collection = community.createCollection(); request.setAttribute("collection", collection); } // Update the basic metadata collection.setMetadata("name", request.getParameter("name")); collection.setMetadata("short_description", request.getParameter("short_description")); String intro = request.getParameter("introductory_text"); if (intro.equals("")) { intro = null; } String copy = request.getParameter("copyright_text"); if (copy.equals("")) { copy = null; } String side = request.getParameter("side_bar_text"); if (side.equals("")) { side = null; } String license = request.getParameter("license"); if (license.equals("")) { license = null; } String provenance = request.getParameter("provenance_description"); if (provenance.equals("")) { provenance = null; } collection.setMetadata("introductory_text", intro); collection.setMetadata("copyright_text", copy); collection.setMetadata("side_bar_text", side); collection.setMetadata("license", license); collection.setMetadata("provenance_description", license); // Which button was pressed? String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_set_logo")) { // Change the logo - delete any that might be there first collection.setLogo(null); // Display "upload logo" page. Necessary attributes already set by // doDSPost() JSPManager.showJSP(request, response, "/admin/upload-logo.jsp"); } else if(button.equals("submit_delete_logo")) { // Simply delete logo collection.setLogo(null); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } else if(button.startsWith("submit_wf_create_")) { int step = Integer.parseInt(button.substring(17)); // Create new group Group newGroup = Group.create(context); newGroup.setName("COLLECTION_" + collection.getID() + "_WFSTEP_" + step); newGroup.update(); collection.setWorkflowGroup(step, newGroup); collection.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/groups?group=" + newGroup.getID())); } else if(button.startsWith("submit_wf_edit_")) { int step = Integer.parseInt(button.substring(15)); // Edit workflow group Group g = collection.getWorkflowGroup(step); response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/groups?group=" + g.getID())); } else if(button.startsWith("submit_wf_delete_")) { // Delete workflow group int step = Integer.parseInt(button.substring(17)); Group g = collection.getWorkflowGroup(step); collection.setWorkflowGroup(step, null); // Have to update to avoid ref. integrity error collection.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } else if(button.equals("submit_create_template")) { // Create a template item collection.createTemplateItem(); // Forward to edit page for new template item Item i = collection.getTemplateItem(); response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/edit_item?item_id=" + i.getID())); } else if(button.equals("submit_edit_template")) { // Forward to edit page for template item Item i = collection.getTemplateItem(); response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/edit_item?item_id=" + i.getID())); } else if(button.equals("submit_delete_template")) { collection.removeTemplateItem(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } else { // Plain old "create/update" button pressed - go back to main page showControls(context, request, response); } // Commit changes to DB collection.update(); context.complete(); }
private void processConfirmEditCollection(Context context, HttpServletRequest request, HttpServletResponse response, Community community, Collection collection) throws ServletException, IOException, SQLException, AuthorizeException { if (request.getParameter("create").equals("true")) { // We need to create a new community collection = community.createCollection(); request.setAttribute("collection", collection); } // Update the basic metadata collection.setMetadata("name", request.getParameter("name")); collection.setMetadata("short_description", request.getParameter("short_description")); String intro = request.getParameter("introductory_text"); if (intro.equals("")) { intro = null; } String copy = request.getParameter("copyright_text"); if (copy.equals("")) { copy = null; } String side = request.getParameter("side_bar_text"); if (side.equals("")) { side = null; } String license = request.getParameter("license"); if (license.equals("")) { license = null; } String provenance = request.getParameter("provenance_description"); if (provenance.equals("")) { provenance = null; } collection.setMetadata("introductory_text", intro); collection.setMetadata("copyright_text", copy); collection.setMetadata("side_bar_text", side); collection.setMetadata("license", license); collection.setMetadata("provenance_description", provenance); // Which button was pressed? String button = UIUtil.getSubmitButton(request, "submit"); if (button.equals("submit_set_logo")) { // Change the logo - delete any that might be there first collection.setLogo(null); // Display "upload logo" page. Necessary attributes already set by // doDSPost() JSPManager.showJSP(request, response, "/admin/upload-logo.jsp"); } else if(button.equals("submit_delete_logo")) { // Simply delete logo collection.setLogo(null); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } else if(button.startsWith("submit_wf_create_")) { int step = Integer.parseInt(button.substring(17)); // Create new group Group newGroup = Group.create(context); newGroup.setName("COLLECTION_" + collection.getID() + "_WFSTEP_" + step); newGroup.update(); collection.setWorkflowGroup(step, newGroup); collection.update(); // Forward to group edit page response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/groups?group=" + newGroup.getID())); } else if(button.startsWith("submit_wf_edit_")) { int step = Integer.parseInt(button.substring(15)); // Edit workflow group Group g = collection.getWorkflowGroup(step); response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/groups?group=" + g.getID())); } else if(button.startsWith("submit_wf_delete_")) { // Delete workflow group int step = Integer.parseInt(button.substring(17)); Group g = collection.getWorkflowGroup(step); collection.setWorkflowGroup(step, null); // Have to update to avoid ref. integrity error collection.update(); g.delete(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } else if(button.equals("submit_create_template")) { // Create a template item collection.createTemplateItem(); // Forward to edit page for new template item Item i = collection.getTemplateItem(); response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/edit_item?item_id=" + i.getID())); } else if(button.equals("submit_edit_template")) { // Forward to edit page for template item Item i = collection.getTemplateItem(); response.sendRedirect(response.encodeRedirectURL( request.getContextPath() + "/admin/edit_item?item_id=" + i.getID())); } else if(button.equals("submit_delete_template")) { collection.removeTemplateItem(); // Show edit page again - attributes set in doDSPost() JSPManager.showJSP(request, response, "/admin/edit-collection.jsp"); } else { // Plain old "create/update" button pressed - go back to main page showControls(context, request, response); } // Commit changes to DB collection.update(); context.complete(); }
diff --git a/ananya-kilkari-functional-tests/src/test/java/org/motechproject/ananya/kilkari/functional/test/CustomerNotAroundThePhoneFunctionalTest.java b/ananya-kilkari-functional-tests/src/test/java/org/motechproject/ananya/kilkari/functional/test/CustomerNotAroundThePhoneFunctionalTest.java index 2f8b9a15..f52057fa 100644 --- a/ananya-kilkari-functional-tests/src/test/java/org/motechproject/ananya/kilkari/functional/test/CustomerNotAroundThePhoneFunctionalTest.java +++ b/ananya-kilkari-functional-tests/src/test/java/org/motechproject/ananya/kilkari/functional/test/CustomerNotAroundThePhoneFunctionalTest.java @@ -1,51 +1,50 @@ package org.motechproject.ananya.kilkari.functional.test; import org.joda.time.DateTime; import org.junit.Test; import org.motechproject.ananya.kilkari.functional.test.builder.SubscriptionDataBuilder; import org.motechproject.ananya.kilkari.functional.test.domain.SubscriptionData; import org.motechproject.ananya.kilkari.functional.test.utils.BaseFunctionalTest; import org.motechproject.ananya.kilkari.subscription.repository.KilkariPropertiesData; import org.springframework.beans.factory.annotation.Autowired; import static org.motechproject.ananya.kilkari.functional.test.Actions.*; public class CustomerNotAroundThePhoneFunctionalTest extends BaseFunctionalTest { @Autowired private KilkariPropertiesData kilkariProperties; @Test public void shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade() throws Exception { System.out.println("Now running shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade"); int scheduleDeltaDays = kilkariProperties.getCampaignScheduleDeltaDays(); int deltaMinutes = kilkariProperties.getCampaignScheduleDeltaMinutes(); DateTime futureDateForFirstCampaignAlert = DateTime.now().plusDays(scheduleDeltaDays).plusMinutes(deltaMinutes + 1); DateTime futureDateForFirstDayFirstSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); DateTime futureDateForFirstDaySecondSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(18).withMinuteOfHour(30); DateTime futureDateForSecondDayFirstSlot = futureDateForFirstDaySecondSlot.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); - DateTime futureDateForSecondDaySecondSlot = futureDateForSecondDayFirstSlot.withHourOfDay(18).withMinuteOfHour(30); String week1 = "WEEK1"; SubscriptionData subscriptionData = new SubscriptionDataBuilder().withDefaults().build(); when(callCenter).subscribes(subscriptionData); and(subscriptionManager).activates(subscriptionData); and(time).isMovedToFuture(futureDateForFirstCampaignAlert); then(user).messageIsReady(subscriptionData, week1); and(time).isMovedToFuture(futureDateForFirstDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); when(obd).reportsUserDidNotPickUpTheCall(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForFirstDaySecondSlot); then(user).messageWasDeliveredDuringSecondSlot(subscriptionData, week1); when(obd).doesNotCallTheUser(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); - and(time).isMovedToFuture(futureDateForSecondDaySecondSlot); + and(time).isMovedToFuture(futureDateForSecondDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); } }
false
true
public void shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade() throws Exception { System.out.println("Now running shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade"); int scheduleDeltaDays = kilkariProperties.getCampaignScheduleDeltaDays(); int deltaMinutes = kilkariProperties.getCampaignScheduleDeltaMinutes(); DateTime futureDateForFirstCampaignAlert = DateTime.now().plusDays(scheduleDeltaDays).plusMinutes(deltaMinutes + 1); DateTime futureDateForFirstDayFirstSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); DateTime futureDateForFirstDaySecondSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(18).withMinuteOfHour(30); DateTime futureDateForSecondDayFirstSlot = futureDateForFirstDaySecondSlot.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); DateTime futureDateForSecondDaySecondSlot = futureDateForSecondDayFirstSlot.withHourOfDay(18).withMinuteOfHour(30); String week1 = "WEEK1"; SubscriptionData subscriptionData = new SubscriptionDataBuilder().withDefaults().build(); when(callCenter).subscribes(subscriptionData); and(subscriptionManager).activates(subscriptionData); and(time).isMovedToFuture(futureDateForFirstCampaignAlert); then(user).messageIsReady(subscriptionData, week1); and(time).isMovedToFuture(futureDateForFirstDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); when(obd).reportsUserDidNotPickUpTheCall(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForFirstDaySecondSlot); then(user).messageWasDeliveredDuringSecondSlot(subscriptionData, week1); when(obd).doesNotCallTheUser(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForSecondDaySecondSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); }
public void shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade() throws Exception { System.out.println("Now running shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade"); int scheduleDeltaDays = kilkariProperties.getCampaignScheduleDeltaDays(); int deltaMinutes = kilkariProperties.getCampaignScheduleDeltaMinutes(); DateTime futureDateForFirstCampaignAlert = DateTime.now().plusDays(scheduleDeltaDays).plusMinutes(deltaMinutes + 1); DateTime futureDateForFirstDayFirstSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); DateTime futureDateForFirstDaySecondSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(18).withMinuteOfHour(30); DateTime futureDateForSecondDayFirstSlot = futureDateForFirstDaySecondSlot.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); String week1 = "WEEK1"; SubscriptionData subscriptionData = new SubscriptionDataBuilder().withDefaults().build(); when(callCenter).subscribes(subscriptionData); and(subscriptionManager).activates(subscriptionData); and(time).isMovedToFuture(futureDateForFirstCampaignAlert); then(user).messageIsReady(subscriptionData, week1); and(time).isMovedToFuture(futureDateForFirstDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); when(obd).reportsUserDidNotPickUpTheCall(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForFirstDaySecondSlot); then(user).messageWasDeliveredDuringSecondSlot(subscriptionData, week1); when(obd).doesNotCallTheUser(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForSecondDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); }
diff --git a/software/database/src/main/java/brooklyn/entity/database/mysql/MySqlSshDriver.java b/software/database/src/main/java/brooklyn/entity/database/mysql/MySqlSshDriver.java index b7c70f585..4766417d9 100644 --- a/software/database/src/main/java/brooklyn/entity/database/mysql/MySqlSshDriver.java +++ b/software/database/src/main/java/brooklyn/entity/database/mysql/MySqlSshDriver.java @@ -1,211 +1,212 @@ package brooklyn.entity.database.mysql; import static brooklyn.entity.basic.lifecycle.CommonCommands.downloadUrlAs; import static brooklyn.entity.basic.lifecycle.CommonCommands.installPackage; import static brooklyn.entity.basic.lifecycle.CommonCommands.ok; import static brooklyn.util.GroovyJavaMethods.elvis; import static brooklyn.util.GroovyJavaMethods.truth; import static java.lang.String.format; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver; import brooklyn.entity.basic.lifecycle.CommonCommands; import brooklyn.entity.drivers.downloads.DownloadResolver; import brooklyn.location.OsDetails; import brooklyn.location.basic.BasicOsDetails.OsVersions; import brooklyn.location.basic.SshMachineLocation; import brooklyn.util.ComparableVersion; import brooklyn.util.MutableMap; import brooklyn.util.ResourceUtils; import brooklyn.util.text.Strings; import com.google.common.collect.ImmutableMap; /** * The SSH implementation of the {@link MySqlDriver}. */ public class MySqlSshDriver extends AbstractSoftwareProcessSshDriver implements MySqlDriver { public static final Logger log = LoggerFactory.getLogger(MySqlSshDriver.class); private String _expandedInstallDir; public MySqlSshDriver(MySqlNodeImpl entity, SshMachineLocation machine) { super(entity, machine); } public String getOsTag() { // e.g. "osx10.6-x86_64"; see http://www.mysql.com/downloads/mysql/#downloads OsDetails os = getLocation().getOsDetails(); if (os == null) return "linux2.6-i686"; if (os.isMac()) { String osp1 = os.getVersion()==null ? "osx10.5" //lowest common denominator : new ComparableVersion(os.getVersion()).isGreaterThanOrEqualTo(OsVersions.MAC_10_6) ? "osx10.6" : new ComparableVersion(os.getVersion()).isGreaterThanOrEqualTo(OsVersions.MAC_10_5) ? "osx10.5" : "osx10.5"; //lowest common denominator String osp2 = os.is64bit() ? "x86_64" : "x86"; return osp1+"-"+osp2; } //assume generic linux String osp1 = "linux2.6"; String osp2 = os.is64bit() ? "x86_64" : "i686"; return osp1+"-"+osp2; } public String getMirrorUrl() { return entity.getConfig(MySqlNode.MIRROR_URL); } public String getBasedir() { return getExpandedInstallDir(); } public String getDatadir() { String result = entity.getConfig(MySqlNode.DATA_DIR); return (result == null) ? "." : result; } public String getInstallFilename() { return String.format("mysql-%s-%s.tar.gz", getVersion(), getOsTag()); } private String getExpandedInstallDir() { if (_expandedInstallDir == null) throw new IllegalStateException("expandedInstallDir is null; most likely install was not called"); return _expandedInstallDir; } @Override public void install() { //mysql-${version}-${driver.osTag}.tar.gz DownloadResolver resolver = entity.getManagementContext().getEntityDownloadsRegistry().resolve( this, ImmutableMap.of("filename", getInstallFilename())); List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); _expandedInstallDir = getInstallDir()+"/"+resolver.getUnpackedDirectorName(format("mysql-%s-%s", getVersion(), getOsTag())); List<String> commands = new LinkedList<String>(); commands.add(CommonCommands.INSTALL_TAR); commands.add("echo installing extra packages"); - commands.add(installPackage(ImmutableMap.of("yum", "libgcc_s.so.1 libaio.so.1 libncurses.so.5", "apt", "libaio1 libaio-dev"), null)); + commands.add(installPackage(ImmutableMap.of("yum", "libgcc_s.so.1"), null)); + commands.add(installPackage(ImmutableMap.of("yum", "libaio.so.1 libncurses.so.5", "apt", "libaio1 libaio-dev"), null)); // these deps are needed on some OS versions but others don't need them so ignore failures (ok(...)) commands.add(ok(installPackage(ImmutableMap.of("yum", "libaio", "apt", "ia32-libs"), null))); commands.add("echo finished installing extra packages"); commands.addAll(downloadUrlAs(urls, saveAs)); commands.add(format("tar xfvz %s", saveAs)); newScript(INSTALLING). body.append(commands).execute(); } public MySqlNodeImpl getEntity() { return (MySqlNodeImpl) super.getEntity(); } public int getPort() { return getEntity().getPort(); } public String getSocketUid() { return getEntity().getSocketUid(); } public String getPassword() { return getEntity().getPassword(); } @Override public void customize() { copyDatabaseCreationScript(); copyDatabaseConfigScript(); newScript(CUSTOMIZING). updateTaskAndFailOnNonZeroResultCode(). body.append( "chmod 600 mymysql.cnf", getBasedir()+"/scripts/mysql_install_db "+ "--basedir="+getBasedir()+" --datadir="+getDatadir()+" "+ "--defaults-file=mymysql.cnf", getBasedir()+"/bin/mysqld --defaults-file=mymysql.cnf --user=`whoami` &", //--user=root needed if we are root "export MYSQL_PID=$!", "sleep 20", "echo launching mysqladmin", getBasedir()+"/bin/mysqladmin --defaults-file=mymysql.cnf --password= password "+getPassword(), "sleep 20", "echo launching mysql creation script", getBasedir()+"/bin/mysql --defaults-file=mymysql.cnf < creation-script.cnf", "echo terminating mysql on customization complete", "kill $MYSQL_PID" ).execute(); } private void copyDatabaseCreationScript() { newScript(CUSTOMIZING). body.append("echo copying creation script"). execute(); //create the directory Reader creationScript; String url = entity.getConfig(MySqlNode.CREATION_SCRIPT_URL); if (!Strings.isBlank(url)) creationScript = new InputStreamReader(new ResourceUtils(entity).getResourceFromUrl(url)); else creationScript = new StringReader((String) elvis(entity.getConfig(MySqlNode.CREATION_SCRIPT_CONTENTS), "")); getMachine().copyTo(creationScript, getRunDir() + "/creation-script.cnf"); } private void copyDatabaseConfigScript() { newScript(CUSTOMIZING). body.append("echo copying config script"). execute(); //create the directory String configScriptContents = processTemplate(entity.getAttribute(MySqlNode.TEMPLATE_CONFIGURATION_URL)); Reader configContents = new StringReader(configScriptContents); getMachine().copyTo(configContents, getRunDir() + "/mymysql.cnf"); } public String getMySqlServerOptionsString() { Map<String, Object> options = entity.getConfig(MySqlNode.MYSQL_SERVER_CONF); if (!truth(options)) return ""; String result = ""; for (Map.Entry<String, Object> entry : options.entrySet()) { if("".equals(entry.getValue())){ result += ""+entry.getKey()+"\n"; }else{ result += ""+entry.getKey()+" = "+entry.getValue()+"\n"; } } return result; } @Override public void launch() { newScript(MutableMap.of("usePidFile", true), LAUNCHING). updateTaskAndFailOnNonZeroResultCode(). body.append( format("nohup %s/bin/mysqld --defaults-file=mymysql.cnf --user=`whoami` > out.log 2> err.log < /dev/null &", getBasedir()) ).execute(); } @Override public boolean isRunning() { return newScript(MutableMap.of("usePidFile", false), CHECK_RUNNING) .body.append(getStatusCmd()) .execute() == 0; } @Override public void stop() { newScript(MutableMap.of("usePidFile", true), STOPPING).execute(); } @Override public void kill() { newScript(MutableMap.of("usePidFile", true), KILLING).execute(); } @Override public String getStatusCmd() { // TODO Is this very bad, to include the password in the command being executed // (so is in `ps` listing temporarily, and in .bash_history) return format("%s/bin/mysqladmin --user=%s --password=%s --socket=/tmp/mysql.sock.%s.%s status", getExpandedInstallDir(), "root", getPassword(), getSocketUid(), getPort()); } }
true
true
public void install() { //mysql-${version}-${driver.osTag}.tar.gz DownloadResolver resolver = entity.getManagementContext().getEntityDownloadsRegistry().resolve( this, ImmutableMap.of("filename", getInstallFilename())); List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); _expandedInstallDir = getInstallDir()+"/"+resolver.getUnpackedDirectorName(format("mysql-%s-%s", getVersion(), getOsTag())); List<String> commands = new LinkedList<String>(); commands.add(CommonCommands.INSTALL_TAR); commands.add("echo installing extra packages"); commands.add(installPackage(ImmutableMap.of("yum", "libgcc_s.so.1 libaio.so.1 libncurses.so.5", "apt", "libaio1 libaio-dev"), null)); // these deps are needed on some OS versions but others don't need them so ignore failures (ok(...)) commands.add(ok(installPackage(ImmutableMap.of("yum", "libaio", "apt", "ia32-libs"), null))); commands.add("echo finished installing extra packages"); commands.addAll(downloadUrlAs(urls, saveAs)); commands.add(format("tar xfvz %s", saveAs)); newScript(INSTALLING). body.append(commands).execute(); }
public void install() { //mysql-${version}-${driver.osTag}.tar.gz DownloadResolver resolver = entity.getManagementContext().getEntityDownloadsRegistry().resolve( this, ImmutableMap.of("filename", getInstallFilename())); List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); _expandedInstallDir = getInstallDir()+"/"+resolver.getUnpackedDirectorName(format("mysql-%s-%s", getVersion(), getOsTag())); List<String> commands = new LinkedList<String>(); commands.add(CommonCommands.INSTALL_TAR); commands.add("echo installing extra packages"); commands.add(installPackage(ImmutableMap.of("yum", "libgcc_s.so.1"), null)); commands.add(installPackage(ImmutableMap.of("yum", "libaio.so.1 libncurses.so.5", "apt", "libaio1 libaio-dev"), null)); // these deps are needed on some OS versions but others don't need them so ignore failures (ok(...)) commands.add(ok(installPackage(ImmutableMap.of("yum", "libaio", "apt", "ia32-libs"), null))); commands.add("echo finished installing extra packages"); commands.addAll(downloadUrlAs(urls, saveAs)); commands.add(format("tar xfvz %s", saveAs)); newScript(INSTALLING). body.append(commands).execute(); }
diff --git a/plugins/ldapbrowser.ui/src/main/java/org/apache/directory/studio/ldapbrowser/ui/dialogs/properties/EntryPropertyPage.java b/plugins/ldapbrowser.ui/src/main/java/org/apache/directory/studio/ldapbrowser/ui/dialogs/properties/EntryPropertyPage.java index b96e1eb23..85a4ae930 100644 --- a/plugins/ldapbrowser.ui/src/main/java/org/apache/directory/studio/ldapbrowser/ui/dialogs/properties/EntryPropertyPage.java +++ b/plugins/ldapbrowser.ui/src/main/java/org/apache/directory/studio/ldapbrowser/ui/dialogs/properties/EntryPropertyPage.java @@ -1,378 +1,378 @@ /* * 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.directory.studio.ldapbrowser.ui.dialogs.properties; import org.apache.directory.shared.ldap.model.constants.SchemaConstants; import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils; import org.apache.directory.studio.connection.ui.RunnableContextRunner; import org.apache.directory.studio.ldapbrowser.core.jobs.InitializeAttributesRunnable; import org.apache.directory.studio.ldapbrowser.core.jobs.InitializeChildrenRunnable; import org.apache.directory.studio.ldapbrowser.core.model.IAttribute; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.IValue; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbenchPropertyPage; import org.eclipse.ui.dialogs.PropertyPage; /** * This page shows some info about the selected Entry. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> */ public class EntryPropertyPage extends PropertyPage implements IWorkbenchPropertyPage { /** The dn text. */ private Text dnText; /** The url text. */ private Text urlText; /** The ct text. */ private Text ctText; /** The cn text. */ private Text cnText; /** The mt text. */ private Text mtText; /** The mn text. */ private Text mnText; /** The reload cmi button. */ private Button reloadCmiButton; /** The size text. */ private Text sizeText; /** The children text. */ private Text childrenText; /** The attributes text. */ private Text attributesText; /** The values text. */ private Text valuesText; /** The include operational attributes button. */ private Button includeOperationalAttributesButton; /** The reload entry button. */ private Button reloadEntryButton; /** * Creates a new instance of EntryPropertyPage. */ public EntryPropertyPage() { super(); super.noDefaultAndApplyButton(); } /** * {@inheritDoc} */ protected Control createContents( Composite parent ) { Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 ); Composite mainGroup = BaseWidgetUtils.createColumnContainer( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ), 2, 1 ); - BaseWidgetUtils.createLabel( mainGroup, Messages.getString( "EntryPropertyPage.Dn" ), 1 ); //$NON-NLS-1$ + BaseWidgetUtils.createLabel( mainGroup, Messages.getString( "EntryPropertyPage.DN" ), 1 ); //$NON-NLS-1$ dnText = BaseWidgetUtils.createWrappedLabeledText( mainGroup, "", 1 ); //$NON-NLS-1$ GridData dnTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false ); dnTextGridData.widthHint = 300; dnText.setLayoutData( dnTextGridData ); BaseWidgetUtils.createLabel( mainGroup, Messages.getString( "EntryPropertyPage.URL" ), 1 ); //$NON-NLS-1$ urlText = BaseWidgetUtils.createWrappedLabeledText( mainGroup, "", 1 ); //$NON-NLS-1$ GridData urlTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false ); urlTextGridData.widthHint = 300; urlText.setLayoutData( urlTextGridData ); Group cmiGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ), Messages.getString( "EntryPropertyPage.CreateModifyinformation" ), 1 ); //$NON-NLS-1$ Composite cmiComposite = BaseWidgetUtils.createColumnContainer( cmiGroup, 3, 1 ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.CreateTimestamp" ), 1 ); //$NON-NLS-1$ ctText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 2 ); //$NON-NLS-1$ GridData ctTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); ctTextGridData.widthHint = 300; ctText.setLayoutData( ctTextGridData ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.CreatorsName" ), 1 ); //$NON-NLS-1$ cnText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 2 ); //$NON-NLS-1$ GridData cnTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); cnTextGridData.widthHint = 300; cnText.setLayoutData( cnTextGridData ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.ModifyTimestamp" ), 1 ); //$NON-NLS-1$ mtText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 2 ); //$NON-NLS-1$ GridData mtTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); mtTextGridData.widthHint = 300; mtText.setLayoutData( mtTextGridData ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.ModifiersName" ), 1 ); //$NON-NLS-1$ mnText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 1 ); //$NON-NLS-1$ GridData mnTextGridData = new GridData( GridData.FILL_HORIZONTAL ); mnTextGridData.widthHint = 300; mnText.setLayoutData( mnTextGridData ); reloadCmiButton = BaseWidgetUtils.createButton( cmiComposite, "", 1 ); //$NON-NLS-1$ GridData gd = new GridData(); gd.verticalAlignment = SWT.BOTTOM; gd.horizontalAlignment = SWT.RIGHT; reloadCmiButton.setLayoutData( gd ); reloadCmiButton.addSelectionListener( new SelectionListener() { public void widgetSelected( SelectionEvent e ) { reloadOperationalAttributes(); } public void widgetDefaultSelected( SelectionEvent e ) { } } ); Group sizingGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ), Messages.getString( "EntryPropertyPage.SizingInformation" ), 1 ); //$NON-NLS-1$ Composite sizingComposite = BaseWidgetUtils.createColumnContainer( sizingGroup, 3, 1 ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.EntrySize" ), 1 ); //$NON-NLS-1$ sizeText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData sizeTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); sizeTextGridData.widthHint = 300; sizeText.setLayoutData( sizeTextGridData ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.NumberOfChildren" ), 1 ); //$NON-NLS-1$ childrenText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData childrenTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); childrenTextGridData.widthHint = 300; childrenText.setLayoutData( childrenTextGridData ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.NumberOfAttributes" ), 1 ); //$NON-NLS-1$ attributesText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData attributesTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); attributesTextGridData.widthHint = 300; attributesText.setLayoutData( attributesTextGridData ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.NumberOfValues" ), 1 ); //$NON-NLS-1$ valuesText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData valuesTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); valuesTextGridData.widthHint = 300; valuesText.setLayoutData( valuesTextGridData ); includeOperationalAttributesButton = BaseWidgetUtils.createCheckbox( sizingComposite, Messages .getString( "EntryPropertyPage.IncludeoperationalAttributes" ), 2 ); //$NON-NLS-1$ includeOperationalAttributesButton.addSelectionListener( new SelectionListener() { public void widgetSelected( SelectionEvent e ) { entryUpdated( getEntry( getElement() ) ); } public void widgetDefaultSelected( SelectionEvent e ) { } } ); reloadEntryButton = BaseWidgetUtils.createButton( sizingComposite, "", 1 ); //$NON-NLS-1$ gd = new GridData(); gd.verticalAlignment = SWT.BOTTOM; gd.horizontalAlignment = SWT.RIGHT; reloadEntryButton.setLayoutData( gd ); reloadEntryButton.addSelectionListener( new SelectionListener() { public void widgetSelected( SelectionEvent e ) { reloadEntry(); } public void widgetDefaultSelected( SelectionEvent e ) { } } ); entryUpdated( getEntry( getElement() ) ); return composite; } /** * Reload operational attributes. */ private void reloadOperationalAttributes() { IEntry entry = EntryPropertyPage.getEntry( getElement() ); entry.setInitOperationalAttributes( true ); InitializeAttributesRunnable runnable = new InitializeAttributesRunnable( entry ); RunnableContextRunner.execute( runnable, null, true ); entryUpdated( entry ); } /** * Reload entry. */ private void reloadEntry() { IEntry entry = EntryPropertyPage.getEntry( getElement() ); entry.setInitOperationalAttributes( true ); InitializeChildrenRunnable runnable1 = new InitializeChildrenRunnable( false, entry ); InitializeAttributesRunnable runnable2 = new InitializeAttributesRunnable( entry ); RunnableContextRunner.execute( runnable1, null, true ); RunnableContextRunner.execute( runnable2, null, true ); entryUpdated( entry ); } /** * Gets the entry. * * @param element the element * * @return the entry */ static IEntry getEntry( Object element ) { IEntry entry = null; if ( element instanceof IAdaptable ) { entry = ( IEntry ) ( ( IAdaptable ) element ).getAdapter( IEntry.class ); } return entry; } /** * Checks if is disposed. * * @return true, if is disposed */ public boolean isDisposed() { return this.dnText.isDisposed(); } /** * Gets the non-null string value. * * @param att the attribute * * @return the non-null string value */ private String getNonNullStringValue( IAttribute att ) { String value = null; if ( att != null ) { value = att.getStringValue(); } return value != null ? value : "-"; //$NON-NLS-1$ } /** * Updates the text widgets if the entry was updated. * * @param entry the entry */ private void entryUpdated( IEntry entry ) { if ( !this.dnText.isDisposed() ) { setMessage( Messages.getString( "EntryPropertyPage.Entry" ) + entry.getDn().getName() ); //$NON-NLS-1$ dnText.setText( entry.getDn().getName() ); urlText.setText( entry.getUrl().toString() ); ctText.setText( getNonNullStringValue( entry.getAttribute( SchemaConstants.CREATE_TIMESTAMP_AT ) ) ); cnText.setText( getNonNullStringValue( entry.getAttribute( SchemaConstants.CREATORS_NAME_AT ) ) ); mtText.setText( getNonNullStringValue( entry.getAttribute( SchemaConstants.MODIFY_TIMESTAMP_AT ) ) ); mnText.setText( getNonNullStringValue( entry.getAttribute( SchemaConstants.MODIFIERS_NAME_AT ) ) ); reloadCmiButton.setText( Messages.getString( "EntryPropertyPage.Refresh" ) ); //$NON-NLS-1$ int attCount = 0; int valCount = 0; int bytes = 0; IAttribute[] allAttributes = entry.getAttributes(); if ( allAttributes != null ) { for ( int attIndex = 0; attIndex < allAttributes.length; attIndex++ ) { if ( !allAttributes[attIndex].isOperationalAttribute() || includeOperationalAttributesButton.getSelection() ) { attCount++; IValue[] allValues = allAttributes[attIndex].getValues(); for ( int valIndex = 0; valIndex < allValues.length; valIndex++ ) { if ( !allValues[valIndex].isEmpty() ) { valCount++; bytes += allValues[valIndex].getBinaryValue().length; } } } } } reloadEntryButton.setText( Messages.getString( "EntryPropertyPage.Refresh" ) ); //$NON-NLS-1$ if ( !entry.isChildrenInitialized() ) { childrenText.setText( Messages.getString( "EntryPropertyPage.NotChecked" ) ); //$NON-NLS-1$ } else { childrenText.setText( ( entry.hasMoreChildren() ? NLS.bind( Messages .getString( "EntryPropertyPage.ChildrenFetched" ), new Object[] { entry.getChildrenCount() } ) //$NON-NLS-1$ : Integer.toString( entry.getChildrenCount() ) ) ); } attributesText.setText( "" + attCount ); //$NON-NLS-1$ valuesText.setText( "" + valCount ); //$NON-NLS-1$ sizeText.setText( Utils.formatBytes( bytes ) ); } } }
true
true
protected Control createContents( Composite parent ) { Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 ); Composite mainGroup = BaseWidgetUtils.createColumnContainer( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ), 2, 1 ); BaseWidgetUtils.createLabel( mainGroup, Messages.getString( "EntryPropertyPage.Dn" ), 1 ); //$NON-NLS-1$ dnText = BaseWidgetUtils.createWrappedLabeledText( mainGroup, "", 1 ); //$NON-NLS-1$ GridData dnTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false ); dnTextGridData.widthHint = 300; dnText.setLayoutData( dnTextGridData ); BaseWidgetUtils.createLabel( mainGroup, Messages.getString( "EntryPropertyPage.URL" ), 1 ); //$NON-NLS-1$ urlText = BaseWidgetUtils.createWrappedLabeledText( mainGroup, "", 1 ); //$NON-NLS-1$ GridData urlTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false ); urlTextGridData.widthHint = 300; urlText.setLayoutData( urlTextGridData ); Group cmiGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ), Messages.getString( "EntryPropertyPage.CreateModifyinformation" ), 1 ); //$NON-NLS-1$ Composite cmiComposite = BaseWidgetUtils.createColumnContainer( cmiGroup, 3, 1 ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.CreateTimestamp" ), 1 ); //$NON-NLS-1$ ctText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 2 ); //$NON-NLS-1$ GridData ctTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); ctTextGridData.widthHint = 300; ctText.setLayoutData( ctTextGridData ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.CreatorsName" ), 1 ); //$NON-NLS-1$ cnText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 2 ); //$NON-NLS-1$ GridData cnTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); cnTextGridData.widthHint = 300; cnText.setLayoutData( cnTextGridData ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.ModifyTimestamp" ), 1 ); //$NON-NLS-1$ mtText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 2 ); //$NON-NLS-1$ GridData mtTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); mtTextGridData.widthHint = 300; mtText.setLayoutData( mtTextGridData ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.ModifiersName" ), 1 ); //$NON-NLS-1$ mnText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 1 ); //$NON-NLS-1$ GridData mnTextGridData = new GridData( GridData.FILL_HORIZONTAL ); mnTextGridData.widthHint = 300; mnText.setLayoutData( mnTextGridData ); reloadCmiButton = BaseWidgetUtils.createButton( cmiComposite, "", 1 ); //$NON-NLS-1$ GridData gd = new GridData(); gd.verticalAlignment = SWT.BOTTOM; gd.horizontalAlignment = SWT.RIGHT; reloadCmiButton.setLayoutData( gd ); reloadCmiButton.addSelectionListener( new SelectionListener() { public void widgetSelected( SelectionEvent e ) { reloadOperationalAttributes(); } public void widgetDefaultSelected( SelectionEvent e ) { } } ); Group sizingGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ), Messages.getString( "EntryPropertyPage.SizingInformation" ), 1 ); //$NON-NLS-1$ Composite sizingComposite = BaseWidgetUtils.createColumnContainer( sizingGroup, 3, 1 ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.EntrySize" ), 1 ); //$NON-NLS-1$ sizeText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData sizeTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); sizeTextGridData.widthHint = 300; sizeText.setLayoutData( sizeTextGridData ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.NumberOfChildren" ), 1 ); //$NON-NLS-1$ childrenText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData childrenTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); childrenTextGridData.widthHint = 300; childrenText.setLayoutData( childrenTextGridData ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.NumberOfAttributes" ), 1 ); //$NON-NLS-1$ attributesText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData attributesTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); attributesTextGridData.widthHint = 300; attributesText.setLayoutData( attributesTextGridData ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.NumberOfValues" ), 1 ); //$NON-NLS-1$ valuesText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData valuesTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); valuesTextGridData.widthHint = 300; valuesText.setLayoutData( valuesTextGridData ); includeOperationalAttributesButton = BaseWidgetUtils.createCheckbox( sizingComposite, Messages .getString( "EntryPropertyPage.IncludeoperationalAttributes" ), 2 ); //$NON-NLS-1$ includeOperationalAttributesButton.addSelectionListener( new SelectionListener() { public void widgetSelected( SelectionEvent e ) { entryUpdated( getEntry( getElement() ) ); } public void widgetDefaultSelected( SelectionEvent e ) { } } ); reloadEntryButton = BaseWidgetUtils.createButton( sizingComposite, "", 1 ); //$NON-NLS-1$ gd = new GridData(); gd.verticalAlignment = SWT.BOTTOM; gd.horizontalAlignment = SWT.RIGHT; reloadEntryButton.setLayoutData( gd ); reloadEntryButton.addSelectionListener( new SelectionListener() { public void widgetSelected( SelectionEvent e ) { reloadEntry(); } public void widgetDefaultSelected( SelectionEvent e ) { } } ); entryUpdated( getEntry( getElement() ) ); return composite; }
protected Control createContents( Composite parent ) { Composite composite = BaseWidgetUtils.createColumnContainer( parent, 1, 1 ); Composite mainGroup = BaseWidgetUtils.createColumnContainer( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ), 2, 1 ); BaseWidgetUtils.createLabel( mainGroup, Messages.getString( "EntryPropertyPage.DN" ), 1 ); //$NON-NLS-1$ dnText = BaseWidgetUtils.createWrappedLabeledText( mainGroup, "", 1 ); //$NON-NLS-1$ GridData dnTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false ); dnTextGridData.widthHint = 300; dnText.setLayoutData( dnTextGridData ); BaseWidgetUtils.createLabel( mainGroup, Messages.getString( "EntryPropertyPage.URL" ), 1 ); //$NON-NLS-1$ urlText = BaseWidgetUtils.createWrappedLabeledText( mainGroup, "", 1 ); //$NON-NLS-1$ GridData urlTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false ); urlTextGridData.widthHint = 300; urlText.setLayoutData( urlTextGridData ); Group cmiGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ), Messages.getString( "EntryPropertyPage.CreateModifyinformation" ), 1 ); //$NON-NLS-1$ Composite cmiComposite = BaseWidgetUtils.createColumnContainer( cmiGroup, 3, 1 ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.CreateTimestamp" ), 1 ); //$NON-NLS-1$ ctText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 2 ); //$NON-NLS-1$ GridData ctTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); ctTextGridData.widthHint = 300; ctText.setLayoutData( ctTextGridData ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.CreatorsName" ), 1 ); //$NON-NLS-1$ cnText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 2 ); //$NON-NLS-1$ GridData cnTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); cnTextGridData.widthHint = 300; cnText.setLayoutData( cnTextGridData ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.ModifyTimestamp" ), 1 ); //$NON-NLS-1$ mtText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 2 ); //$NON-NLS-1$ GridData mtTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); mtTextGridData.widthHint = 300; mtText.setLayoutData( mtTextGridData ); BaseWidgetUtils.createLabel( cmiComposite, Messages.getString( "EntryPropertyPage.ModifiersName" ), 1 ); //$NON-NLS-1$ mnText = BaseWidgetUtils.createLabeledText( cmiComposite, "", 1 ); //$NON-NLS-1$ GridData mnTextGridData = new GridData( GridData.FILL_HORIZONTAL ); mnTextGridData.widthHint = 300; mnText.setLayoutData( mnTextGridData ); reloadCmiButton = BaseWidgetUtils.createButton( cmiComposite, "", 1 ); //$NON-NLS-1$ GridData gd = new GridData(); gd.verticalAlignment = SWT.BOTTOM; gd.horizontalAlignment = SWT.RIGHT; reloadCmiButton.setLayoutData( gd ); reloadCmiButton.addSelectionListener( new SelectionListener() { public void widgetSelected( SelectionEvent e ) { reloadOperationalAttributes(); } public void widgetDefaultSelected( SelectionEvent e ) { } } ); Group sizingGroup = BaseWidgetUtils.createGroup( BaseWidgetUtils.createColumnContainer( composite, 1, 1 ), Messages.getString( "EntryPropertyPage.SizingInformation" ), 1 ); //$NON-NLS-1$ Composite sizingComposite = BaseWidgetUtils.createColumnContainer( sizingGroup, 3, 1 ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.EntrySize" ), 1 ); //$NON-NLS-1$ sizeText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData sizeTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); sizeTextGridData.widthHint = 300; sizeText.setLayoutData( sizeTextGridData ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.NumberOfChildren" ), 1 ); //$NON-NLS-1$ childrenText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData childrenTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); childrenTextGridData.widthHint = 300; childrenText.setLayoutData( childrenTextGridData ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.NumberOfAttributes" ), 1 ); //$NON-NLS-1$ attributesText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData attributesTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); attributesTextGridData.widthHint = 300; attributesText.setLayoutData( attributesTextGridData ); BaseWidgetUtils.createLabel( sizingComposite, Messages.getString( "EntryPropertyPage.NumberOfValues" ), 1 ); //$NON-NLS-1$ valuesText = BaseWidgetUtils.createLabeledText( sizingComposite, "", 2 ); //$NON-NLS-1$ GridData valuesTextGridData = new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ); valuesTextGridData.widthHint = 300; valuesText.setLayoutData( valuesTextGridData ); includeOperationalAttributesButton = BaseWidgetUtils.createCheckbox( sizingComposite, Messages .getString( "EntryPropertyPage.IncludeoperationalAttributes" ), 2 ); //$NON-NLS-1$ includeOperationalAttributesButton.addSelectionListener( new SelectionListener() { public void widgetSelected( SelectionEvent e ) { entryUpdated( getEntry( getElement() ) ); } public void widgetDefaultSelected( SelectionEvent e ) { } } ); reloadEntryButton = BaseWidgetUtils.createButton( sizingComposite, "", 1 ); //$NON-NLS-1$ gd = new GridData(); gd.verticalAlignment = SWT.BOTTOM; gd.horizontalAlignment = SWT.RIGHT; reloadEntryButton.setLayoutData( gd ); reloadEntryButton.addSelectionListener( new SelectionListener() { public void widgetSelected( SelectionEvent e ) { reloadEntry(); } public void widgetDefaultSelected( SelectionEvent e ) { } } ); entryUpdated( getEntry( getElement() ) ); return composite; }
diff --git a/src/test/java/org/vanq/tests/HeaderTest.java b/src/test/java/org/vanq/tests/HeaderTest.java index 792dc11..08ae5ed 100644 --- a/src/test/java/org/vanq/tests/HeaderTest.java +++ b/src/test/java/org/vanq/tests/HeaderTest.java @@ -1,15 +1,15 @@ package org.vanq.tests; import org.testng.Assert; import org.testng.annotations.Test; import org.vanq.pages.Home; public class HeaderTest extends BaseTest { @Test(groups = {"functional"}) public void vanqLogoDisplayedOnHomePageTest() { Home home = new Home(driver); - Assert.assertFalse(home.isVanqLogoDisplayed()); + Assert.assertTrue(home.isVanqLogoDisplayed()); } }
true
true
public void vanqLogoDisplayedOnHomePageTest() { Home home = new Home(driver); Assert.assertFalse(home.isVanqLogoDisplayed()); }
public void vanqLogoDisplayedOnHomePageTest() { Home home = new Home(driver); Assert.assertTrue(home.isVanqLogoDisplayed()); }
diff --git a/aejb-subsystem/src/main/java/org/nju/artemis/aejb/component/interceptors/TransactionSecurityInterceptor.java b/aejb-subsystem/src/main/java/org/nju/artemis/aejb/component/interceptors/TransactionSecurityInterceptor.java index 6a80dbc..f1e723e 100644 --- a/aejb-subsystem/src/main/java/org/nju/artemis/aejb/component/interceptors/TransactionSecurityInterceptor.java +++ b/aejb-subsystem/src/main/java/org/nju/artemis/aejb/component/interceptors/TransactionSecurityInterceptor.java @@ -1,59 +1,59 @@ package org.nju.artemis.aejb.component.interceptors; import org.jboss.invocation.Interceptor; import org.jboss.invocation.InterceptorContext; import org.jboss.logging.Logger; import org.nju.artemis.aejb.component.AcContainer; import org.nju.artemis.aejb.deployment.processors.TransactionManager; import org.nju.artemis.aejb.evolution.DuService; import org.nju.artemis.aejb.evolution.protocols.Protocol; /** * This interceptor checks transaction security using specified protocol.<p>Instance level * * @author <a href="mailto:[email protected]">Jason</a> */ public class TransactionSecurityInterceptor implements Interceptor { Logger log = Logger.getLogger(TransactionSecurityInterceptor.class); private final AcContainer container; public TransactionSecurityInterceptor(AcContainer container) { this.container = container; } @Override public Object processInvocation(InterceptorContext context) throws Exception { log.debug("TransactionSecurityInterceptor: start process invocation"); String param0 = (String) context.getParameters()[0]; String[] splits = param0.split("/"); if(splits.length != 2) { - context.proceed(); + return context.proceed(); } final String transactionName = splits[0]; final String objectId = splits[1]; final String targetName = (String) context.getContextData().get("aejbName"); final String protocol = container.getEvolutionStatistics().getProtocolByBeanName(targetName); log.debug("transactionName = " + transactionName + ",objectId = " + objectId + ",protocol = " + protocol); if(protocol == null || isValidProtocolName(protocol) == false) return context.proceed(); boolean ts = checkTransactionSecurity(targetName, objectId, container.getTransactionManager(transactionName), protocol); log.debug("checkTransactionSecurity = " + ts); context.putPrivateData(Boolean.class, ts); log.debug("TransactionSecurityInterceptor: stop process invocation"); return context.proceed(); } private boolean checkTransactionSecurity(String targetName, String objectId, TransactionManager transactionManager, String protocolName) { Protocol protocol = DuService.getProtocol(protocolName); if(protocol != null) { return protocol.checkTransactionSecurity(targetName, objectId, transactionManager); } return false; } // more protocol names private boolean isValidProtocolName(String protocol) { return protocol.equals("tranquility") || protocol.equals("quiescence"); } }
true
true
public Object processInvocation(InterceptorContext context) throws Exception { log.debug("TransactionSecurityInterceptor: start process invocation"); String param0 = (String) context.getParameters()[0]; String[] splits = param0.split("/"); if(splits.length != 2) { context.proceed(); } final String transactionName = splits[0]; final String objectId = splits[1]; final String targetName = (String) context.getContextData().get("aejbName"); final String protocol = container.getEvolutionStatistics().getProtocolByBeanName(targetName); log.debug("transactionName = " + transactionName + ",objectId = " + objectId + ",protocol = " + protocol); if(protocol == null || isValidProtocolName(protocol) == false) return context.proceed(); boolean ts = checkTransactionSecurity(targetName, objectId, container.getTransactionManager(transactionName), protocol); log.debug("checkTransactionSecurity = " + ts); context.putPrivateData(Boolean.class, ts); log.debug("TransactionSecurityInterceptor: stop process invocation"); return context.proceed(); }
public Object processInvocation(InterceptorContext context) throws Exception { log.debug("TransactionSecurityInterceptor: start process invocation"); String param0 = (String) context.getParameters()[0]; String[] splits = param0.split("/"); if(splits.length != 2) { return context.proceed(); } final String transactionName = splits[0]; final String objectId = splits[1]; final String targetName = (String) context.getContextData().get("aejbName"); final String protocol = container.getEvolutionStatistics().getProtocolByBeanName(targetName); log.debug("transactionName = " + transactionName + ",objectId = " + objectId + ",protocol = " + protocol); if(protocol == null || isValidProtocolName(protocol) == false) return context.proceed(); boolean ts = checkTransactionSecurity(targetName, objectId, container.getTransactionManager(transactionName), protocol); log.debug("checkTransactionSecurity = " + ts); context.putPrivateData(Boolean.class, ts); log.debug("TransactionSecurityInterceptor: stop process invocation"); return context.proceed(); }
diff --git a/tycho/net.bpelunit.toolsupport/src/net/bpelunit/toolsupport/editors/sections/TestCaseAndTrackSection.java b/tycho/net.bpelunit.toolsupport/src/net/bpelunit/toolsupport/editors/sections/TestCaseAndTrackSection.java index 806a92f6..b2dea90b 100644 --- a/tycho/net.bpelunit.toolsupport/src/net/bpelunit/toolsupport/editors/sections/TestCaseAndTrackSection.java +++ b/tycho/net.bpelunit.toolsupport/src/net/bpelunit/toolsupport/editors/sections/TestCaseAndTrackSection.java @@ -1,683 +1,683 @@ /** * This file belongs to the BPELUnit utility and Eclipse plugin set. See enclosed * license file for more information. * */ package net.bpelunit.toolsupport.editors.sections; import java.util.ArrayList; import java.util.List; import net.bpelunit.framework.client.eclipse.dialog.FieldBasedInputDialog; import net.bpelunit.framework.client.eclipse.dialog.field.CheckBoxField; import net.bpelunit.framework.client.eclipse.dialog.field.ComboField; import net.bpelunit.framework.client.eclipse.dialog.field.TextField; import net.bpelunit.framework.client.eclipse.dialog.validate.NotEmptyValidator; import net.bpelunit.framework.client.eclipse.dialog.validate.NullValidator; import net.bpelunit.framework.client.eclipse.launch.BPELLaunchShortCut; import net.bpelunit.framework.control.util.ActivityUtil; import net.bpelunit.framework.control.util.BPELUnitConstants; import net.bpelunit.framework.xml.suite.XMLHumanPartnerDeploymentInformation; import net.bpelunit.framework.xml.suite.XMLHumanPartnerTrack; import net.bpelunit.framework.xml.suite.XMLPartnerDeploymentInformation; import net.bpelunit.framework.xml.suite.XMLPartnerTrack; import net.bpelunit.framework.xml.suite.XMLTestCase; import net.bpelunit.framework.xml.suite.XMLTestCasesSection; import net.bpelunit.framework.xml.suite.XMLTestSuite; import net.bpelunit.framework.xml.suite.XMLTrack; import net.bpelunit.toolsupport.ToolSupportActivator; import net.bpelunit.toolsupport.editors.TestSuitePage; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlObject; import org.eclipse.core.resources.IFile; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.Window; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.w3c.dom.Node; /** * The TestCaseAndTrack section offers a tree view of test cases and their * associated partner tracks, allowing the user to add, edit, remove, and move * test cases and partner tracks. * * @version $Id: TestCaseAndTrackSection.java 81 2007-06-03 10:07:37Z asalnikow * $ * @author Philip Mayer * */ public class TestCaseAndTrackSection extends TreeSection { private XMLTestSuite testSuite; private class TestCaseLabelProvider implements ILabelProvider { public Image getImage(Object element) { return ToolSupportActivator.getImage(ToolSupportActivator.IMAGE_TESTCASE); } public String getText(Object element) { if (element instanceof XMLTestCase) return ((XMLTestCase) element).getName(); else if (element instanceof XMLPartnerTrack) return ((XMLPartnerTrack) element).getName(); else if (element instanceof XMLHumanPartnerTrack) { return ((XMLHumanPartnerTrack) element).getName(); } else return BPELUnitConstants.CLIENT_NAME; } public void addListener(ILabelProviderListener listener) { // noop } public void dispose() { // noop } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { // noop } } private class TestCaseContentProvider implements ITreeContentProvider { private final Object[] EMPTY_LIST = new Object[0]; private XMLTestCasesSection fSection; public Object[] getElements(Object inputElement) { if (inputElement instanceof XMLTestCasesSection) { XMLTestCasesSection element = (XMLTestCasesSection) inputElement; return element.getTestCaseList().toArray(); } else return EMPTY_LIST; } public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput instanceof XMLTestCasesSection) fSection = (XMLTestCasesSection) newInput; } public Object[] getChildren(Object parentElement) { if (parentElement instanceof XMLTestCase) { XMLTestCase testCase = (XMLTestCase) parentElement; List<Object> tracks = new ArrayList<Object>(); tracks.addAll(testCase.getPartnerTrackList()); tracks.addAll(testCase.getHumanPartnerTrackList()); if (testCase.getClientTrack() != null) tracks.add(testCase.getClientTrack()); return tracks.toArray(); } else return EMPTY_LIST; } public Object getParent(Object element) { if (element instanceof XMLTrack) { XMLTrack track = (XMLTrack) element; List<XMLTestCase> testCaseList = fSection.getTestCaseList(); for (XMLTestCase case1 : testCaseList) { List<XMLPartnerTrack> partnerTrackList = case1.getPartnerTrackList(); for (XMLPartnerTrack track2 : partnerTrackList) { if (track2.equals(track)) return case1; } if (element.equals(case1.getClientTrack())) return case1; } } if (element instanceof XMLHumanPartnerTrack) { XMLHumanPartnerTrack track = (XMLHumanPartnerTrack) element; List<XMLTestCase> testCaseList = fSection.getTestCaseList(); for (XMLTestCase case1 : testCaseList) { List<XMLHumanPartnerTrack> partnerTrackList = case1.getHumanPartnerTrackList(); for (XMLHumanPartnerTrack track2 : partnerTrackList) { if (track2.equals(track)) return case1; } } } return null; } public boolean hasChildren(Object element) { if (element instanceof XMLTestCase) { XMLTestCase testCase = (XMLTestCase) element; return testCase.getPartnerTrackList().size() > 0 || testCase.getHumanPartnerTrackList().size() > 0 || testCase.getClientTrack() != null; } else return false; } } public TestCaseAndTrackSection(Composite parent, TestSuitePage page, FormToolkit toolkit) { super(parent, toolkit, page, true, true, null); testSuite = page.getSuiteEditor().getTestSuite(); init(); } private void init() { getViewer().setLabelProvider(new TestCaseLabelProvider()); getViewer().setContentProvider(new TestCaseContentProvider()); } @Override protected String getDescription() { return "Manage test cases and partner tracks."; } @Override protected String getName() { return "Test Cases and Tracks"; } @Override public void refresh() { setViewerInput(getTestCasesXMLPart()); getTreeViewer().expandAll(); super.refresh(); } private XMLTestCasesSection getTestCasesXMLPart() { XMLTestSuite model = getEditor().getTestSuite(); return model.getTestCases(); } @Override protected void addPressed() { addTestCase(); } protected void addPartnerTrack(XMLTestCase to) { String name = editPartnerTrack("Add a new partner track", null); if (name != null && name.length() > 0) { XMLPartnerTrack track = to.addNewPartnerTrack(); track.setName(name); adjust(); } } protected void addHumanPartnerTrack(XMLTestCase to) { String name = editHumanPartnerTrack("Add a new WS-HT Track", null); if (name != null && name.length() > 0) { XMLHumanPartnerTrack track = to.addNewHumanPartnerTrack(); track.setName(name); adjust(); } } protected void addClientTrack(XMLTestCase to) { to.addNewClientTrack(); adjust(); } private void addTestCase() { String[] results = editTestCase("Add a new test case", null, null, false, false); if (results != null) { XMLTestCase testCase = getTestCasesXMLPart().addNewTestCase(); // initialize the test case testCase.setName(results[0]); testCase.setBasedOn(results[1]); testCase.setAbstract(Boolean.parseBoolean(results[2])); testCase.setVary(Boolean.parseBoolean(results[3])); testCase.addNewClientTrack(); List<XMLPartnerDeploymentInformation> allDeployers = getAllDeployers(); for (XMLPartnerDeploymentInformation information : allDeployers) { XMLPartnerTrack track = testCase.addNewPartnerTrack(); track.setName(information.getName()); } adjust(); getTreeViewer().expandToLevel(testCase, AbstractTreeViewer.ALL_LEVELS); getTreeViewer().setSelection(new StructuredSelection(testCase)); } } private List<XMLPartnerDeploymentInformation> getAllDeployers() { XMLTestSuite model = getEditor().getTestSuite(); List<XMLPartnerDeploymentInformation> partnerList = model.getDeployment().getPartnerList(); return partnerList; } @Override protected void editPressed() { Object current = getViewerSelection(); if (current instanceof XMLTestCase) { XMLTestCase testCase = (XMLTestCase) current; String[] results = editTestCase("Edit a test case", testCase.getName(), testCase.getBasedOn(), testCase.getAbstract(), testCase.getVary()); if (results != null) { testCase.setName(results[0]); testCase.setBasedOn(results[1]); testCase.setAbstract(Boolean.parseBoolean(results[2])); testCase.setVary(Boolean.parseBoolean(results[3])); setEditRemoveDuplicateEnabled(true); adjust(); } } else if (current instanceof XMLPartnerTrack) { // TODO use a combo editPartnerTrack((XMLPartnerTrack) current); } else if (current instanceof XMLPartnerTrack) { editHumanPartnerTrack((XMLHumanPartnerTrack) current); } } private void editPartnerTrack(XMLPartnerTrack track) { String name = editPartnerTrack("Edit a partner track", track.getName()); if (name != null) { track.setName(name); setEditRemoveDuplicateEnabled(true); adjust(); } } private void editHumanPartnerTrack(XMLHumanPartnerTrack track) { String name = editPartnerTrack("Edit a WS-HT Track", track.getName()); if (name != null) { track.setName(name); setEditRemoveDuplicateEnabled(true); adjust(); } } @Override protected void removePressed() { Object current = getViewerSelection(); if (current instanceof XMLTestCase) { removeTestCase(current); } else if (current instanceof XMLTrack) { removeTrack((XMLTrack) current); } else if (current instanceof XMLHumanPartnerTrack) { removeTrack((XMLHumanPartnerTrack) current); } } private void removeTrack(XMLHumanPartnerTrack track) { XMLTestCase current = getTestCase(track); List<XMLHumanPartnerTrack> partnerTrackList = current.getHumanPartnerTrackList(); int index = partnerTrackList.indexOf(track); if (index >= 0) { current.removeHumanPartnerTrack(index); getPage().postTrackSelected((XMLHumanPartnerTrack) null); } getViewer().refresh(); setEditRemoveDuplicateEnabled(false); markDirty(); } private void removeTestCase(Object current) { XMLTestCasesSection testCaseSection = getTestCasesXMLPart(); List<XMLTestCase> testCaseList = testCaseSection.getTestCaseList(); int i = 0; for (XMLTestCase testCase : testCaseList) { if (testCase.equals(current)) { testCaseSection.removeTestCase(i); break; } i++; } getViewer().refresh(); setEditRemoveDuplicateEnabled(false); markDirty(); } private XMLTestCase getTestCase(XmlObject o) { XmlCursor c = o.newCursor(); try { if (!c.toParent()) { return null; } XmlObject object = c.getObject(); if (object instanceof XMLTestCase) { return (XMLTestCase) object; } else { return null; } } finally { c.dispose(); } } private void removeTrack(XMLTrack track) { XMLTestCase current = getTestCase(track); List<XMLPartnerTrack> partnerTrackList = current.getPartnerTrackList(); int index = partnerTrackList.indexOf(track); if (index >= 0) { current.removePartnerTrack(index); getPage().postTrackSelected((XMLTrack) null); } getViewer().refresh(); setEditRemoveDuplicateEnabled(false); markDirty(); } @Override protected void upPressed() { Object viewerSelection = getViewerSelection(); if (viewerSelection instanceof XMLTestCase) { // move the current activity to the one before XMLTestCase xmlTestCase = (XMLTestCase) viewerSelection; int currentPosition = testSuite.getTestCases().getTestCaseList().indexOf(xmlTestCase); XmlCursor currentCursor = xmlTestCase.newCursor(); // Does this activity even have a previous sibling? if (currentCursor.toPrevSibling()) { // move from the current activity to the position of the // previous sibling, i.e. one up. xmlTestCase.newCursor().moveXml(currentCursor); adjust(); setSelection(testSuite.getTestCases().getTestCaseList().get(currentPosition - 1)); } currentCursor.dispose(); } } @Override protected void downPressed() { Object viewerSelection = getViewerSelection(); if (viewerSelection instanceof XMLTestCase) { // move the current activity to the one before XMLTestCase xmlTestCase = (XMLTestCase) viewerSelection; int currentPosition = testSuite.getTestCases().getTestCaseList().indexOf(xmlTestCase); XmlCursor currentCursor = xmlTestCase.newCursor(); // Does this activity even have a next sibling? if (currentCursor.toNextSibling()) { // Yes, it does -> move that sibling up to the current activity // position currentCursor.moveXml(xmlTestCase.newCursor()); adjust(); setSelection(testSuite.getTestCases().getTestCaseList().get(currentPosition + 1)); } currentCursor.dispose(); } } @Override protected void duplicatePressed() { Object viewerSelection = getViewerSelection(); if (viewerSelection instanceof XMLTestCase) { // move the current activity to the one before XMLTestCase testCase = (XMLTestCase) viewerSelection; Node node = testCase.getDomNode(); node.getParentNode().appendChild(node.cloneNode(true)); adjust(); List<XMLTestCase> testCases = testSuite.getTestCases().getTestCaseList(); setSelection(testCases.get(testCases.size() - 1)); } } private void adjust() { // Don't call this.refresh(); changes dirty/stale states getViewer().refresh(); markDirty(); } private String editPartnerTrack(String title, String current) { List<XMLPartnerDeploymentInformation> partnerList = getEditor().getTestSuite() .getDeployment().getPartnerList(); String[] partnerNames = new String[partnerList.size()]; int i = 0; boolean found = false; for (XMLPartnerDeploymentInformation information : partnerList) { partnerNames[i] = information.getName(); if (partnerNames[i].equals(current)) found = true; i++; } if (!found) { // The partner track seems to have been deleted. Cannot display // it... current = null; } FieldBasedInputDialog dialog = new FieldBasedInputDialog(getShell(), title); ComboField combo = new ComboField(dialog, "Name:", current, partnerNames); combo.setValidator(new NotEmptyValidator("Name")); dialog.addField(combo); if (dialog.open() != Window.OK) return null; return combo.getSelection(); } private String editHumanPartnerTrack(String title, String current) { List<XMLHumanPartnerDeploymentInformation> partnerList = getEditor().getTestSuite() .getDeployment().getHumanPartnerList(); String[] partnerNames = new String[partnerList.size()]; int i = 0; boolean found = false; for (XMLHumanPartnerDeploymentInformation information : partnerList) { partnerNames[i] = information.getName(); if (partnerNames[i].equals(current)) found = true; i++; } if (!found) { // The partner track seems to have been deleted. Cannot display // it... current = null; } FieldBasedInputDialog dialog = new FieldBasedInputDialog(getShell(), title); ComboField combo = new ComboField(dialog, "Name:", current, partnerNames); combo.setValidator(new NotEmptyValidator("Name")); dialog.addField(combo); if (dialog.open() != Window.OK) return null; return combo.getSelection(); } private String[] editTestCase(String title, String currentName, String currentBasedOn, boolean currentAbstractSetting, boolean currentVarySetting) { FieldBasedInputDialog dialog = new FieldBasedInputDialog(getShell(), title); TextField nameField = new TextField(dialog, "Name:", currentName, TextField.Style.SINGLE); nameField.setValidator(new NotEmptyValidator("Name")); dialog.addField(nameField); TextField basedOnField = new TextField(dialog, "Based On:", currentBasedOn, TextField.Style.SINGLE); basedOnField.setValidator(new NullValidator()); dialog.addField(basedOnField); CheckBoxField abstractField = new CheckBoxField(dialog, "Abstract", currentAbstractSetting); abstractField.setValidator(new NotEmptyValidator("Abstract")); dialog.addField(abstractField); CheckBoxField varyField = new CheckBoxField(dialog, "Vary send delay times", currentVarySetting); varyField.setValidator(new NotEmptyValidator("Vary")); dialog.addField(varyField); if (dialog.open() != Window.OK) return null; return new String[] { nameField.getSelection(), basedOnField.getSelection(), abstractField.getSelection(), varyField.getSelection() }; } @Override protected void itemSelected(Object firstElement) { if (firstElement instanceof XMLTrack) { XMLTrack selection = (XMLTrack) firstElement; getPage().postTrackSelected(selection); } else if (firstElement instanceof XMLHumanPartnerTrack) { XMLHumanPartnerTrack selection = (XMLHumanPartnerTrack) firstElement; getPage().postTrackSelected(selection); } setEnabled(BUTTON_REMOVE, getIsDeleteEnabled(firstElement)); setEnabled(BUTTON_EDIT, getIsEditEnabled(firstElement)); setEnabled(BUTTON_DUPLICATE, getIsDuplicateEnabled(firstElement)); setEnabled( BUTTON_UP, getIsMoveEnabled(firstElement) && ActivityUtil.hasPrevious((XmlObject) firstElement)); setEnabled(BUTTON_DOWN, getIsMoveEnabled(firstElement) && ActivityUtil.hasNext((XmlObject) firstElement)); } @Override protected void fillContextMenu(IMenuManager manager) { ISelection selection = getViewer().getSelection(); IStructuredSelection ssel = (IStructuredSelection) selection; IMenuManager newMenu = new MenuManager("&New"); // Enable adding test cases if no selection, or current selection is a // test case if (ssel.size() == 0 || (ssel.size() == 1 && ssel.getFirstElement() instanceof XMLTestCase)) { createAction(newMenu, "Test Case", new Action() { @Override public void run() { addPressed(); } }); } if (ssel.size() == 1) { final Object object = ssel.getFirstElement(); if (object instanceof XMLTestCase) { // Enable adding partner tracks/client tracks if a test case is // selected final XMLTestCase testCase = (XMLTestCase) object; createAction(newMenu, "Partner Track", new Action() { @Override public void run() { addPartnerTrack(testCase); } }); createAction(newMenu, "WS-HT Track", new Action() { @Override public void run() { addHumanPartnerTrack(testCase); } }); Action newClientTrackAction = createAction(newMenu, "Client Track", new Action() { @Override public void run() { addClientTrack(testCase); } }); newClientTrackAction.setEnabled(testCase.getClientTrack() == null); } manager.add(newMenu); manager.add(new Separator()); Action editAction = createAction(manager, "&Edit", new Action() { @Override public void run() { editPressed(); } }); editAction.setEnabled(getIsEditEnabled(object)); manager.add(new Separator()); Action removeAction = createAction(manager, "&Delete", new Action() { @Override public void run() { removePressed(); } }); removeAction.setEnabled(getIsDeleteEnabled(object)); manager.add(new Separator()); Action duplicateAction = createAction(manager, "D&uplicate", new Action() { @Override public void run() { - removePressed(); + duplicatePressed(); } }); duplicateAction.setEnabled(getIsDeleteEnabled(object)); if(object instanceof XMLTestCase) { manager.add(new Separator()); createAction(manager, "Run Test Case", new Action() { @Override public void run() { getEditor().doSave(null); runTestCase((XMLTestCase) object); } }); } } } protected void runTestCase(XMLTestCase testCase) { BPELLaunchShortCut launchShortCut = new BPELLaunchShortCut(); launchShortCut.launch((IFile)getEditor().getEditorInput().getAdapter(IFile.class), testCase.getName(), "run"); } private boolean getIsMoveEnabled(Object object) { return (object instanceof XMLTestCase); } private boolean getIsEditEnabled(Object object) { return (object instanceof XMLPartnerTrack || object instanceof XMLTestCase || object instanceof XMLHumanPartnerTrack); } private boolean getIsDuplicateEnabled(Object object) { return (object instanceof XMLTestCase); } private boolean getIsDeleteEnabled(Object object) { return object != null; // (object instanceof XMLTestCase); } }
true
true
protected void fillContextMenu(IMenuManager manager) { ISelection selection = getViewer().getSelection(); IStructuredSelection ssel = (IStructuredSelection) selection; IMenuManager newMenu = new MenuManager("&New"); // Enable adding test cases if no selection, or current selection is a // test case if (ssel.size() == 0 || (ssel.size() == 1 && ssel.getFirstElement() instanceof XMLTestCase)) { createAction(newMenu, "Test Case", new Action() { @Override public void run() { addPressed(); } }); } if (ssel.size() == 1) { final Object object = ssel.getFirstElement(); if (object instanceof XMLTestCase) { // Enable adding partner tracks/client tracks if a test case is // selected final XMLTestCase testCase = (XMLTestCase) object; createAction(newMenu, "Partner Track", new Action() { @Override public void run() { addPartnerTrack(testCase); } }); createAction(newMenu, "WS-HT Track", new Action() { @Override public void run() { addHumanPartnerTrack(testCase); } }); Action newClientTrackAction = createAction(newMenu, "Client Track", new Action() { @Override public void run() { addClientTrack(testCase); } }); newClientTrackAction.setEnabled(testCase.getClientTrack() == null); } manager.add(newMenu); manager.add(new Separator()); Action editAction = createAction(manager, "&Edit", new Action() { @Override public void run() { editPressed(); } }); editAction.setEnabled(getIsEditEnabled(object)); manager.add(new Separator()); Action removeAction = createAction(manager, "&Delete", new Action() { @Override public void run() { removePressed(); } }); removeAction.setEnabled(getIsDeleteEnabled(object)); manager.add(new Separator()); Action duplicateAction = createAction(manager, "D&uplicate", new Action() { @Override public void run() { removePressed(); } }); duplicateAction.setEnabled(getIsDeleteEnabled(object)); if(object instanceof XMLTestCase) { manager.add(new Separator()); createAction(manager, "Run Test Case", new Action() { @Override public void run() { getEditor().doSave(null); runTestCase((XMLTestCase) object); } }); } } }
protected void fillContextMenu(IMenuManager manager) { ISelection selection = getViewer().getSelection(); IStructuredSelection ssel = (IStructuredSelection) selection; IMenuManager newMenu = new MenuManager("&New"); // Enable adding test cases if no selection, or current selection is a // test case if (ssel.size() == 0 || (ssel.size() == 1 && ssel.getFirstElement() instanceof XMLTestCase)) { createAction(newMenu, "Test Case", new Action() { @Override public void run() { addPressed(); } }); } if (ssel.size() == 1) { final Object object = ssel.getFirstElement(); if (object instanceof XMLTestCase) { // Enable adding partner tracks/client tracks if a test case is // selected final XMLTestCase testCase = (XMLTestCase) object; createAction(newMenu, "Partner Track", new Action() { @Override public void run() { addPartnerTrack(testCase); } }); createAction(newMenu, "WS-HT Track", new Action() { @Override public void run() { addHumanPartnerTrack(testCase); } }); Action newClientTrackAction = createAction(newMenu, "Client Track", new Action() { @Override public void run() { addClientTrack(testCase); } }); newClientTrackAction.setEnabled(testCase.getClientTrack() == null); } manager.add(newMenu); manager.add(new Separator()); Action editAction = createAction(manager, "&Edit", new Action() { @Override public void run() { editPressed(); } }); editAction.setEnabled(getIsEditEnabled(object)); manager.add(new Separator()); Action removeAction = createAction(manager, "&Delete", new Action() { @Override public void run() { removePressed(); } }); removeAction.setEnabled(getIsDeleteEnabled(object)); manager.add(new Separator()); Action duplicateAction = createAction(manager, "D&uplicate", new Action() { @Override public void run() { duplicatePressed(); } }); duplicateAction.setEnabled(getIsDeleteEnabled(object)); if(object instanceof XMLTestCase) { manager.add(new Separator()); createAction(manager, "Run Test Case", new Action() { @Override public void run() { getEditor().doSave(null); runTestCase((XMLTestCase) object); } }); } } }
diff --git a/src/share/personal/classes/common/sun/io/CharToByteDoubleByte.java b/src/share/personal/classes/common/sun/io/CharToByteDoubleByte.java index 203cce16..fe6bbe44 100644 --- a/src/share/personal/classes/common/sun/io/CharToByteDoubleByte.java +++ b/src/share/personal/classes/common/sun/io/CharToByteDoubleByte.java @@ -1,217 +1,217 @@ /* * @(#)CharToByteDoubleByte.java 1.12 06/10/10 * * Copyright 1990-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, 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 version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. * */ package sun.io; /** * @author Limin Shi */ public abstract class CharToByteDoubleByte extends CharToByteConverter { /* * 1st level index, provided by subclass */ protected short index1[]; /* * 2nd level index, provided by subclass */ protected String index2[]; /* * Size of bad input that caused conversion to stop */ protected int badInputLength; protected char highHalfZoneCode; public int flush(byte[] output, int outStart, int outEnd) throws MalformedInputException, ConversionBufferFullException { if (highHalfZoneCode != 0) { highHalfZoneCode = 0; badInputLength = 0; throw new MalformedInputException(); } byteOff = charOff = 0; return 0; } /** * Converts characters to sequences of bytes. * Conversions that result in Exceptions can be restarted by calling * convert again, with appropriately modified parameters. * @return the characters written to output. * @param input char array containing text in Unicode * @param inStart offset in input array * @param inEnd offset of last byte to be converted * @param output byte array to receive conversion result * @param outStart starting offset * @param outEnd offset of last byte to be written to * @throw UnsupportedCharacterException for any character * that cannot be converted to the external character set. */ public int convert(char[] input, int inOff, int inEnd, byte[] output, int outOff, int outEnd) throws MalformedInputException, UnknownCharacterException, ConversionBufferFullException { char inputChar; // Input character to be converted byte[] outputByte; // Output byte written to output int inputSize = 0; // Size of input int outputSize = 0; // Size of output byte[] tmpbuf = new byte[2]; // Record beginning offsets charOff = inOff; byteOff = outOff; if (highHalfZoneCode != 0) { inputChar = highHalfZoneCode; highHalfZoneCode = 0; if (input[inOff] >= 0xdc00 && input[inOff] <= 0xdfff) { // This is legal UTF16 sequence. badInputLength = 1; throw new UnknownCharacterException(); } else { // This is illegal UTF16 sequence. badInputLength = 0; throw new MalformedInputException(); } } inputSize = 1; // Loop until we hit the end of the input while (charOff < inEnd) { outputByte = tmpbuf; inputChar = input[charOff]; // Get the input character // Is this a high surrogate? - if (inputChar <= '\uD800' && inputChar >= '\uDBFF') { + if (inputChar >= '\uD800' && inputChar <= '\uDBFF') { // Is this the last character of the input? if (charOff + 1 >= inEnd) { highHalfZoneCode = inputChar; break; } // Is there a low surrogate following? inputChar = input[charOff + 1]; if (inputChar >= '\uDC00' && inputChar <= '\uDFFF') { // We have a valid surrogate pair. Too bad we don't do // surrogates. Is substitution enabled? if (subMode) { outputByte = subBytes; outputSize = subBytes.length; inputSize = 2; } else { badInputLength = 2; throw new UnknownCharacterException(); } } else { // We have a malformed surrogate pair badInputLength = 1; throw new MalformedInputException(); } } // Is this an unaccompanied low surrogate? else if (inputChar >= '\uDC00' && inputChar <= '\uDFFF') { badInputLength = 1; throw new MalformedInputException(); } else { outputSize = convSingleByte(inputChar, outputByte); if (outputSize == 0) { // DoubleByte int ncode = getNative(inputChar); if (ncode != 0) { if (ncode < 0x100) { outputByte[0] = (byte) (ncode & 0xff); outputSize = 1; } else { outputByte[0] = (byte) ((ncode & 0xff00) >> 8); outputByte[1] = (byte) (ncode & 0xff); outputSize = 2; } } else { if (subMode) { outputByte = subBytes; outputSize = subBytes.length; } else { badInputLength = 1; throw new UnknownCharacterException(); } } } } // If we don't have room for the output, throw an exception if (byteOff + outputSize > outEnd) throw new ConversionBufferFullException(); // Put the byte in the output buffer for (int i = 0; i < outputSize; i++) { output[byteOff++] = outputByte[i]; } charOff += inputSize; } // Return the length written to the output buffer return byteOff - outOff; } /** * the maximum number of bytes needed to hold a converted char * @returns the maximum number of bytes needed for a converted char */ public int getMaxBytesPerChar() { return 2; } /** * Resets the converter. * Call this method to reset the converter to its initial state */ public void reset() { byteOff = charOff = 0; highHalfZoneCode = 0; } /** * Return whether a character is mappable or not * @return true if a character is mappable */ public boolean canConvert(char ch) { byte[] outByte = new byte[2]; if ((ch == (char) 0) || (convSingleByte(ch, outByte) != 0)) return true; if (this.getNative(ch) != 0) return true; return false; } /* * Can be changed by subclass */ protected int convSingleByte(char inputChar, byte[] outputByte) { if (inputChar < 0x80) { outputByte[0] = (byte) (inputChar & 0x7f); return 1; } return 0; } /* * Can be changed by subclass */ protected int getNative(char ch) { int offset = index1[((ch & 0xff00) >> 8)] << 8; return index2[offset >> 12].charAt((offset & 0xfff) + (ch & 0xff)); } }
true
true
public int convert(char[] input, int inOff, int inEnd, byte[] output, int outOff, int outEnd) throws MalformedInputException, UnknownCharacterException, ConversionBufferFullException { char inputChar; // Input character to be converted byte[] outputByte; // Output byte written to output int inputSize = 0; // Size of input int outputSize = 0; // Size of output byte[] tmpbuf = new byte[2]; // Record beginning offsets charOff = inOff; byteOff = outOff; if (highHalfZoneCode != 0) { inputChar = highHalfZoneCode; highHalfZoneCode = 0; if (input[inOff] >= 0xdc00 && input[inOff] <= 0xdfff) { // This is legal UTF16 sequence. badInputLength = 1; throw new UnknownCharacterException(); } else { // This is illegal UTF16 sequence. badInputLength = 0; throw new MalformedInputException(); } } inputSize = 1; // Loop until we hit the end of the input while (charOff < inEnd) { outputByte = tmpbuf; inputChar = input[charOff]; // Get the input character // Is this a high surrogate? if (inputChar <= '\uD800' && inputChar >= '\uDBFF') { // Is this the last character of the input? if (charOff + 1 >= inEnd) { highHalfZoneCode = inputChar; break; } // Is there a low surrogate following? inputChar = input[charOff + 1]; if (inputChar >= '\uDC00' && inputChar <= '\uDFFF') { // We have a valid surrogate pair. Too bad we don't do // surrogates. Is substitution enabled? if (subMode) { outputByte = subBytes; outputSize = subBytes.length; inputSize = 2; } else { badInputLength = 2; throw new UnknownCharacterException(); } } else { // We have a malformed surrogate pair badInputLength = 1; throw new MalformedInputException(); } } // Is this an unaccompanied low surrogate? else if (inputChar >= '\uDC00' && inputChar <= '\uDFFF') { badInputLength = 1; throw new MalformedInputException(); } else { outputSize = convSingleByte(inputChar, outputByte); if (outputSize == 0) { // DoubleByte int ncode = getNative(inputChar); if (ncode != 0) { if (ncode < 0x100) { outputByte[0] = (byte) (ncode & 0xff); outputSize = 1; } else { outputByte[0] = (byte) ((ncode & 0xff00) >> 8); outputByte[1] = (byte) (ncode & 0xff); outputSize = 2; } } else { if (subMode) { outputByte = subBytes; outputSize = subBytes.length; } else { badInputLength = 1; throw new UnknownCharacterException(); } } } } // If we don't have room for the output, throw an exception if (byteOff + outputSize > outEnd) throw new ConversionBufferFullException(); // Put the byte in the output buffer for (int i = 0; i < outputSize; i++) { output[byteOff++] = outputByte[i]; } charOff += inputSize; } // Return the length written to the output buffer return byteOff - outOff; }
public int convert(char[] input, int inOff, int inEnd, byte[] output, int outOff, int outEnd) throws MalformedInputException, UnknownCharacterException, ConversionBufferFullException { char inputChar; // Input character to be converted byte[] outputByte; // Output byte written to output int inputSize = 0; // Size of input int outputSize = 0; // Size of output byte[] tmpbuf = new byte[2]; // Record beginning offsets charOff = inOff; byteOff = outOff; if (highHalfZoneCode != 0) { inputChar = highHalfZoneCode; highHalfZoneCode = 0; if (input[inOff] >= 0xdc00 && input[inOff] <= 0xdfff) { // This is legal UTF16 sequence. badInputLength = 1; throw new UnknownCharacterException(); } else { // This is illegal UTF16 sequence. badInputLength = 0; throw new MalformedInputException(); } } inputSize = 1; // Loop until we hit the end of the input while (charOff < inEnd) { outputByte = tmpbuf; inputChar = input[charOff]; // Get the input character // Is this a high surrogate? if (inputChar >= '\uD800' && inputChar <= '\uDBFF') { // Is this the last character of the input? if (charOff + 1 >= inEnd) { highHalfZoneCode = inputChar; break; } // Is there a low surrogate following? inputChar = input[charOff + 1]; if (inputChar >= '\uDC00' && inputChar <= '\uDFFF') { // We have a valid surrogate pair. Too bad we don't do // surrogates. Is substitution enabled? if (subMode) { outputByte = subBytes; outputSize = subBytes.length; inputSize = 2; } else { badInputLength = 2; throw new UnknownCharacterException(); } } else { // We have a malformed surrogate pair badInputLength = 1; throw new MalformedInputException(); } } // Is this an unaccompanied low surrogate? else if (inputChar >= '\uDC00' && inputChar <= '\uDFFF') { badInputLength = 1; throw new MalformedInputException(); } else { outputSize = convSingleByte(inputChar, outputByte); if (outputSize == 0) { // DoubleByte int ncode = getNative(inputChar); if (ncode != 0) { if (ncode < 0x100) { outputByte[0] = (byte) (ncode & 0xff); outputSize = 1; } else { outputByte[0] = (byte) ((ncode & 0xff00) >> 8); outputByte[1] = (byte) (ncode & 0xff); outputSize = 2; } } else { if (subMode) { outputByte = subBytes; outputSize = subBytes.length; } else { badInputLength = 1; throw new UnknownCharacterException(); } } } } // If we don't have room for the output, throw an exception if (byteOff + outputSize > outEnd) throw new ConversionBufferFullException(); // Put the byte in the output buffer for (int i = 0; i < outputSize; i++) { output[byteOff++] = outputByte[i]; } charOff += inputSize; } // Return the length written to the output buffer return byteOff - outOff; }
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/viewers/ChildrenUpdateTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/viewers/ChildrenUpdateTests.java index 06dc36a58..a4413e3e6 100644 --- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/viewers/ChildrenUpdateTests.java +++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/viewers/ChildrenUpdateTests.java @@ -1,58 +1,58 @@ /******************************************************************************* * Copyright (c) 2007 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 *******************************************************************************/ package org.eclipse.jdt.debug.tests.viewers; import org.eclipse.debug.internal.ui.viewers.model.ChildrenUpdate; import org.eclipse.jdt.debug.tests.AbstractDebugTest; import org.eclipse.jface.viewers.TreePath; /** * Tests coalescing of children update requests. * * @since 3.3 */ public class ChildrenUpdateTests extends AbstractDebugTest { /** * @param name */ public ChildrenUpdateTests(String name) { super(name); } /** * Tests coalescing of requests */ public void testCoalesce () { Object element = new Object(); - ChildrenUpdate update1 = new ChildrenUpdate(null, TreePath.EMPTY, element, 1, null); - ChildrenUpdate update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 2, null); + ChildrenUpdate update1 = new ChildrenUpdate(null, TreePath.EMPTY, element, 1, null, null); + ChildrenUpdate update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 2, null, null); assertTrue("Should coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 2, update1.getLength()); - update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 3, null); + update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 3, null, null); assertTrue("Should coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 3, update1.getLength()); - update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 2, null); + update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 2, null, null); assertTrue("Should coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 3, update1.getLength()); - update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 5, null); + update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 5, null, null); assertFalse("Should not coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 3, update1.getLength()); } }
false
true
public void testCoalesce () { Object element = new Object(); ChildrenUpdate update1 = new ChildrenUpdate(null, TreePath.EMPTY, element, 1, null); ChildrenUpdate update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 2, null); assertTrue("Should coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 2, update1.getLength()); update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 3, null); assertTrue("Should coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 3, update1.getLength()); update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 2, null); assertTrue("Should coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 3, update1.getLength()); update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 5, null); assertFalse("Should not coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 3, update1.getLength()); }
public void testCoalesce () { Object element = new Object(); ChildrenUpdate update1 = new ChildrenUpdate(null, TreePath.EMPTY, element, 1, null, null); ChildrenUpdate update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 2, null, null); assertTrue("Should coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 2, update1.getLength()); update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 3, null, null); assertTrue("Should coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 3, update1.getLength()); update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 2, null, null); assertTrue("Should coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 3, update1.getLength()); update2 = new ChildrenUpdate(null, TreePath.EMPTY, element, 5, null, null); assertFalse("Should not coalesce", update1.coalesce(update2)); assertEquals("Wrong offset", 1, update1.getOffset()); assertEquals("Wrong length", 3, update1.getLength()); }
diff --git a/enduro-project/test/unittest/LapRaceSorterTest.java b/enduro-project/test/unittest/LapRaceSorterTest.java index 6cfcb9c..d7bffda 100644 --- a/enduro-project/test/unittest/LapRaceSorterTest.java +++ b/enduro-project/test/unittest/LapRaceSorterTest.java @@ -1,45 +1,45 @@ package unittest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.FileReader; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import regressiontest.ListTest; import regressiontest.PVGRunner; import enduro.LapRaceSorter; @ListTest() @RunWith(PVGRunner.class) public class LapRaceSorterTest { @Test public void testReadWriteStartTimeFile() { assertTrue(PVGRunner.testSuccess); } @Test public void testImpossibleLap() { try { - BufferedReader in = new BufferedReader(new FileReader("result.temp")); + BufferedReader in = new BufferedReader(new FileReader("result.temp.lap")); in.readLine(); assertEquals( "StartNr; Namn; #Varv; TotalTid; Varv1; Varv2; Varv3; Start; Varvning1; Varvning2; Mål", in.readLine()); in.readLine(); assertEquals( "2; Bengt Bsson; 3; 01.15.16; 00.14.00; 00.27.00; 00.34.16; 12.00.00; 12.14.00; 12.41.00; 13.15.16; Omöjlig varvtid?", in.readLine()); in.close(); } catch (Exception e) { e.printStackTrace(); } } }
true
true
public void testImpossibleLap() { try { BufferedReader in = new BufferedReader(new FileReader("result.temp")); in.readLine(); assertEquals( "StartNr; Namn; #Varv; TotalTid; Varv1; Varv2; Varv3; Start; Varvning1; Varvning2; Mål", in.readLine()); in.readLine(); assertEquals( "2; Bengt Bsson; 3; 01.15.16; 00.14.00; 00.27.00; 00.34.16; 12.00.00; 12.14.00; 12.41.00; 13.15.16; Omöjlig varvtid?", in.readLine()); in.close(); } catch (Exception e) { e.printStackTrace(); } }
public void testImpossibleLap() { try { BufferedReader in = new BufferedReader(new FileReader("result.temp.lap")); in.readLine(); assertEquals( "StartNr; Namn; #Varv; TotalTid; Varv1; Varv2; Varv3; Start; Varvning1; Varvning2; Mål", in.readLine()); in.readLine(); assertEquals( "2; Bengt Bsson; 3; 01.15.16; 00.14.00; 00.27.00; 00.34.16; 12.00.00; 12.14.00; 12.41.00; 13.15.16; Omöjlig varvtid?", in.readLine()); in.close(); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/war-core/src/main/java/com/silverpeas/socialNetwork/myProfil/servlets/JSONServlet.java b/war-core/src/main/java/com/silverpeas/socialNetwork/myProfil/servlets/JSONServlet.java index c39ff72190..eb581f2361 100644 --- a/war-core/src/main/java/com/silverpeas/socialNetwork/myProfil/servlets/JSONServlet.java +++ b/war-core/src/main/java/com/silverpeas/socialNetwork/myProfil/servlets/JSONServlet.java @@ -1,67 +1,74 @@ /** * Copyright (C) 2000 - 2011 Silverpeas * * 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, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.com/legal/licensing" * * 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 com.silverpeas.socialNetwork.myProfil.servlets; import java.io.IOException; import java.io.PrintWriter; 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 org.json.JSONObject; import com.silverpeas.socialNetwork.myProfil.control.SocialNetworkService; import com.silverpeas.util.StringUtil; import com.stratelia.silverpeas.peasCore.MainSessionController; public class JSONServlet extends HttpServlet { private static final long serialVersionUID = -843491398398079951L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); MainSessionController m_MainSessionCtrl = (MainSessionController) session.getAttribute( MainSessionController.MAIN_SESSION_CONTROLLER_ATT); + if (m_MainSessionCtrl == null) { + JSONObject jsonStatus = new JSONObject(); + jsonStatus.put("status", "silverpeastimeout"); + PrintWriter out = response.getWriter(); + out.println(jsonStatus); + return; + } String userId = m_MainSessionCtrl.getUserId(); String action = request.getParameter("Action"); if ("updateStatus".equalsIgnoreCase(action)) { SocialNetworkService socialNetworkService = new SocialNetworkService(userId); String status = request.getParameter("status"); // if status equal null or empty so don't do update status and do get Last status if (StringUtil.isDefined(status)) { status = socialNetworkService.changeStatusService(status); } else { status = socialNetworkService.getLastStatusService(); } JSONObject jsonStatus = new JSONObject(); jsonStatus.put("status", status); PrintWriter out = response.getWriter(); out.println(jsonStatus); } } }
true
true
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); MainSessionController m_MainSessionCtrl = (MainSessionController) session.getAttribute( MainSessionController.MAIN_SESSION_CONTROLLER_ATT); String userId = m_MainSessionCtrl.getUserId(); String action = request.getParameter("Action"); if ("updateStatus".equalsIgnoreCase(action)) { SocialNetworkService socialNetworkService = new SocialNetworkService(userId); String status = request.getParameter("status"); // if status equal null or empty so don't do update status and do get Last status if (StringUtil.isDefined(status)) { status = socialNetworkService.changeStatusService(status); } else { status = socialNetworkService.getLastStatusService(); } JSONObject jsonStatus = new JSONObject(); jsonStatus.put("status", status); PrintWriter out = response.getWriter(); out.println(jsonStatus); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); MainSessionController m_MainSessionCtrl = (MainSessionController) session.getAttribute( MainSessionController.MAIN_SESSION_CONTROLLER_ATT); if (m_MainSessionCtrl == null) { JSONObject jsonStatus = new JSONObject(); jsonStatus.put("status", "silverpeastimeout"); PrintWriter out = response.getWriter(); out.println(jsonStatus); return; } String userId = m_MainSessionCtrl.getUserId(); String action = request.getParameter("Action"); if ("updateStatus".equalsIgnoreCase(action)) { SocialNetworkService socialNetworkService = new SocialNetworkService(userId); String status = request.getParameter("status"); // if status equal null or empty so don't do update status and do get Last status if (StringUtil.isDefined(status)) { status = socialNetworkService.changeStatusService(status); } else { status = socialNetworkService.getLastStatusService(); } JSONObject jsonStatus = new JSONObject(); jsonStatus.put("status", status); PrintWriter out = response.getWriter(); out.println(jsonStatus); } }
diff --git a/Alkitab/src/yuku/alkitab/base/storage/InternalReader.java b/Alkitab/src/yuku/alkitab/base/storage/InternalReader.java index 1bf79dfe..29457696 100644 --- a/Alkitab/src/yuku/alkitab/base/storage/InternalReader.java +++ b/Alkitab/src/yuku/alkitab/base/storage/InternalReader.java @@ -1,240 +1,240 @@ package yuku.alkitab.base.storage; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import yuku.alkitab.base.S; import yuku.alkitab.base.model.Ari; import yuku.alkitab.base.model.Book; import yuku.alkitab.base.model.PericopeBlock; import yuku.alkitab.base.model.PericopeIndex; import yuku.alkitab.base.model.Version; import yuku.bintex.BintexReader; public class InternalReader implements Reader { public static final String TAG = InternalReader.class.getSimpleName(); // # buat cache Asset private static InputStream cache_inputStream = null; private static String cache_file = null; private static int cache_posInput = -1; private final String edisiPrefix; private final String edisiShortName; private final String edisiLongName; private final ReaderDecoder readerDecoder; public InternalReader(String edisiPrefix, String edisiShortName, String edisiLongName, ReaderDecoder readerDecoder) { this.edisiPrefix = edisiPrefix; this.edisiShortName = edisiShortName; this.edisiLongName = edisiLongName; this.readerDecoder = readerDecoder; } @Override public String getShortName() { return edisiShortName; } @Override public String getLongName() { return edisiLongName; } @Override public Book[] loadBooks() { InputStream is = S.openRaw(edisiPrefix + "_index_bt"); //$NON-NLS-1$ BintexReader in = new BintexReader(is); try { ArrayList<Book> xkitab = new ArrayList<Book>(); try { int pos = 0; while (true) { Book k = bacaKitab(in, pos++); xkitab.add(k); } } catch (IOException e) { Log.d(TAG, "siapinKitab selesai memuat"); //$NON-NLS-1$ } return xkitab.toArray(new Book[xkitab.size()]); } finally { in.close(); } } private static Book bacaKitab(BintexReader in, int pos) throws IOException { Book k = new Book(); k.bookId = pos; // autostring bookName // shortstring resName // int chapter_count // uint8[chapter_count] verse_counts // int[chapter_count+1] chapter_offsets k.nama = k.judul = in.readAutoString(); k.file = in.readShortString(); k.nchapter = in.readInt(); k.nverses = new int[k.nchapter]; for (int i = 0; i < k.nchapter; i++) { k.nverses[i] = in.readUint8(); } k.pasal_offset = new int[k.nchapter + 1]; for (int i = 0; i < k.nchapter + 1; i++) { k.pasal_offset[i] = in.readInt(); } return k; } @Override public String[] loadVerseText(Book book, int pasal_1, boolean janganPisahAyat, boolean hurufKecil) { - if (pasal_1 > book.nchapter) { + if (pasal_1 < 1 || pasal_1 > book.nchapter) { return null; } int offset = book.pasal_offset[pasal_1 - 1]; int length = 0; try { InputStream in; // Log.d("alki", "muatTeks kitab=" + kitab.nama + " pasal[1base]=" + pasal + " offset=" + offset); // Log.d("alki", "muatTeks cache_file=" + cache_file + " cache_posInput=" + cache_posInput); if (cache_inputStream == null) { // kasus 1: belum buka apapun in = S.openRaw(book.file); cache_inputStream = in; cache_file = book.file; in.skip(offset); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 1"); } else { // kasus 2: uda pernah buka. Cek apakah filenya sama if (book.file.equals(cache_file)) { // kasus 2.1: filenya sama. if (offset >= cache_posInput) { // bagus, kita bisa maju. in = cache_inputStream; in.skip(offset - cache_posInput); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 2.1 bagus"); } else { // ga bisa mundur. tutup dan buka lagi. cache_inputStream.close(); in = S.openRaw(book.file); cache_inputStream = in; in.skip(offset); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 2.1 jelek"); } } else { // kasus 2.2: filenya beda, tutup dan buka baru cache_inputStream.close(); in = S.openRaw(book.file); cache_inputStream = in; cache_file = book.file; in.skip(offset); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 2.2"); } } if (pasal_1 == book.nchapter) { length = in.available(); } else { length = book.pasal_offset[pasal_1] - offset; } byte[] ba = new byte[length]; in.read(ba); cache_posInput += ba.length; // jangan ditutup walau uda baca. Siapa tau masih sama filenya dengan sebelumnya. if (janganPisahAyat) { return new String[] { readerDecoder.jadikanStringTunggal(ba, hurufKecil) }; } else { return readerDecoder.pisahJadiAyat(ba, hurufKecil); } } catch (IOException e) { return new String[] { e.getMessage() }; } } @Override public PericopeIndex loadPericopeIndex() { long wmulai = System.currentTimeMillis(); InputStream is = S.openRaw(edisiPrefix + "_pericope_index_bt"); //$NON-NLS-1$ if (is == null) { return null; } BintexReader in = new BintexReader(is); try { return PericopeIndex.read(in); } catch (IOException e) { Log.e(TAG, "baca perikop index ngaco", e); //$NON-NLS-1$ return null; } finally { in.close(); Log.d(TAG, "Muat index perikop butuh ms: " + (System.currentTimeMillis() - wmulai)); //$NON-NLS-1$ } } @Override public int loadPericope(Version version, int kitab, int pasal, int[] xari, PericopeBlock[] xblok, int max) { PericopeIndex pericopeIndex = version.getIndexPerikop(); if (pericopeIndex == null) { return 0; // ga ada perikop! } int ariMin = Ari.encode(kitab, pasal, 0); int ariMax = Ari.encode(kitab, pasal + 1, 0); int res = 0; int pertama = pericopeIndex.findFirst(ariMin, ariMax); if (pertama == -1) { return 0; } int kini = pertama; BintexReader in = new BintexReader(S.openRaw(edisiPrefix + "_pericope_blocks_bt")); //$NON-NLS-1$ try { while (true) { int ari = pericopeIndex.getAri(kini); if (ari >= ariMax) { // habis. Uda ga relevan break; } PericopeBlock pericopeBlock = pericopeIndex.getBlock(in, kini); kini++; if (res < max) { xari[res] = ari; xblok[res] = pericopeBlock; res++; } else { break; } } } finally { in.close(); } return res; } }
true
true
@Override public String[] loadVerseText(Book book, int pasal_1, boolean janganPisahAyat, boolean hurufKecil) { if (pasal_1 > book.nchapter) { return null; } int offset = book.pasal_offset[pasal_1 - 1]; int length = 0; try { InputStream in; // Log.d("alki", "muatTeks kitab=" + kitab.nama + " pasal[1base]=" + pasal + " offset=" + offset); // Log.d("alki", "muatTeks cache_file=" + cache_file + " cache_posInput=" + cache_posInput); if (cache_inputStream == null) { // kasus 1: belum buka apapun in = S.openRaw(book.file); cache_inputStream = in; cache_file = book.file; in.skip(offset); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 1"); } else { // kasus 2: uda pernah buka. Cek apakah filenya sama if (book.file.equals(cache_file)) { // kasus 2.1: filenya sama. if (offset >= cache_posInput) { // bagus, kita bisa maju. in = cache_inputStream; in.skip(offset - cache_posInput); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 2.1 bagus"); } else { // ga bisa mundur. tutup dan buka lagi. cache_inputStream.close(); in = S.openRaw(book.file); cache_inputStream = in; in.skip(offset); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 2.1 jelek"); } } else { // kasus 2.2: filenya beda, tutup dan buka baru cache_inputStream.close(); in = S.openRaw(book.file); cache_inputStream = in; cache_file = book.file; in.skip(offset); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 2.2"); } } if (pasal_1 == book.nchapter) { length = in.available(); } else { length = book.pasal_offset[pasal_1] - offset; } byte[] ba = new byte[length]; in.read(ba); cache_posInput += ba.length; // jangan ditutup walau uda baca. Siapa tau masih sama filenya dengan sebelumnya. if (janganPisahAyat) { return new String[] { readerDecoder.jadikanStringTunggal(ba, hurufKecil) }; } else { return readerDecoder.pisahJadiAyat(ba, hurufKecil); } } catch (IOException e) { return new String[] { e.getMessage() }; } }
@Override public String[] loadVerseText(Book book, int pasal_1, boolean janganPisahAyat, boolean hurufKecil) { if (pasal_1 < 1 || pasal_1 > book.nchapter) { return null; } int offset = book.pasal_offset[pasal_1 - 1]; int length = 0; try { InputStream in; // Log.d("alki", "muatTeks kitab=" + kitab.nama + " pasal[1base]=" + pasal + " offset=" + offset); // Log.d("alki", "muatTeks cache_file=" + cache_file + " cache_posInput=" + cache_posInput); if (cache_inputStream == null) { // kasus 1: belum buka apapun in = S.openRaw(book.file); cache_inputStream = in; cache_file = book.file; in.skip(offset); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 1"); } else { // kasus 2: uda pernah buka. Cek apakah filenya sama if (book.file.equals(cache_file)) { // kasus 2.1: filenya sama. if (offset >= cache_posInput) { // bagus, kita bisa maju. in = cache_inputStream; in.skip(offset - cache_posInput); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 2.1 bagus"); } else { // ga bisa mundur. tutup dan buka lagi. cache_inputStream.close(); in = S.openRaw(book.file); cache_inputStream = in; in.skip(offset); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 2.1 jelek"); } } else { // kasus 2.2: filenya beda, tutup dan buka baru cache_inputStream.close(); in = S.openRaw(book.file); cache_inputStream = in; cache_file = book.file; in.skip(offset); cache_posInput = offset; // Log.d("alki", "muatTeks masuk kasus 2.2"); } } if (pasal_1 == book.nchapter) { length = in.available(); } else { length = book.pasal_offset[pasal_1] - offset; } byte[] ba = new byte[length]; in.read(ba); cache_posInput += ba.length; // jangan ditutup walau uda baca. Siapa tau masih sama filenya dengan sebelumnya. if (janganPisahAyat) { return new String[] { readerDecoder.jadikanStringTunggal(ba, hurufKecil) }; } else { return readerDecoder.pisahJadiAyat(ba, hurufKecil); } } catch (IOException e) { return new String[] { e.getMessage() }; } }
diff --git a/src/RegularExplab3.java b/src/RegularExplab3.java index 6633d2a..84f159a 100644 --- a/src/RegularExplab3.java +++ b/src/RegularExplab3.java @@ -1,58 +1,58 @@ import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegularExplab3 { // static String testStr="01010101"; static String testStr = "ac"; public static void main(String[] args) { File file = new File( - "/home/student/workspace/CompilerLab/src/expression.txt"); + "expression.txt"); int ch; String exp = null; StringBuffer strContent = new StringBuffer(""); FileInputStream fin = null; try { FileInputStream fstream = new FileInputStream( - "/home/student/workspace/CompilerLab/src/expression.txt"); + "expression.txt"); String str = null; int test = 1; DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((str = br.readLine()) != null) { // System.out.println("LINE NO: " + test + " "); // System.out.println(str); exp = str; test++; // Pattern matching Pattern pattern = Pattern.compile(exp); Matcher matcher = pattern.matcher(testStr); System.out.println("expression " + exp); if (matcher.matches()) { System.out.println("The string " + testStr + " matches with the expression!!!"); } else { System.out .println("The string does not matche with the expression!!!"); } } in.close(); } catch (Exception e) { System.err.println(e); } // } }
false
true
public static void main(String[] args) { File file = new File( "/home/student/workspace/CompilerLab/src/expression.txt"); int ch; String exp = null; StringBuffer strContent = new StringBuffer(""); FileInputStream fin = null; try { FileInputStream fstream = new FileInputStream( "/home/student/workspace/CompilerLab/src/expression.txt"); String str = null; int test = 1; DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((str = br.readLine()) != null) { // System.out.println("LINE NO: " + test + " "); // System.out.println(str); exp = str; test++; // Pattern matching Pattern pattern = Pattern.compile(exp); Matcher matcher = pattern.matcher(testStr); System.out.println("expression " + exp); if (matcher.matches()) { System.out.println("The string " + testStr + " matches with the expression!!!"); } else { System.out .println("The string does not matche with the expression!!!"); } } in.close(); } catch (Exception e) { System.err.println(e); } // }
public static void main(String[] args) { File file = new File( "expression.txt"); int ch; String exp = null; StringBuffer strContent = new StringBuffer(""); FileInputStream fin = null; try { FileInputStream fstream = new FileInputStream( "expression.txt"); String str = null; int test = 1; DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while ((str = br.readLine()) != null) { // System.out.println("LINE NO: " + test + " "); // System.out.println(str); exp = str; test++; // Pattern matching Pattern pattern = Pattern.compile(exp); Matcher matcher = pattern.matcher(testStr); System.out.println("expression " + exp); if (matcher.matches()) { System.out.println("The string " + testStr + " matches with the expression!!!"); } else { System.out .println("The string does not matche with the expression!!!"); } } in.close(); } catch (Exception e) { System.err.println(e); } // }
diff --git a/src/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java b/src/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java index 033f0cc8..84aa71d5 100644 --- a/src/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java +++ b/src/org/red5/server/net/rtmp/codec/RTMPProtocolDecoder.java @@ -1,871 +1,882 @@ package org.red5.server.net.rtmp.codec; /* * RED5 Open Source Flash Server - http://www.osflash.org/red5 * * Copyright (c) 2006-2007 by respective authors (see below). All rights reserved. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later * version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.mina.common.ByteBuffer; import org.red5.io.amf.AMF; import org.red5.io.object.Deserializer; import org.red5.io.object.Input; import org.red5.io.utils.BufferUtils; import org.red5.server.api.IConnection; import org.red5.server.api.IContext; import org.red5.server.api.IScope; import org.red5.server.api.Red5; import org.red5.server.api.IConnection.Encoding; import org.red5.server.net.protocol.HandshakeFailedException; import org.red5.server.net.protocol.ProtocolException; import org.red5.server.net.protocol.ProtocolState; import org.red5.server.net.protocol.SimpleProtocolDecoder; import org.red5.server.net.rtmp.RTMPUtils; import org.red5.server.net.rtmp.event.AudioData; import org.red5.server.net.rtmp.event.BytesRead; import org.red5.server.net.rtmp.event.ChunkSize; import org.red5.server.net.rtmp.event.ClientBW; import org.red5.server.net.rtmp.event.FlexMessage; import org.red5.server.net.rtmp.event.IRTMPEvent; import org.red5.server.net.rtmp.event.Invoke; import org.red5.server.net.rtmp.event.Notify; import org.red5.server.net.rtmp.event.Ping; import org.red5.server.net.rtmp.event.ServerBW; import org.red5.server.net.rtmp.event.Unknown; import org.red5.server.net.rtmp.event.VideoData; import org.red5.server.net.rtmp.message.Constants; import org.red5.server.net.rtmp.message.Header; import org.red5.server.net.rtmp.message.Packet; import org.red5.server.net.rtmp.message.SharedObjectTypeMapping; import org.red5.server.service.Call; import org.red5.server.service.PendingCall; import org.red5.server.so.FlexSharedObjectMessage; import org.red5.server.so.ISharedObjectEvent; import org.red5.server.so.ISharedObjectMessage; import org.red5.server.so.SharedObjectMessage; /** * RTMP protocol decoder */ public class RTMPProtocolDecoder implements Constants, SimpleProtocolDecoder, IEventDecoder { /** * Logger */ protected static Log log = LogFactory.getLog(RTMPProtocolDecoder.class .getName()); /** * I/O logger */ protected static Log ioLog = LogFactory.getLog(RTMPProtocolDecoder.class .getName() + ".in"); /** * Deserializer */ private Deserializer deserializer; /** Constructs a new RTMPProtocolDecoder. */ public RTMPProtocolDecoder() { } /** * Setter for deserializer * * @param deserializer Deserializer */ public void setDeserializer(Deserializer deserializer) { this.deserializer = deserializer; } /** {@inheritDoc} */ public List decodeBuffer(ProtocolState state, ByteBuffer buffer) { final List<Object> result = new LinkedList<Object>(); try { while (true) { final int remaining = buffer.remaining(); if (state.canStartDecoding(remaining)) { state.startDecoding(); } else { break; } final Object decodedObject = decode(state, buffer); if (state.hasDecodedObject()) { result.add(decodedObject); } else if (state.canContinueDecoding()) { continue; } else { break; } if (!buffer.hasRemaining()) { break; } } } catch (HandshakeFailedException hfe) { IConnection conn = Red5.getConnectionLocal(); if (conn != null) { conn.close(); } else { log.error("Handshake validation failed but no current connection!?"); } return null; } catch (ProtocolException pvx) { log.error("Error decoding buffer", pvx); } catch (Exception ex) { log.error("Error decoding buffer", ex); } finally { buffer.compact(); } return result; } /** * Setup the classloader to use when deserializing custom objects. */ protected void setupClassLoader() { IConnection conn = Red5.getConnectionLocal(); if (conn == null) { return; } IScope scope = conn.getScope(); if (scope == null) { return; } IContext context = scope.getContext(); if (context != null) { Thread.currentThread().setContextClassLoader(context.getApplicationContext().getClassLoader()); } } /** * Decodes byte buffer * @param state Protocol state * @param in Input byte buffer * @return Decoded object * @throws ProtocolException Exception during decoding */ public Object decode(ProtocolState state, ByteBuffer in) throws ProtocolException { int start = in.position(); try { final RTMP rtmp = (RTMP) state; switch (rtmp.getState()) { case RTMP.STATE_CONNECTED: return decodePacket(rtmp, in); case RTMP.STATE_ERROR: // attempt to correct error return null; case RTMP.STATE_CONNECT: case RTMP.STATE_HANDSHAKE: return decodeHandshake(rtmp, in); default: return null; } } catch (ProtocolException pe) { // Raise to caller unmodified throw pe; } catch (RuntimeException e) { log.error("Error in packet at " + start, e); throw new ProtocolException("Error during decoding"); } } /** * Decodes handshake message * @param rtmp RTMP protocol state * @param in Byte buffer * @return Byte buffer */ public ByteBuffer decodeHandshake(RTMP rtmp, ByteBuffer in) { final int remaining = in.remaining(); if (rtmp.getMode() == RTMP.MODE_SERVER) { if (rtmp.getState() == RTMP.STATE_CONNECT) { if (remaining < HANDSHAKE_SIZE + 1) { if (log.isDebugEnabled()) { log.debug("Handshake init too small, buffering. remaining: " + remaining); } rtmp.bufferDecoding(HANDSHAKE_SIZE + 1); return null; } else { final ByteBuffer hs = ByteBuffer.allocate(HANDSHAKE_SIZE); in.get(); // skip the header byte BufferUtils.put(hs, in, HANDSHAKE_SIZE); hs.flip(); rtmp.setState(RTMP.STATE_HANDSHAKE); return hs; } } if (rtmp.getState() == RTMP.STATE_HANDSHAKE) { if (log.isDebugEnabled()) { log.debug("Handshake reply"); } if (remaining < HANDSHAKE_SIZE) { if (log.isDebugEnabled()) { log.debug("Handshake reply too small, buffering. remaining: " + remaining); } rtmp.bufferDecoding(HANDSHAKE_SIZE); return null; } else { // Skip first 8 bytes when comparing the handshake, they seem to // be changed when connecting from a Mac client. if (!rtmp.validateHandshakeReply(in, 8, HANDSHAKE_SIZE-8)) { if (log.isDebugEnabled()) { log.debug("Handshake reply validation failed, disconnecting client."); } in.skip(HANDSHAKE_SIZE); rtmp.setState(RTMP.STATE_ERROR); throw new HandshakeFailedException("Handshake validation failed"); } in.skip(HANDSHAKE_SIZE); rtmp.setState(RTMP.STATE_CONNECTED); rtmp.continueDecoding(); return null; } } } else { // else, this is client mode. if (rtmp.getState() == RTMP.STATE_CONNECT) { final int size = (2 * HANDSHAKE_SIZE) + 1; if (remaining < size) { if (log.isDebugEnabled()) { log.debug("Handshake init too small, buffering. remaining: " + remaining); } rtmp.bufferDecoding(size); return null; } else { final ByteBuffer hs = ByteBuffer.allocate(size); BufferUtils.put(hs, in, size); hs.flip(); rtmp.setState(RTMP.STATE_CONNECTED); return hs; } } } return null; } /** * Decodes packet * @param rtmp RTMP protocol state * @param in Byte buffer * @return Byte buffer */ public Packet decodePacket(RTMP rtmp, ByteBuffer in) { final int remaining = in.remaining(); // We need at least one byte if (remaining < 1) { rtmp.bufferDecoding(1); return null; } final int position = in.position(); byte headerByte = in.get(); int headerValue; int byteCount; if ((headerByte & 0x3f) == 0) { // Two byte header + if (remaining < 2) { + in.position(position); + rtmp.bufferDecoding(2); + return null; + } headerValue = ((int) headerByte & 0xff) << 8 | ((int) in.get() & 0xff); byteCount = 2; } else if ((headerByte & 0x3f) == 1) { // Three byte header + if (remaining < 3) { + in.position(position); + rtmp.bufferDecoding(3); + return null; + } headerValue = ((int) headerByte & 0xff) << 16 | ((int) in.get() & 0xff) << 8 | ((int) in.get() & 0xff); byteCount = 3; } else { // Single byte header headerValue = (int) headerByte & 0xff; byteCount = 1; } final int channelId = RTMPUtils.decodeChannelId(headerValue, byteCount); if (channelId < 0) { throw new ProtocolException("Bad channel id: " + channelId); } // Get the header size and length int headerLength = RTMPUtils.getHeaderLength(RTMPUtils.decodeHeaderSize(headerValue, byteCount)); + headerLength += byteCount - 1; if (headerLength > remaining) { if (log.isDebugEnabled()) { log.debug("Header too small, buffering. remaining: " + remaining); } in.position(position); rtmp.bufferDecoding(headerLength); return null; } // Move the position back to the start in.position(position); final Header header = decodeHeader(in, rtmp .getLastReadHeader(channelId)); if (header == null) { throw new ProtocolException("Header is null, check for error"); } // Save the header rtmp.setLastReadHeader(channelId, header); // Check to see if this is a new packets or continue decoding an // existing one. Packet packet = rtmp.getLastReadPacket(channelId); if (packet == null) { packet = new Packet(header); rtmp.setLastReadPacket(channelId, packet); } final ByteBuffer buf = packet.getData(); final int addSize = (header.getTimer() == 0xffffff ? 4 : 0); final int readRemaining = header.getSize() + addSize - buf.position(); final int chunkSize = rtmp.getReadChunkSize(); final int readAmount = (readRemaining > chunkSize) ? chunkSize : readRemaining; if (in.remaining() < readAmount) { if (log.isDebugEnabled()) { log.debug("Chunk too small, buffering (" + in.remaining() + ',' + readAmount); } // skip the position back to the start in.position(position); rtmp.bufferDecoding(headerLength + readAmount); return null; } BufferUtils.put(buf, in, readAmount); if (buf.position() < header.getSize() + addSize) { rtmp.continueDecoding(); return null; } buf.flip(); final IRTMPEvent message = decodeMessage(rtmp, packet.getHeader(), buf); packet.setMessage(message); if (message instanceof ChunkSize) { ChunkSize chunkSizeMsg = (ChunkSize) message; rtmp.setReadChunkSize(chunkSizeMsg.getSize()); } rtmp.setLastReadPacket(channelId, null); return packet; } /** * Decides packet header * @param in Input byte buffer * @param lastHeader Previous header * @return Decoded header */ public Header decodeHeader(ByteBuffer in, Header lastHeader) { byte headerByte = in.get(); int headerValue; int byteCount = 1; if ((headerByte & 0x3f) == 0) { // Two byte header headerValue = ((int) headerByte & 0xff) << 8 | ((int) in.get() & 0xff); byteCount = 2; } else if ((headerByte & 0x3f) == 1) { // Three byte header headerValue = ((int) headerByte & 0xff) << 16 | ((int) in.get() & 0xff) << 8 | ((int) in.get() & 0xff); byteCount = 3; } else { // Single byte header headerValue = (int) headerByte & 0xff; byteCount = 1; } final int channelId = RTMPUtils.decodeChannelId(headerValue, byteCount); final int headerSize = RTMPUtils.decodeHeaderSize(headerValue, byteCount); Header header = new Header(); header.setChannelId(channelId); header.setTimerRelative(headerSize != HEADER_NEW); switch (headerSize) { case HEADER_NEW: header.setTimer(RTMPUtils.readUnsignedMediumInt(in)); header.setSize(RTMPUtils.readMediumInt(in)); header.setDataType(in.get()); header.setStreamId(RTMPUtils.readReverseInt(in)); break; case HEADER_SAME_SOURCE: header.setTimer(RTMPUtils.readUnsignedMediumInt(in)); header.setSize(RTMPUtils.readMediumInt(in)); header.setDataType(in.get()); header.setStreamId(lastHeader.getStreamId()); break; case HEADER_TIMER_CHANGE: header.setTimer(RTMPUtils.readUnsignedMediumInt(in)); header.setSize(lastHeader.getSize()); header.setDataType(lastHeader.getDataType()); header.setStreamId(lastHeader.getStreamId()); break; case HEADER_CONTINUE: header.setTimer(lastHeader.getTimer()); header.setSize(lastHeader.getSize()); header.setDataType(lastHeader.getDataType()); header.setStreamId(lastHeader.getStreamId()); break; default: log.error("Unexpected header size: " + headerSize); return null; } return header; } /** * Decodes RTMP message event * @param rtmp RTMP protocol state * @param header RTMP header * @param in Input byte buffer * @return RTMP event */ public IRTMPEvent decodeMessage(RTMP rtmp, Header header, ByteBuffer in) { IRTMPEvent message; if (header.getTimer() == 0xffffff) { // Skip first four bytes int unknown = in.getInt(); if (log.isDebugEnabled()) { log.debug("Unknown 4 bytes: " + unknown); } } switch (header.getDataType()) { case TYPE_CHUNK_SIZE: message = decodeChunkSize(in); break; case TYPE_INVOKE: message = decodeInvoke(in, rtmp); break; case TYPE_NOTIFY: if (header.getStreamId() == 0) message = decodeNotify(in, header, rtmp); else message = decodeStreamMetadata(in); break; case TYPE_PING: message = decodePing(in); break; case TYPE_BYTES_READ: message = decodeBytesRead(in); break; case TYPE_AUDIO_DATA: message = decodeAudioData(in); break; case TYPE_VIDEO_DATA: message = decodeVideoData(in); break; case TYPE_FLEX_SHARED_OBJECT: message = decodeFlexSharedObject(in, rtmp); break; case TYPE_SHARED_OBJECT: message = decodeSharedObject(in, rtmp); break; case TYPE_SERVER_BANDWIDTH: message = decodeServerBW(in); break; case TYPE_CLIENT_BANDWIDTH: message = decodeClientBW(in); break; case TYPE_FLEX_MESSAGE: message = decodeFlexMessage(in, rtmp); break; default: log.warn("Unknown object type: " + header.getDataType()); message = decodeUnknown(header.getDataType(), in); break; } message.setHeader(header); message.setTimestamp(header.getTimer()); return message; } /** * Decodes server bandwidth * @param in Byte buffer * @return RTMP event */ private IRTMPEvent decodeServerBW(ByteBuffer in) { return new ServerBW(in.getInt()); } /** * Decodes client bandwidth * @param in Byte buffer * @return RTMP event */ private IRTMPEvent decodeClientBW(ByteBuffer in) { return new ClientBW(in.getInt(), in.get()); } /** {@inheritDoc} */ public Unknown decodeUnknown(byte dataType, ByteBuffer in) { return new Unknown(dataType, in.asReadOnlyBuffer()); } /** {@inheritDoc} */ public ChunkSize decodeChunkSize(ByteBuffer in) { return new ChunkSize(in.getInt()); } /** {@inheritDoc} */ public ISharedObjectMessage decodeFlexSharedObject(ByteBuffer in, RTMP rtmp) { // Unknown byte, always 0? in.skip(1); final Input input = new org.red5.io.amf.Input(in); String name = input.getString(); // Read version of SO to modify int version = in.getInt(); // Read persistence informations boolean persistent = in.getInt() == 2; // Skip unknown bytes in.skip(4); final SharedObjectMessage so = new FlexSharedObjectMessage(null, name, version, persistent); doDecodeSharedObject(so, in, input); return so; } /** {@inheritDoc} */ public ISharedObjectMessage decodeSharedObject(ByteBuffer in, RTMP rtmp) { final Input input = new org.red5.io.amf.Input(in); String name = input.getString(); // Read version of SO to modify int version = in.getInt(); // Read persistence informations boolean persistent = in.getInt() == 2; // Skip unknown bytes in.skip(4); final SharedObjectMessage so = new FlexSharedObjectMessage(null, name, version, persistent); doDecodeSharedObject(so, in, input); return so; } /** * Perform the actual decoding of the shared object contents. * * @param so * @param in * @param rtmp */ protected void doDecodeSharedObject(SharedObjectMessage so, ByteBuffer in, Input input) { // Parse request body setupClassLoader(); while (in.hasRemaining()) { final ISharedObjectEvent.Type type = SharedObjectTypeMapping .toType(in.get()); String key = null; Object value = null; //if(log.isDebugEnabled()) // log.debug("type: "+SharedObjectTypeMapping.toString(type)); //SharedObjectEvent event = new SharedObjectEvent(,null,null); final int length = in.getInt(); if (type == ISharedObjectEvent.Type.CLIENT_STATUS) { // Status code key = input.getString(); // Status level value = input.getString(); } else if (type == ISharedObjectEvent.Type.CLIENT_UPDATE_DATA) { key = null; // Map containing new attribute values final Map<String, Object> map = new HashMap<String, Object>(); final int start = in.position(); while (in.position() - start < length) { String tmp = input.getString(); map.put(tmp, deserializer.deserialize(input)); } value = map; } else if (type != ISharedObjectEvent.Type.SERVER_SEND_MESSAGE && type != ISharedObjectEvent.Type.CLIENT_SEND_MESSAGE) { if (length > 0) { key = input.getString(); if (length > key.length() + 2) { value = deserializer.deserialize(input); } } } else { final int start = in.position(); // the "send" event seems to encode the handler name // as complete AMF string including the string type byte key = (String) deserializer.deserialize(input); // read parameters final List<Object> list = new LinkedList<Object>(); while (in.position() - start < length) { Object tmp = deserializer.deserialize(input); list.add(tmp); } value = list; } so.addEvent(type, key, value); } } /** {@inheritDoc} */ public Notify decodeNotify(ByteBuffer in, RTMP rtmp) { return decodeNotify(in, null, rtmp); } public Notify decodeNotify(ByteBuffer in, Header header, RTMP rtmp) { return decodeNotifyOrInvoke(new Notify(), in, header, rtmp); } /** {@inheritDoc} */ public Invoke decodeInvoke(ByteBuffer in, RTMP rtmp) { return (Invoke) decodeNotifyOrInvoke(new Invoke(), in, null, rtmp); } /** * Checks if the passed action is a reserved stream method. * * @param action Action to check * @return <code>true</code> if passed action is a reserved stream method, <code>false</code> otherwise */ private boolean isStreamCommand(String action) { return (ACTION_CREATE_STREAM.equals(action) || ACTION_DELETE_STREAM.equals(action) || ACTION_PUBLISH.equals(action) || ACTION_PLAY.equals(action) || ACTION_SEEK.equals(action) || ACTION_PAUSE.equals(action) || ACTION_CLOSE_STREAM.equals(action) || ACTION_RECEIVE_VIDEO.equals(action) || ACTION_RECEIVE_AUDIO .equals(action)); } /** * Decodes notification event * @param notify Notify event * @param in Byte buffer * @param header Header * @param rtmp RTMP protocol state * @return Notification event */ protected Notify decodeNotifyOrInvoke(Notify notify, ByteBuffer in, Header header, RTMP rtmp) { // TODO: we should use different code depending on server or client mode int start = in.position(); Input input; if (rtmp.getEncoding() == Encoding.AMF3) input = new org.red5.io.amf3.Input(in); else input = new org.red5.io.amf.Input(in); String action = (String) deserializer.deserialize(input); if (!(notify instanceof Invoke) && rtmp != null && rtmp.getMode() == RTMP.MODE_SERVER && header != null && header.getStreamId() != 0 && !isStreamCommand(action)) { // Don't decode "NetStream.send" requests in.position(start); notify.setData(in.asReadOnlyBuffer()); return notify; } if (log.isDebugEnabled()) { log.debug("Action " + action); } if (header == null || header.getStreamId() == 0) { int invokeId = ((Number) deserializer.deserialize(input)).intValue(); notify.setInvokeId(invokeId); } Object[] params = new Object[] {}; if (in.hasRemaining()) { setupClassLoader(); List<Object> paramList = new ArrayList<Object>(); final Object obj = deserializer.deserialize(input); if (obj instanceof Map) { // Before the actual parameters we sometimes (connect) get a map // of parameters, this is usually null, but if set should be // passed to the connection object. final Map connParams = (Map) obj; notify.setConnectionParams(connParams); } else if (obj != null) { paramList.add(obj); } while (in.hasRemaining()) { paramList.add(deserializer.deserialize(input)); } params = paramList.toArray(); if (log.isDebugEnabled()) { log.debug("Num params: " + paramList.size()); for (int i = 0; i < params.length; i++) { log.debug(" > " + i + ": " + params[i]); } } } final int dotIndex = action.lastIndexOf('.'); String serviceName = (dotIndex == -1) ? null : action.substring(0, dotIndex); String serviceMethod = (dotIndex == -1) ? action : action.substring( dotIndex + 1, action.length()); if (notify instanceof Invoke) { PendingCall call = new PendingCall(serviceName, serviceMethod, params); ((Invoke) notify).setCall(call); } else { Call call = new Call(serviceName, serviceMethod, params); notify.setCall(call); } return notify; } /** * Decodes ping event * @param in Byte buffer * @return Ping event */ public Ping decodePing(ByteBuffer in) { final Ping ping = new Ping(); ping.setDebug(in.getHexDump()); ping.setValue1(in.getShort()); ping.setValue2(in.getInt()); if (in.hasRemaining()) { ping.setValue3(in.getInt()); } if (in.hasRemaining()) { ping.setValue4(in.getInt()); } return ping; } /** {@inheritDoc} */ public BytesRead decodeBytesRead(ByteBuffer in) { return new BytesRead(in.getInt()); } /** {@inheritDoc} */ public AudioData decodeAudioData(ByteBuffer in) { return new AudioData(in.asReadOnlyBuffer()); } /** {@inheritDoc} */ public VideoData decodeVideoData(ByteBuffer in) { return new VideoData(in.asReadOnlyBuffer()); } public Notify decodeStreamMetadata(ByteBuffer in) { return new Notify(in.asReadOnlyBuffer()); } /** * Decodes FlexMessage event * @param in Byte buffer * @param rtmp RTMP protocol state * @return FlexMessage event */ public FlexMessage decodeFlexMessage(ByteBuffer in, RTMP rtmp) { // Unknown byte, always 0? in.skip(1); Input input = new org.red5.io.amf.Input(in); String action = (String) deserializer.deserialize(input); int invokeId = ((Number) deserializer.deserialize(input)).intValue(); FlexMessage msg = new FlexMessage(); msg.setInvokeId(invokeId); Object[] params = new Object[] {}; if (in.hasRemaining()) { setupClassLoader(); ArrayList<Object> paramList = new ArrayList<Object>(); final Object obj = deserializer.deserialize(input); if (obj != null) { paramList.add(obj); } while (in.hasRemaining()) { // Check for AMF3 encoding of parameters byte tmp = in.get(); in.position(in.position()-1); if (tmp == AMF.TYPE_AMF3_OBJECT) { // The next parameter is encoded using AMF3 input = new org.red5.io.amf3.Input(in); } else { // The next parameter is encoded using AMF0 input = new org.red5.io.amf.Input(in); } paramList.add(deserializer.deserialize(input)); } params = paramList.toArray(); if (log.isDebugEnabled()) { log.debug("Num params: " + paramList.size()); for (int i = 0; i < params.length; i++) { log.debug(" > " + i + ": " + params[i]); } } } final int dotIndex = action.lastIndexOf('.'); String serviceName = (dotIndex == -1) ? null : action.substring(0, dotIndex); String serviceMethod = (dotIndex == -1) ? action : action.substring( dotIndex + 1, action.length()); PendingCall call = new PendingCall(serviceName, serviceMethod, params); msg.setCall(call); return msg; } }
false
true
public Packet decodePacket(RTMP rtmp, ByteBuffer in) { final int remaining = in.remaining(); // We need at least one byte if (remaining < 1) { rtmp.bufferDecoding(1); return null; } final int position = in.position(); byte headerByte = in.get(); int headerValue; int byteCount; if ((headerByte & 0x3f) == 0) { // Two byte header headerValue = ((int) headerByte & 0xff) << 8 | ((int) in.get() & 0xff); byteCount = 2; } else if ((headerByte & 0x3f) == 1) { // Three byte header headerValue = ((int) headerByte & 0xff) << 16 | ((int) in.get() & 0xff) << 8 | ((int) in.get() & 0xff); byteCount = 3; } else { // Single byte header headerValue = (int) headerByte & 0xff; byteCount = 1; } final int channelId = RTMPUtils.decodeChannelId(headerValue, byteCount); if (channelId < 0) { throw new ProtocolException("Bad channel id: " + channelId); } // Get the header size and length int headerLength = RTMPUtils.getHeaderLength(RTMPUtils.decodeHeaderSize(headerValue, byteCount)); if (headerLength > remaining) { if (log.isDebugEnabled()) { log.debug("Header too small, buffering. remaining: " + remaining); } in.position(position); rtmp.bufferDecoding(headerLength); return null; } // Move the position back to the start in.position(position); final Header header = decodeHeader(in, rtmp .getLastReadHeader(channelId)); if (header == null) { throw new ProtocolException("Header is null, check for error"); } // Save the header rtmp.setLastReadHeader(channelId, header); // Check to see if this is a new packets or continue decoding an // existing one. Packet packet = rtmp.getLastReadPacket(channelId); if (packet == null) { packet = new Packet(header); rtmp.setLastReadPacket(channelId, packet); } final ByteBuffer buf = packet.getData(); final int addSize = (header.getTimer() == 0xffffff ? 4 : 0); final int readRemaining = header.getSize() + addSize - buf.position(); final int chunkSize = rtmp.getReadChunkSize(); final int readAmount = (readRemaining > chunkSize) ? chunkSize : readRemaining; if (in.remaining() < readAmount) { if (log.isDebugEnabled()) { log.debug("Chunk too small, buffering (" + in.remaining() + ',' + readAmount); } // skip the position back to the start in.position(position); rtmp.bufferDecoding(headerLength + readAmount); return null; } BufferUtils.put(buf, in, readAmount); if (buf.position() < header.getSize() + addSize) { rtmp.continueDecoding(); return null; } buf.flip(); final IRTMPEvent message = decodeMessage(rtmp, packet.getHeader(), buf); packet.setMessage(message); if (message instanceof ChunkSize) { ChunkSize chunkSizeMsg = (ChunkSize) message; rtmp.setReadChunkSize(chunkSizeMsg.getSize()); } rtmp.setLastReadPacket(channelId, null); return packet; }
public Packet decodePacket(RTMP rtmp, ByteBuffer in) { final int remaining = in.remaining(); // We need at least one byte if (remaining < 1) { rtmp.bufferDecoding(1); return null; } final int position = in.position(); byte headerByte = in.get(); int headerValue; int byteCount; if ((headerByte & 0x3f) == 0) { // Two byte header if (remaining < 2) { in.position(position); rtmp.bufferDecoding(2); return null; } headerValue = ((int) headerByte & 0xff) << 8 | ((int) in.get() & 0xff); byteCount = 2; } else if ((headerByte & 0x3f) == 1) { // Three byte header if (remaining < 3) { in.position(position); rtmp.bufferDecoding(3); return null; } headerValue = ((int) headerByte & 0xff) << 16 | ((int) in.get() & 0xff) << 8 | ((int) in.get() & 0xff); byteCount = 3; } else { // Single byte header headerValue = (int) headerByte & 0xff; byteCount = 1; } final int channelId = RTMPUtils.decodeChannelId(headerValue, byteCount); if (channelId < 0) { throw new ProtocolException("Bad channel id: " + channelId); } // Get the header size and length int headerLength = RTMPUtils.getHeaderLength(RTMPUtils.decodeHeaderSize(headerValue, byteCount)); headerLength += byteCount - 1; if (headerLength > remaining) { if (log.isDebugEnabled()) { log.debug("Header too small, buffering. remaining: " + remaining); } in.position(position); rtmp.bufferDecoding(headerLength); return null; } // Move the position back to the start in.position(position); final Header header = decodeHeader(in, rtmp .getLastReadHeader(channelId)); if (header == null) { throw new ProtocolException("Header is null, check for error"); } // Save the header rtmp.setLastReadHeader(channelId, header); // Check to see if this is a new packets or continue decoding an // existing one. Packet packet = rtmp.getLastReadPacket(channelId); if (packet == null) { packet = new Packet(header); rtmp.setLastReadPacket(channelId, packet); } final ByteBuffer buf = packet.getData(); final int addSize = (header.getTimer() == 0xffffff ? 4 : 0); final int readRemaining = header.getSize() + addSize - buf.position(); final int chunkSize = rtmp.getReadChunkSize(); final int readAmount = (readRemaining > chunkSize) ? chunkSize : readRemaining; if (in.remaining() < readAmount) { if (log.isDebugEnabled()) { log.debug("Chunk too small, buffering (" + in.remaining() + ',' + readAmount); } // skip the position back to the start in.position(position); rtmp.bufferDecoding(headerLength + readAmount); return null; } BufferUtils.put(buf, in, readAmount); if (buf.position() < header.getSize() + addSize) { rtmp.continueDecoding(); return null; } buf.flip(); final IRTMPEvent message = decodeMessage(rtmp, packet.getHeader(), buf); packet.setMessage(message); if (message instanceof ChunkSize) { ChunkSize chunkSizeMsg = (ChunkSize) message; rtmp.setReadChunkSize(chunkSizeMsg.getSize()); } rtmp.setLastReadPacket(channelId, null); return packet; }
diff --git a/src/main/java/be/redlab/jaxb/swagger/SwaggerAnnotationsJaxbPlugin.java b/src/main/java/be/redlab/jaxb/swagger/SwaggerAnnotationsJaxbPlugin.java index 4da559e..cdebb37 100644 --- a/src/main/java/be/redlab/jaxb/swagger/SwaggerAnnotationsJaxbPlugin.java +++ b/src/main/java/be/redlab/jaxb/swagger/SwaggerAnnotationsJaxbPlugin.java @@ -1,136 +1,136 @@ /* * Copyright 2013 Balder Van Camp * * 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 be.redlab.jaxb.swagger; import java.io.StringWriter; import java.util.Collection; import java.util.Map; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.sun.codemodel.JAnnotationUse; import com.sun.codemodel.JAnnotationValue; import com.sun.codemodel.JFormatter; import com.sun.codemodel.JMethod; import com.sun.tools.xjc.Options; import com.sun.tools.xjc.Plugin; import com.sun.tools.xjc.outline.ClassOutline; import com.sun.tools.xjc.outline.Outline; import com.wordnik.swagger.annotations.ApiClass; import com.wordnik.swagger.annotations.ApiProperty; /** * @author redlab * */ public class SwaggerAnnotationsJaxbPlugin extends Plugin { private static final String SWAGGERIFY = "swaggerify"; private static final String USAGE = "Add this plugin to the JAXB classes generator classpath and provide the argument '-swaggerify'."; /* * (non-Javadoc) * * @see com.sun.tools.xjc.Plugin#getOptionName() */ @Override public String getOptionName() { return SWAGGERIFY; } /* * (non-Javadoc) * * @see com.sun.tools.xjc.Plugin#getUsage() */ @Override public String getUsage() { return USAGE; } /* * (non-Javadoc) * * @see com.sun.tools.xjc.Plugin#run(com.sun.tools.xjc.outline.Outline, com.sun.tools.xjc.Options, * org.xml.sax.ErrorHandler) * * Api Annotations Info * String value() default ""; * String allowableValues() default "";endIndex * String access() default ""; * String notes() default ""; * String dataType() default ""; * boolean required() default false; */ @Override public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException { Collection<? extends ClassOutline> classes = outline.getClasses(); for (ClassOutline o : classes) { if (o.implClass.isClass() && !o.implClass.isAbstract() && !o.implClass.isInterface() && !o.implClass.isAnnotationTypeDeclaration()) { JAnnotationUse annotate2 = o.implClass.annotate(ApiClass.class); annotate2.param("value", o.ref.name()); annotate2.param("description", new StringBuilder(o.ref.fullName()) .append(" description generated by jaxb-swagger, hence no class description yet.").toString()); for (JMethod m : o.implClass.methods()) { if (m.name().startsWith("get") && m.name().length() > 3) { JAnnotationUse annotate = m.annotate(ApiProperty.class); - String name = m.name(); - annotate.param("value", prepareNameFromGetter(name)); + String name = prepareNameFromGetter(m.name()); + annotate.param("value", name); String dataType = DataTypeDeterminationUtil.determineDataType(m.type()); if (dataType != null) { annotate.param("dataType", dataType); } Collection<JAnnotationUse> fieldAnnotations = o.implClass.fields() .get(name.substring(0, 1).toLowerCase() + name.substring(1)).annotations(); for (JAnnotationUse jau : fieldAnnotations) { if (jau.getAnnotationClass().name().equals("XmlElement")) { Map<String, JAnnotationValue> members = jau.getAnnotationMembers(); JAnnotationValue value = members.get("defaultValue"); if (null != value) { StringWriter w2 = new StringWriter(); JFormatter f = new JFormatter(w2); value.generate(f); annotate.param("notes", w2.toString()); } value = members.get("required"); if (null != value) { annotate.param("required", true); } else { annotate.param("required", false); } } } } } } else { errorHandler.warning(new SAXParseException(String.format("Skipping %s as it is not an implementation or class", o), null)); } } return true; } protected String prepareNameFromGetter(final String getterName) { String name = getterName.substring(3); StringBuilder b = new StringBuilder(); b.append(Character.toLowerCase(name.charAt(0))); if (name.length() > 1) { b.append(name.substring(1)); } return b.toString(); } }
true
true
public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException { Collection<? extends ClassOutline> classes = outline.getClasses(); for (ClassOutline o : classes) { if (o.implClass.isClass() && !o.implClass.isAbstract() && !o.implClass.isInterface() && !o.implClass.isAnnotationTypeDeclaration()) { JAnnotationUse annotate2 = o.implClass.annotate(ApiClass.class); annotate2.param("value", o.ref.name()); annotate2.param("description", new StringBuilder(o.ref.fullName()) .append(" description generated by jaxb-swagger, hence no class description yet.").toString()); for (JMethod m : o.implClass.methods()) { if (m.name().startsWith("get") && m.name().length() > 3) { JAnnotationUse annotate = m.annotate(ApiProperty.class); String name = m.name(); annotate.param("value", prepareNameFromGetter(name)); String dataType = DataTypeDeterminationUtil.determineDataType(m.type()); if (dataType != null) { annotate.param("dataType", dataType); } Collection<JAnnotationUse> fieldAnnotations = o.implClass.fields() .get(name.substring(0, 1).toLowerCase() + name.substring(1)).annotations(); for (JAnnotationUse jau : fieldAnnotations) { if (jau.getAnnotationClass().name().equals("XmlElement")) { Map<String, JAnnotationValue> members = jau.getAnnotationMembers(); JAnnotationValue value = members.get("defaultValue"); if (null != value) { StringWriter w2 = new StringWriter(); JFormatter f = new JFormatter(w2); value.generate(f); annotate.param("notes", w2.toString()); } value = members.get("required"); if (null != value) { annotate.param("required", true); } else { annotate.param("required", false); } } } } } } else { errorHandler.warning(new SAXParseException(String.format("Skipping %s as it is not an implementation or class", o), null)); } } return true; }
public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException { Collection<? extends ClassOutline> classes = outline.getClasses(); for (ClassOutline o : classes) { if (o.implClass.isClass() && !o.implClass.isAbstract() && !o.implClass.isInterface() && !o.implClass.isAnnotationTypeDeclaration()) { JAnnotationUse annotate2 = o.implClass.annotate(ApiClass.class); annotate2.param("value", o.ref.name()); annotate2.param("description", new StringBuilder(o.ref.fullName()) .append(" description generated by jaxb-swagger, hence no class description yet.").toString()); for (JMethod m : o.implClass.methods()) { if (m.name().startsWith("get") && m.name().length() > 3) { JAnnotationUse annotate = m.annotate(ApiProperty.class); String name = prepareNameFromGetter(m.name()); annotate.param("value", name); String dataType = DataTypeDeterminationUtil.determineDataType(m.type()); if (dataType != null) { annotate.param("dataType", dataType); } Collection<JAnnotationUse> fieldAnnotations = o.implClass.fields() .get(name.substring(0, 1).toLowerCase() + name.substring(1)).annotations(); for (JAnnotationUse jau : fieldAnnotations) { if (jau.getAnnotationClass().name().equals("XmlElement")) { Map<String, JAnnotationValue> members = jau.getAnnotationMembers(); JAnnotationValue value = members.get("defaultValue"); if (null != value) { StringWriter w2 = new StringWriter(); JFormatter f = new JFormatter(w2); value.generate(f); annotate.param("notes", w2.toString()); } value = members.get("required"); if (null != value) { annotate.param("required", true); } else { annotate.param("required", false); } } } } } } else { errorHandler.warning(new SAXParseException(String.format("Skipping %s as it is not an implementation or class", o), null)); } } return true; }
diff --git a/src/test/java/com/ning/atlas/TestJRubyTemplateParser.java b/src/test/java/com/ning/atlas/TestJRubyTemplateParser.java index 8ab5f58..796a175 100644 --- a/src/test/java/com/ning/atlas/TestJRubyTemplateParser.java +++ b/src/test/java/com/ning/atlas/TestJRubyTemplateParser.java @@ -1,175 +1,177 @@ package com.ning.atlas; import com.google.common.collect.Iterables; import com.ning.atlas.spi.Maybe; import com.ning.atlas.base.MorePredicates; import com.ning.atlas.space.InMemorySpace; import com.ning.atlas.spi.Identity; import com.ning.atlas.spi.Installer; import com.ning.atlas.spi.My; import com.ning.atlas.spi.space.Space; import com.ning.atlas.spi.Uri; import com.ning.atlas.tree.Trees; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.util.Collections; import java.util.List; import static com.ning.atlas.base.MorePredicates.beanPropertyEquals; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; public class TestJRubyTemplateParser { public static final JsonFactory factory = new JsonFactory(new ObjectMapper()); @Test public void testSimpleSystem() throws Exception { JRubyTemplateParser p = new JRubyTemplateParser(); Template t = p.parseSystem(new File("src/test/ruby/ex1/system-template.rb")); assertThat(t, notNullValue()); List<Template> leaves = Trees.leaves(t); assertThat(leaves.size(), equalTo(7)); Template rslv_t = Iterables.find(leaves, beanPropertyEquals("type", "resolver")); assertThat(rslv_t, instanceOf(ServerTemplate.class)); ServerTemplate rslv = (ServerTemplate) rslv_t; assertThat(rslv.getCardinality(), equalTo(asList("0", "1", "2", "3", "4", "5", "6", "7"))); assertThat(rslv.getBase(), equalTo("ubuntu-small")); assertThat(rslv.getInstallations(), hasItem(Uri.<Installer>valueOf("cast:load-balancer-9.3"))); } @Test @Ignore public void testJson() throws Exception { JRubyTemplateParser p = new JRubyTemplateParser(); Template t = p.parseSystem(new File("src/test/ruby/ex1/system-template.rb")); SystemMap map = t.normalize(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); mapper.writeValue(System.out, map.getSingleRoot()); } @Test public void testCardinalityAsArray() throws Exception { JRubyTemplateParser p = new JRubyTemplateParser(); Template t = p.parseSystem(new File("src/test/ruby/ex1/system-template.rb")); assertThat(t, notNullValue()); List<Template> rs = Trees.find(t, MorePredicates.<Template>beanPropertyEquals("type", "aclu")); assertThat(rs.size(), equalTo(1)); assertThat(rs.get(0), instanceOf(SystemTemplate.class)); SystemTemplate aclu = (SystemTemplate) rs.get(0); assertThat(aclu.getCardinality(), equalTo(asList("aclu0", "aclu1"))); } @Test public void testMyAttributesPopulated() throws Exception { JRubyTemplateParser p = new JRubyTemplateParser(); Template t = p.parseSystem(new File("src/test/ruby/ex1/system-template.rb")); List<Template> leaves = Trees.leaves(t); Template appc = Iterables.find(leaves, beanPropertyEquals("type", "appcore")); My my = appc.getMy(); JsonNode json = factory.createJsonParser(my.toJson()).readValueAsTree(); assertThat(json.get("waffle").getIntValue(), equalTo(7)); JsonNode r = json.get("xn.raspberry"); assertThat(r.get(0).getIntValue(), equalTo(1)); assertThat(r.get(1).getIntValue(), equalTo(2)); assertThat(r.get(2).getIntValue(), equalTo(3)); } @Test public void testSimpleEnvironment() throws Exception { JRubyTemplateParser p = new JRubyTemplateParser(); Environment e = p.parseEnvironment(new File("src/test/ruby/ex1/simple-environment.rb")); Maybe<Base> cs = e.findBase("concrete"); assertThat(cs.getValue(), notNullValue()); Base b = cs.getValue(); Uri<Installer> u = Uri.valueOf("chef-solo:{ \"run_list\": \"role[java-core]\" }"); assertThat(b.getInitializations(), equalTo(asList(u))); } @Test public void testParameterizedInstallersPopulated() throws Exception { JRubyTemplateParser p = new JRubyTemplateParser(); Template t = p.parseSystem(new File("src/test/ruby/ex1/system-template.rb")); ServerTemplate st = Iterables.find(Trees.findInstancesOf(t, ServerTemplate.class), MorePredicates.<ServerTemplate>beanPropertyEquals("type", "single-param-install")); List<Uri<Installer>> xs = st.getInstallations(); assertThat(xs, equalTo(asList(Uri.<Installer>valueOf("foo:bar?size=7")))); } @Test public void testInstallers2() throws Exception { JRubyTemplateParser p = new JRubyTemplateParser(); Template t = p.parseSystem(new File("src/test/ruby/ex1/system-template.rb")); ServerTemplate st = Iterables.find(Trees.findInstancesOf(t, ServerTemplate.class), MorePredicates.<ServerTemplate>beanPropertyEquals("type", "single-param-install2")); List<Uri<Installer>> xs = st.getInstallations(); assertThat(xs, equalTo(asList(Uri.<Installer>valueOf("foo:bar?size=7")))); } @Test public void testInstallers3() throws Exception { JRubyTemplateParser p = new JRubyTemplateParser(); Template t = p.parseSystem(new File("src/test/ruby/ex1/system-template.rb")); ServerTemplate st = Iterables.find(Trees.findInstancesOf(t, ServerTemplate.class), MorePredicates.<ServerTemplate>beanPropertyEquals("type", "single-param-install4")); List<Uri<Installer>> xs = st.getInstallations(); assertThat(xs, equalTo(asList(Uri.<Installer>valueOf("hello:world")))); } @Test public void testEnvironmentWithListener() throws Exception { ListenerThing.calls.clear(); JRubyTemplateParser p = new JRubyTemplateParser(); Environment env = p.parseEnvironment(new File("src/test/ruby/ex1/env-with-listener.rb")); Host h = new Host(Identity.root().createChild("some", "thing"), "concrete", new My(), Collections.<Uri<Installer>>emptyList()); SystemMap map = new SystemMap(h); Space space = InMemorySpace.newInstance(); ActualDeployment d = new ActualDeployment(map, env, space); d.perform(); assertThat(ListenerThing.calls, equalTo(asList("startDeployment", "startProvision", "finishProvision", "startInit", "finishInit", "startInstall", "finishInstall", + "startUnwind", + "finishUnwind", "finishDeployment"))); } }
true
true
public void testEnvironmentWithListener() throws Exception { ListenerThing.calls.clear(); JRubyTemplateParser p = new JRubyTemplateParser(); Environment env = p.parseEnvironment(new File("src/test/ruby/ex1/env-with-listener.rb")); Host h = new Host(Identity.root().createChild("some", "thing"), "concrete", new My(), Collections.<Uri<Installer>>emptyList()); SystemMap map = new SystemMap(h); Space space = InMemorySpace.newInstance(); ActualDeployment d = new ActualDeployment(map, env, space); d.perform(); assertThat(ListenerThing.calls, equalTo(asList("startDeployment", "startProvision", "finishProvision", "startInit", "finishInit", "startInstall", "finishInstall", "finishDeployment"))); }
public void testEnvironmentWithListener() throws Exception { ListenerThing.calls.clear(); JRubyTemplateParser p = new JRubyTemplateParser(); Environment env = p.parseEnvironment(new File("src/test/ruby/ex1/env-with-listener.rb")); Host h = new Host(Identity.root().createChild("some", "thing"), "concrete", new My(), Collections.<Uri<Installer>>emptyList()); SystemMap map = new SystemMap(h); Space space = InMemorySpace.newInstance(); ActualDeployment d = new ActualDeployment(map, env, space); d.perform(); assertThat(ListenerThing.calls, equalTo(asList("startDeployment", "startProvision", "finishProvision", "startInit", "finishInit", "startInstall", "finishInstall", "startUnwind", "finishUnwind", "finishDeployment"))); }
diff --git a/sdk-common/src/main/java/com/android/ide/common/resources/configuration/DeviceConfigHelper.java b/sdk-common/src/main/java/com/android/ide/common/resources/configuration/DeviceConfigHelper.java index 27eaa01..98cb979 100644 --- a/sdk-common/src/main/java/com/android/ide/common/resources/configuration/DeviceConfigHelper.java +++ b/sdk-common/src/main/java/com/android/ide/common/resources/configuration/DeviceConfigHelper.java @@ -1,112 +1,113 @@ /* * Copyright (C) 2012 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.ide.common.resources.configuration; import com.android.annotations.Nullable; import com.android.resources.NightMode; import com.android.resources.UiMode; import com.android.sdklib.devices.Device; import com.android.sdklib.devices.Hardware; import com.android.sdklib.devices.Screen; import com.android.sdklib.devices.State; public class DeviceConfigHelper { /** * Returns a {@link FolderConfiguration} based on the given state * * @param state * The {@link State} of the {@link Device} to base the * {@link FolderConfiguration} on. Can be null. * @return A {@link FolderConfiguration} based on the given {@link State}. * If the given {@link State} is null, the result is also null; */ @Nullable public static FolderConfiguration getFolderConfig(@Nullable State state) { if (state == null) { return null; } Hardware hw = state.getHardware(); FolderConfiguration config = new FolderConfiguration(); config.createDefault(); Screen screen = hw.getScreen(); config.setDensityQualifier(new DensityQualifier(screen.getPixelDensity())); config.setNavigationMethodQualifier(new NavigationMethodQualifier(hw.getNav())); ScreenDimensionQualifier sdq; if (screen.getXDimension() > screen.getYDimension()) { sdq = new ScreenDimensionQualifier(screen.getXDimension(), screen.getYDimension()); } else { sdq = new ScreenDimensionQualifier(screen.getYDimension(), screen.getXDimension()); } config.setScreenDimensionQualifier(sdq); config.setScreenRatioQualifier(new ScreenRatioQualifier(screen.getRatio())); config.setScreenSizeQualifier(new ScreenSizeQualifier(screen.getSize())); config.setTextInputMethodQualifier(new TextInputMethodQualifier(hw.getKeyboard())); config.setTouchTypeQualifier(new TouchScreenQualifier(screen.getMechanism())); config.setKeyboardStateQualifier(new KeyboardStateQualifier(state.getKeyState())); config.setNavigationStateQualifier(new NavigationStateQualifier(state.getNavState())); config.setScreenOrientationQualifier( new ScreenOrientationQualifier(state.getOrientation())); config.updateScreenWidthAndHeight(); // Setup some default qualifiers config.setUiModeQualifier(new UiModeQualifier(UiMode.NORMAL)); config.setNightModeQualifier(new NightModeQualifier(NightMode.NOTNIGHT)); config.setCountryCodeQualifier(new CountryCodeQualifier()); config.setLanguageQualifier(new LanguageQualifier()); + config.setLayoutDirectionQualifier(new LayoutDirectionQualifier()); config.setNetworkCodeQualifier(new NetworkCodeQualifier()); config.setRegionQualifier(new RegionQualifier()); config.setVersionQualifier(new VersionQualifier()); return config; } /** * Returns a {@link FolderConfiguration} based on the {@link State} given by * the {@link Device} and the state name. * * @param d * The {@link Device} to base the {@link FolderConfiguration} on. * @param stateName * The name of the state to base the {@link FolderConfiguration} * on. * @return The {@link FolderConfiguration} based on the determined * {@link State}. If there is no {@link State} with the given state * name for the given device, null is returned. */ @Nullable public static FolderConfiguration getFolderConfig(Device d, String stateName) { return getFolderConfig(d.getState(stateName)); } /** * Returns a {@link FolderConfiguration} based on the default {@link State} * for the given {@link Device}. * * @param d * The {@link Device} to generate the {@link FolderConfiguration} * from. * @return A {@link FolderConfiguration} based on the default {@link State} * for the given {@link Device} */ public static FolderConfiguration getFolderConfig(Device d) { return getFolderConfig(d.getDefaultState()); } }
true
true
public static FolderConfiguration getFolderConfig(@Nullable State state) { if (state == null) { return null; } Hardware hw = state.getHardware(); FolderConfiguration config = new FolderConfiguration(); config.createDefault(); Screen screen = hw.getScreen(); config.setDensityQualifier(new DensityQualifier(screen.getPixelDensity())); config.setNavigationMethodQualifier(new NavigationMethodQualifier(hw.getNav())); ScreenDimensionQualifier sdq; if (screen.getXDimension() > screen.getYDimension()) { sdq = new ScreenDimensionQualifier(screen.getXDimension(), screen.getYDimension()); } else { sdq = new ScreenDimensionQualifier(screen.getYDimension(), screen.getXDimension()); } config.setScreenDimensionQualifier(sdq); config.setScreenRatioQualifier(new ScreenRatioQualifier(screen.getRatio())); config.setScreenSizeQualifier(new ScreenSizeQualifier(screen.getSize())); config.setTextInputMethodQualifier(new TextInputMethodQualifier(hw.getKeyboard())); config.setTouchTypeQualifier(new TouchScreenQualifier(screen.getMechanism())); config.setKeyboardStateQualifier(new KeyboardStateQualifier(state.getKeyState())); config.setNavigationStateQualifier(new NavigationStateQualifier(state.getNavState())); config.setScreenOrientationQualifier( new ScreenOrientationQualifier(state.getOrientation())); config.updateScreenWidthAndHeight(); // Setup some default qualifiers config.setUiModeQualifier(new UiModeQualifier(UiMode.NORMAL)); config.setNightModeQualifier(new NightModeQualifier(NightMode.NOTNIGHT)); config.setCountryCodeQualifier(new CountryCodeQualifier()); config.setLanguageQualifier(new LanguageQualifier()); config.setNetworkCodeQualifier(new NetworkCodeQualifier()); config.setRegionQualifier(new RegionQualifier()); config.setVersionQualifier(new VersionQualifier()); return config; }
public static FolderConfiguration getFolderConfig(@Nullable State state) { if (state == null) { return null; } Hardware hw = state.getHardware(); FolderConfiguration config = new FolderConfiguration(); config.createDefault(); Screen screen = hw.getScreen(); config.setDensityQualifier(new DensityQualifier(screen.getPixelDensity())); config.setNavigationMethodQualifier(new NavigationMethodQualifier(hw.getNav())); ScreenDimensionQualifier sdq; if (screen.getXDimension() > screen.getYDimension()) { sdq = new ScreenDimensionQualifier(screen.getXDimension(), screen.getYDimension()); } else { sdq = new ScreenDimensionQualifier(screen.getYDimension(), screen.getXDimension()); } config.setScreenDimensionQualifier(sdq); config.setScreenRatioQualifier(new ScreenRatioQualifier(screen.getRatio())); config.setScreenSizeQualifier(new ScreenSizeQualifier(screen.getSize())); config.setTextInputMethodQualifier(new TextInputMethodQualifier(hw.getKeyboard())); config.setTouchTypeQualifier(new TouchScreenQualifier(screen.getMechanism())); config.setKeyboardStateQualifier(new KeyboardStateQualifier(state.getKeyState())); config.setNavigationStateQualifier(new NavigationStateQualifier(state.getNavState())); config.setScreenOrientationQualifier( new ScreenOrientationQualifier(state.getOrientation())); config.updateScreenWidthAndHeight(); // Setup some default qualifiers config.setUiModeQualifier(new UiModeQualifier(UiMode.NORMAL)); config.setNightModeQualifier(new NightModeQualifier(NightMode.NOTNIGHT)); config.setCountryCodeQualifier(new CountryCodeQualifier()); config.setLanguageQualifier(new LanguageQualifier()); config.setLayoutDirectionQualifier(new LayoutDirectionQualifier()); config.setNetworkCodeQualifier(new NetworkCodeQualifier()); config.setRegionQualifier(new RegionQualifier()); config.setVersionQualifier(new VersionQualifier()); return config; }
diff --git a/xmppbot-core/src/main/java/de/raion/xmppbot/XmppBot.java b/xmppbot-core/src/main/java/de/raion/xmppbot/XmppBot.java index f7043fc..96173cf 100644 --- a/xmppbot-core/src/main/java/de/raion/xmppbot/XmppBot.java +++ b/xmppbot-core/src/main/java/de/raion/xmppbot/XmppBot.java @@ -1,596 +1,596 @@ package de.raion.xmppbot; /* * #%L * XmppBot Core * %% * Copyright (C) 2012 - 2013 Bernd Kiefer <[email protected]> * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.io.File; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import net.dharwin.common.tools.cli.api.CLIContext; import net.dharwin.common.tools.cli.api.CommandLineApplication; import net.dharwin.common.tools.cli.api.annotations.CLICommand; import net.dharwin.common.tools.cli.api.annotations.CLIEntry; import net.dharwin.common.tools.cli.api.exceptions.CLIInitException; import net.dharwin.common.tools.cli.api.utils.CLIAnnotationDiscovereryListener; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.ChatManagerListener; import org.jivesoftware.smack.Connection; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.FromContainsFilter; import org.jivesoftware.smack.filter.NotFilter; import org.jivesoftware.smackx.muc.DiscussionHistory; import org.jivesoftware.smackx.muc.MultiUserChat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.impetus.annovention.ClasspathDiscoverer; import com.impetus.annovention.Discoverer; import de.raion.xmppbot.annotation.MultiUserChatListener; import de.raion.xmppbot.annotation.PacketInterceptor; import de.raion.xmppbot.command.core.AbstractXmppCommand; import de.raion.xmppbot.config.BotConfiguration; import de.raion.xmppbot.config.XmppConfiguration; import de.raion.xmppbot.plugin.AbstractMessageListenerPlugin; import de.raion.xmppbot.plugin.MessageListenerPlugin; import de.raion.xmppbot.plugin.PluginStatusListener; /** *<h2>Enbot Botson</h2> * *a simple xmppbot providing a framework for commands and plugins.<br> * *@see AbstractXmppCommand for commands *@see CLICommand marker annotation for commands *@see AbstractMessageListenerPlugin for plugins *@see MessageListenerPlugin marker annotation for plugins */ @SuppressWarnings("rawtypes") @CLIEntry public class XmppBot extends CommandLineApplication implements ChatManagerListener, PluginStatusListener { private static Logger log = LoggerFactory.getLogger(XmppBot.class); private Map<String, XMPPConnection> connectionMap; private Map<String, MultiUserChat> multiUserChatMap; private Map<String, Chat> chatMap; private HashMap<MultiUserChat, Set<String>> multiUserChatPresenceMap; private ChatMessageListener messageHandler; private Map<String, Class<PacketInterceptor>> packetInterceptorMap; private Map<String, Class<MultiUserChatListener>> multiUserChatListenerMap; private BotConfiguration configuration; /** * constructor * @throws CLIInitException if the initilization of the CommandLineInterface fails */ public XmppBot() throws CLIInitException { connectionMap = new HashMap<String, XMPPConnection>(); multiUserChatMap = new HashMap<String, MultiUserChat>(); chatMap = new HashMap<String, Chat>(); multiUserChatPresenceMap = new HashMap<MultiUserChat, Set<String>>(); messageHandler = new ChatMessageListener(this); packetInterceptorMap = loadPacketInterceptors(); multiUserChatListenerMap = loadMultiUserChatListener(); } /** * initializes the bot with the given configuration * @param aConfig the configuration to use */ @SuppressWarnings("unchecked") public void init(BotConfiguration aConfig) { try { configuration = aConfig; super._commands = loadCommands(); Map<String, ConnectionConfiguration> conConfigMap = prepareConnectionConfiguration(aConfig.getConfigurations()); connectionMap = initConnections(aConfig, conConfigMap); this.registerChatListener(this, connectionMap); getContext().init(); Collection<XMPPConnection> connections = connectionMap.values(); for (XMPPConnection connection : connections) { addPlugins(connection); } } catch(Exception e) { log.error("init(BotConfiguration) - ", e); } } /** * @return context with thread-specific settings */ public XmppContext getContext() { return (XmppContext) _appContext; } /** implementation of the ChatManagerListener interface.<br> * method is called when a new chat request is incoming * @param chat the incoming chat * @param createdLocally true if local created, otherwise false * @see org.jivesoftware.smack.ChatManagerListener#chatCreated(org.jivesoftware.smack.Chat, boolean) */ public void chatCreated(Chat chat, boolean createdLocally) { if (!createdLocally) { chat.addMessageListener(messageHandler); log.info("incoming chat from {} with threadId {}",chat.getParticipant(), chat.getThreadID()); chatMap.put(chat.getParticipant().trim(), chat); } } /** * processes a incoming command * @param cmdString the command as string */ public void processCommand(String cmdString) { log.debug("Thread = " + Thread.currentThread().getName()); super.processInputLine(cmdString); } /** * get multiuserchat by name * @param mucName name of the multiuserchat * @return multiuserchat or null if not available */ public MultiUserChat getMultiUserChat(String mucName) { return this.multiUserChatMap.get(mucName); } /** * marks aUser for the MultiUserChat muc as available * @param muc MultiUserChat * @param aUser the user */ public void userAvailable(MultiUserChat muc, String aUser) { if (this.multiUserChatPresenceMap.containsKey(muc)) { this.multiUserChatPresenceMap.get(muc).add(aUser); } else { HashSet<String> userSet = new HashSet<String>(); userSet.add(aUser); this.multiUserChatPresenceMap.put(muc, userSet); } } /** * removes aUser from the {@link #multiUserChatPresenceMap} mapped by muc * @param muc MultiUserChat as key * @param aUser the user to mark as unavailable */ public void userUnavailabe(MultiUserChat muc, String aUser) { if (this.multiUserChatPresenceMap.containsKey(muc)) { this.multiUserChatPresenceMap.get(muc).remove(aUser); } } /** * the available user for a certain multiuserchat * @param muc multiuserchat * @return available user names */ public Set<String> getAvailableUser(MultiUserChat muc) { return multiUserChatPresenceMap.get(muc); } /** * chat by name * @param participant user name * @return the chat or null if not available */ public Chat getChat(String participant) { return chatMap.get(participant); } /** * Load the necessary commands for this application. * * @return The map of commands. * @throws CLIInitException when the initialization of the CLIContext failed */ private Map<String, Class<AbstractXmppCommand>> loadCommands() throws CLIInitException { Discoverer discoverer = new ClasspathDiscoverer(); CLIAnnotationDiscovereryListener discoveryListener = new CLIAnnotationDiscovereryListener( new String[] { CLICommand.class.getName() }); discoverer.addAnnotationListener(discoveryListener); discoverer.discover(); return loadCommands(discoveryListener.getDiscoveredClasses()); } private Map<String, Class<AbstractXmppCommand>> loadCommands(List<String> commandClasses) throws CLIInitException { Map<String, Class<AbstractXmppCommand>> commandMap = new HashMap<String, Class<AbstractXmppCommand>>(); for (String commandClassName : commandClasses) { try { @SuppressWarnings("unchecked") Class<AbstractXmppCommand> commandClass = (Class<AbstractXmppCommand>) Class .forName(commandClassName); if (AbstractXmppCommand.class.isAssignableFrom(commandClass)) { CLICommand annotation = commandClass.getAnnotation(CLICommand.class); commandMap.put(annotation.name().toLowerCase(), commandClass); log.debug("Loaded command [" + annotation.name() + "]."); } } catch (ClassNotFoundException e) { throw new CLIInitException("Unable to find command class [" + commandClassName + "]."); } catch (Exception e) { throw new CLIInitException("Unable to load command class [" + commandClassName + "]: " + e.getMessage()); } } return commandMap; } /** * maps the configuration information for Xmpp connections into smackx ConnectionConfiguration * @param configMap the configuration info to use * @return smackx ConnectionConfiguration mapped by the configured name */ private Map<String, ConnectionConfiguration> prepareConnectionConfiguration( Map<String, XmppConfiguration> configMap) { Map<String, ConnectionConfiguration> connections = new HashMap<String, ConnectionConfiguration>(); Set<String> keySet = configMap.keySet(); for (String key : keySet) { XmppConfiguration xmppConfig = configMap.get(key); String host = xmppConfig.getHost(); int port = xmppConfig.getPort(); String serviceName = xmppConfig.getServiceName(); if (serviceName == null || serviceName.equals("")) { serviceName = host; } connections.put(key.toLowerCase(), new ConnectionConfiguration(host, port, serviceName)); } return connections; } /** * establishes the XMPPConnections with the given BotConfiguration and * the XMPP ConnectionConfiguration and joins the configured MultiUserChats and Chats * @param aConfig the BotConfiguration to use * @param connectionConfigurationMap the ConnectionConfigurations to use for establishing * XMPPConnections mapped by configured name * @return established XMPPConnections mapped by the configured name from the BotConfiguration */ private Map<String, XMPPConnection> initConnections(BotConfiguration aConfig, Map<String, ConnectionConfiguration> connectionConfigurationMap) { Map<String, XMPPConnection> aConnectionMap = new HashMap<String, XMPPConnection>(); Map<String, XmppConfiguration> xmppConfigMap = aConfig.getConfigurations(); Connection.DEBUG_ENABLED = aConfig.isXmppConnectionDebuggingEnabled(); Set<String> keySet = connectionConfigurationMap.keySet(); for (String key : keySet) { ConnectionConfiguration cc = connectionConfigurationMap.get(key); XmppConfiguration xmppConfig = xmppConfigMap.get(key); try { XMPPConnection connection = new XMPPConnection(cc); connection.connect(); log.info("connection established to server '{}'", xmppConfig.getHost()); String jabberId = xmppConfig.getJabberId() + "/bot"; String pwd = xmppConfig.getPassword(); connection.login(jabberId, pwd); log.info("logged in with name '{}'", jabberId); joinMultiUserChats(xmppConfig, connection); joinChats(xmppConfig, connection); aConnectionMap.put(key, connection); } catch (XMPPException e) { log.error("login failed to server {} with nickname {}", xmppConfig.getHost(), xmppConfig.getNickName()); } } return aConnectionMap; } private XMPPConnection addPlugins(XMPPConnection connection) { Collection<AbstractMessageListenerPlugin> plugins = getContext().getPluginManager() .getEnabledPlugins() .values(); // excluding messages from enbot himself :) List<String> nickNameList = getOwnNickNames(); List<NotFilter> notFromFilterList = new ArrayList<NotFilter>(); for (String nickName : nickNameList) { FromContainsFilter fromFilter = new FromContainsFilter(nickName); notFromFilterList.add(new NotFilter(fromFilter)); } for(AbstractMessageListenerPlugin plugin : plugins){ NotFilter[] notFilter = new NotFilter[notFromFilterList.size()]; AndFilter andFilter = new AndFilter(notFromFilterList.toArray(notFilter)); andFilter.addFilter(plugin.getAcceptFilter()); connection.addPacketListener(plugin, andFilter); } return connection; } private List<String> getOwnNickNames() { List<String> list = new ArrayList<String>(); Collection<XmppConfiguration> c = configuration.getConfigurations().values(); for (XmppConfiguration xmppConfiguration : c) { list.add(xmppConfiguration.getNickName()); } return list; } private void joinMultiUserChats(XmppConfiguration xmppConfig, XMPPConnection connection) { Collection<String> mucNameCollection = xmppConfig.getMultiUserChats().values(); for (String mucName : mucNameCollection) { try { if (packetInterceptorMap.containsKey(xmppConfig.getServiceType())) { AbstractPacketInterceptor interceptor = (AbstractPacketInterceptor) packetInterceptorMap .get(xmppConfig.getServiceType()).newInstance(); interceptor.setContext(getContext()); connection.addPacketInterceptor(interceptor, interceptor.getPacketFilter()); } // start TODO remove workareound handly of muclistener DiscussionHistory history = new DiscussionHistory(); history.setMaxStanzas(0); MultiUserChat muc = new MultiUserChat(connection, mucName); if(multiUserChatListenerMap.containsKey(xmppConfig.getServiceType())) { Class<MultiUserChatListener> mucListenerClass = multiUserChatListenerMap.get(xmppConfig.getServiceType()); Constructor<MultiUserChatListener> constructor = mucListenerClass.getConstructor(XmppBot.class); AbstractMultiUserChatListener mucListener = (AbstractMultiUserChatListener)constructor.newInstance(this); muc.addMessageListener(mucListener); } muc.join(xmppConfig.getNickName(), xmppConfig.getPassword(), history, SmackConfiguration.getPacketReplyTimeout()); log.info("joined multiuserchat '{}' with address {}", mucName, muc.getRoom()); this.multiUserChatMap.put(mucName, muc); // TODO maybe removing Iterator<String> it = muc.getOccupants(); while (it.hasNext()) { userAvailable(muc, it.next()); } } catch (Exception e) { - log.error("Exception caught in joinChannels: " + e.getMessage(), e); + log.error("Exception caught in joinChannels for multiuserchat '{}' : {}", mucName, e.getMessage() ); } } } private Map<String, Class<PacketInterceptor>> loadPacketInterceptors() { Discoverer discoverer = new ClasspathDiscoverer(); CLIAnnotationDiscovereryListener discoveryListener = new CLIAnnotationDiscovereryListener( new String[] { PacketInterceptor.class.getName() }); discoverer.addAnnotationListener(discoveryListener); discoverer.discover(); List<String> list = discoveryListener.getDiscoveredClasses(); HashMap<String, Class<PacketInterceptor>> map = new HashMap<String, Class<PacketInterceptor>>(); for (String className : list) { try { @SuppressWarnings("unchecked") Class<PacketInterceptor> clazz = (Class<PacketInterceptor>) Class.forName(className); PacketInterceptor annotation = clazz.getAnnotation(PacketInterceptor.class); map.put(annotation.service().toLowerCase(), clazz); } catch (ClassNotFoundException e) { log.error("loadPacketInterceptors()", e); } } return map; } // TODO reduce redundance of duplicated code use template instead private Map<String, Class<MultiUserChatListener>> loadMultiUserChatListener() { Discoverer discoverer = new ClasspathDiscoverer(); CLIAnnotationDiscovereryListener discoveryListener = new CLIAnnotationDiscovereryListener( new String[] { MultiUserChatListener.class.getName() }); discoverer.addAnnotationListener(discoveryListener); discoverer.discover(); List<String> list = discoveryListener.getDiscoveredClasses(); HashMap<String, Class<MultiUserChatListener>> map = new HashMap<String, Class<MultiUserChatListener>>(); for (String className : list) { try { @SuppressWarnings("unchecked") Class<MultiUserChatListener> clazz = (Class<MultiUserChatListener>) Class.forName(className); MultiUserChatListener annotation = clazz.getAnnotation(MultiUserChatListener.class); map.put(annotation.service().toLowerCase(), clazz); } catch (ClassNotFoundException e) { log.error("loadMultiUserChatListener()", e); } } return map; } // TODO implement! private void joinChats(XmppConfiguration xmppConfig, XMPPConnection connection) { Set<String> keySet = xmppConfig.getChats().keySet(); } private void registerChatListener(ChatManagerListener chatListener, Map<String, XMPPConnection> conMap) { Set<String> keySet = conMap.keySet(); for (String key : keySet) { XMPPConnection connection = conMap.get(key); connection.getChatManager().addChatListener(chatListener); } } /** * <b>does nothing! disables shutdown</b> * @see net.dharwin.common.tools.cli.api.CommandLineApplication#shutdown() */ @Override protected void shutdown() {/* do nothing here */} @Override protected CLIContext createContext() { return new XmppContext(this); } /** * @return configuration object of enbot */ public BotConfiguration getConfiguration() { return configuration; } /** * checks if Command command is available * @param command cmd * @return true if available otherwise false */ public boolean hasCommand(String command) { return getCommandNames().contains(command); } public <T> void pluginDisabled(String pluginName, AbstractMessageListenerPlugin<T> plugin) { // TODO Auto-generated method stub } public <T> void pluginEnabled(String pluginName, AbstractMessageListenerPlugin<T> plugin) { // TODO Auto-generated method stub } /** * starting the xmppbot * @param args arguments, arg[0] should link to the named configfile, otherwise * Enbot will lookup for <code>xmppbot.json</code> in the workingdirectory * @throws Exception if an not expected Exception occure */ public static void main(String[] args) throws Exception { XmppBot bot = new XmppBot(); File configFile = null; if (args.length == 0) { String fileName = bot.getContext().getString("xmppbot.configuration.filename", "xmppbot.json"); configFile = new File(fileName); } else { configFile = new File(args[0]); } log.info(configFile.getAbsolutePath()); ObjectMapper mapper = new ObjectMapper(); BotConfiguration config = mapper.readValue(configFile, BotConfiguration.class); log.debug(config.toString()); bot.init(config); TimeUnit.HOURS.sleep(1); } }
true
true
private void joinMultiUserChats(XmppConfiguration xmppConfig, XMPPConnection connection) { Collection<String> mucNameCollection = xmppConfig.getMultiUserChats().values(); for (String mucName : mucNameCollection) { try { if (packetInterceptorMap.containsKey(xmppConfig.getServiceType())) { AbstractPacketInterceptor interceptor = (AbstractPacketInterceptor) packetInterceptorMap .get(xmppConfig.getServiceType()).newInstance(); interceptor.setContext(getContext()); connection.addPacketInterceptor(interceptor, interceptor.getPacketFilter()); } // start TODO remove workareound handly of muclistener DiscussionHistory history = new DiscussionHistory(); history.setMaxStanzas(0); MultiUserChat muc = new MultiUserChat(connection, mucName); if(multiUserChatListenerMap.containsKey(xmppConfig.getServiceType())) { Class<MultiUserChatListener> mucListenerClass = multiUserChatListenerMap.get(xmppConfig.getServiceType()); Constructor<MultiUserChatListener> constructor = mucListenerClass.getConstructor(XmppBot.class); AbstractMultiUserChatListener mucListener = (AbstractMultiUserChatListener)constructor.newInstance(this); muc.addMessageListener(mucListener); } muc.join(xmppConfig.getNickName(), xmppConfig.getPassword(), history, SmackConfiguration.getPacketReplyTimeout()); log.info("joined multiuserchat '{}' with address {}", mucName, muc.getRoom()); this.multiUserChatMap.put(mucName, muc); // TODO maybe removing Iterator<String> it = muc.getOccupants(); while (it.hasNext()) { userAvailable(muc, it.next()); } } catch (Exception e) { log.error("Exception caught in joinChannels: " + e.getMessage(), e); } } }
private void joinMultiUserChats(XmppConfiguration xmppConfig, XMPPConnection connection) { Collection<String> mucNameCollection = xmppConfig.getMultiUserChats().values(); for (String mucName : mucNameCollection) { try { if (packetInterceptorMap.containsKey(xmppConfig.getServiceType())) { AbstractPacketInterceptor interceptor = (AbstractPacketInterceptor) packetInterceptorMap .get(xmppConfig.getServiceType()).newInstance(); interceptor.setContext(getContext()); connection.addPacketInterceptor(interceptor, interceptor.getPacketFilter()); } // start TODO remove workareound handly of muclistener DiscussionHistory history = new DiscussionHistory(); history.setMaxStanzas(0); MultiUserChat muc = new MultiUserChat(connection, mucName); if(multiUserChatListenerMap.containsKey(xmppConfig.getServiceType())) { Class<MultiUserChatListener> mucListenerClass = multiUserChatListenerMap.get(xmppConfig.getServiceType()); Constructor<MultiUserChatListener> constructor = mucListenerClass.getConstructor(XmppBot.class); AbstractMultiUserChatListener mucListener = (AbstractMultiUserChatListener)constructor.newInstance(this); muc.addMessageListener(mucListener); } muc.join(xmppConfig.getNickName(), xmppConfig.getPassword(), history, SmackConfiguration.getPacketReplyTimeout()); log.info("joined multiuserchat '{}' with address {}", mucName, muc.getRoom()); this.multiUserChatMap.put(mucName, muc); // TODO maybe removing Iterator<String> it = muc.getOccupants(); while (it.hasNext()) { userAvailable(muc, it.next()); } } catch (Exception e) { log.error("Exception caught in joinChannels for multiuserchat '{}' : {}", mucName, e.getMessage() ); } } }
diff --git a/x10.compiler/src/x10/compiler/ws/WSCodeGenerator.java b/x10.compiler/src/x10/compiler/ws/WSCodeGenerator.java index 4e907895b..ae7c3d925 100644 --- a/x10.compiler/src/x10/compiler/ws/WSCodeGenerator.java +++ b/x10.compiler/src/x10/compiler/ws/WSCodeGenerator.java @@ -1,196 +1,203 @@ /* * This file is part of the X10 project (http://x10-lang.org). * * This file is licensed to You under the Eclipse Public License (EPL); * 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/eclipse-1.0.php * * (C) Copyright IBM Corporation 2006-2010. */ package x10.compiler.ws; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import polyglot.ast.ConstructorDecl; import polyglot.ast.Expr; import polyglot.ast.MethodDecl; import polyglot.ast.Node; import polyglot.ast.NodeFactory; import polyglot.frontend.Job; import polyglot.types.ClassDef; import polyglot.types.ClassType; import polyglot.types.ConstructorDef; import polyglot.types.MethodDef; import polyglot.types.ProcedureDef; import polyglot.types.SemanticException; import polyglot.types.TypeSystem; import polyglot.visit.ContextVisitor; import polyglot.visit.NodeVisitor; import x10.ast.Async; import x10.ast.AtEach; import x10.ast.Closure; import x10.ast.Here; import x10.ast.Offer; import x10.ast.PlacedClosure; import x10.ast.RemoteActivityInvocation; import x10.ast.X10ClassDecl; import x10.ast.X10MethodDecl; import x10.ast.X10NodeFactory; import x10.compiler.ws.codegen.AbstractWSClassGen; import x10.compiler.ws.codegen.WSMethodFrameClassGen; import x10.compiler.ws.util.WSCallGraph; import x10.compiler.ws.util.WSCallGraphNode; import x10.types.ClosureDef; import x10.types.X10Context; import x10.types.X10TypeSystem; import x10.types.checker.PlaceChecker; import x10.util.Synthesizer; import x10.util.synthesizer.MethodSynth; import x10.visit.X10PrettyPrinterVisitor; /** * ContextVisitor that generates code for work stealing. * @author Haibo * @author Haichuan * @author tardieu * * In work-stealing code transformation, all methods with finish-async statements, * and all methods that invoke directly or indirectly the above methods, * need rewriting. * * So it needs to build a static call-graph, and have a DFS on the reverse call-graph * edges and mark all methods reachable. * * In the first step, we only mark all methods that contain finish-async as the target. */ public class WSCodeGenerator extends ContextVisitor { public static final int debugLevel = 5; //0: no; 3: little; 5: median; 7: heave; 9: verbose // Single static WSTransformState shared by all visitors (FIXME) public static WSTransformState wts; private final HashSet<X10MethodDecl> genMethodDecls; private final HashSet<X10ClassDecl> genClassDecls; /** * @param job * @param ts * @param nf */ public WSCodeGenerator(Job job, TypeSystem ts, NodeFactory nf) { super(job, ts, nf); genMethodDecls = new HashSet<X10MethodDecl>(); genClassDecls = new HashSet<X10ClassDecl>(); } public static void buildCallGraph(X10TypeSystem xts, X10NodeFactory xnf, String theLanguage) { wts = new WSTransformState(xts, xnf, theLanguage); } /** * WS codegen * MethodDecl --> if it is a target method, transform it into an inner class * X10ClassDecl --> add generated inner classes and methods if any */ protected Node leaveCall(Node parent, Node old, Node n, NodeVisitor v) throws SemanticException { // reject unsupported patterns if(n instanceof ConstructorDecl){ ConstructorDecl cDecl = (ConstructorDecl)n; ConstructorDef cDef = cDecl.constructorDef(); if(wts.isTargetProcedure(cDef)){ throw new SemanticException("Work Stealing doesn't support concurrent constructor: " + cDef,n.position()); } } if(n instanceof RemoteActivityInvocation){ RemoteActivityInvocation r = (RemoteActivityInvocation)n; if(!(r.place() instanceof Here)){ throw new SemanticException("Work-Stealing doesn't support at: " + r, n.position()); } } if(n instanceof Closure && !(n instanceof PlacedClosure)){ //match with WSCallGraph, not handle PlacedClosure Closure closure = (Closure)n; ClosureDef cDef = closure.closureDef(); if(wts.isTargetProcedure(cDef)){ throw new SemanticException("Work Stealing doesn't support concurrent closure: " + cDef,n.position()); } } if(n instanceof AtEach){ throw new SemanticException("Work Stealing doesn't support ateach: " + n,n.position()); } if(n instanceof Offer){ throw new SemanticException("Work Stealing doesn't support collecting finish: " + n,n.position()); } // transform methods if(n instanceof MethodDecl) { MethodDecl mDecl = (MethodDecl)n; MethodDef mDef = mDecl.methodDef(); if(wts.isTargetProcedure(mDef)){ if(debugLevel > 3){ System.out.println("[WS_INFO] Start transforming target method: " + mDef.name()); } Job job = ((ClassType) mDef.container().get()).def().job(); WSMethodFrameClassGen mFrame = new WSMethodFrameClassGen(job, (X10NodeFactory) nf, (X10Context) context, mDef, mDecl, wts); + try{ n = mFrame.transform(); + } + catch(SemanticException e){ + System.err.println("==========>" + e.getMessage()); + e.printStackTrace(); + System.exit(-1); + } genClassDecls.addAll(mFrame.close()); genMethodDecls.add(mFrame.getWraperMethod()); if(debugLevel > 3){ System.out.println(mFrame.getFrameStructureDesc(4)); } } return n; } // transform classes if (n instanceof X10ClassDecl) { X10ClassDecl cDecl = (X10ClassDecl)n; ClassDef cDef = cDecl.classDef(); List<X10ClassDecl> classes = getClassDecls(cDef); if (classes.isEmpty()) { return n; //no change } else{ if(debugLevel > 3){ System.out.println(); System.out.println("[WS_INFO] Add new methods and nested classes to class: " + n); } cDecl = Synthesizer.addNestedClasses(cDecl, classes); cDecl = Synthesizer.addMethods(cDecl, getMethodDecls(cDef)); return cDecl; } } return n; } protected List<X10MethodDecl> getMethodDecls(ClassDef cDef) throws SemanticException { List<X10MethodDecl> mDecls = new ArrayList<X10MethodDecl>(); for(X10MethodDecl mDecl : genMethodDecls){ ClassDef containerDef = ((ClassType) mDecl.methodDef().container().get()).def(); if(containerDef == cDef){ mDecls.add(mDecl); } } return mDecls; } protected List<X10ClassDecl> getClassDecls(ClassDef cDef) throws SemanticException { ArrayList<X10ClassDecl> cDecls = new ArrayList<X10ClassDecl>(); for(X10ClassDecl cDecl : genClassDecls){ ClassDef containerDef = cDecl.classDef().outer().get(); if(containerDef == cDef){ cDecls.add(cDecl); } } return cDecls; } }
false
true
protected Node leaveCall(Node parent, Node old, Node n, NodeVisitor v) throws SemanticException { // reject unsupported patterns if(n instanceof ConstructorDecl){ ConstructorDecl cDecl = (ConstructorDecl)n; ConstructorDef cDef = cDecl.constructorDef(); if(wts.isTargetProcedure(cDef)){ throw new SemanticException("Work Stealing doesn't support concurrent constructor: " + cDef,n.position()); } } if(n instanceof RemoteActivityInvocation){ RemoteActivityInvocation r = (RemoteActivityInvocation)n; if(!(r.place() instanceof Here)){ throw new SemanticException("Work-Stealing doesn't support at: " + r, n.position()); } } if(n instanceof Closure && !(n instanceof PlacedClosure)){ //match with WSCallGraph, not handle PlacedClosure Closure closure = (Closure)n; ClosureDef cDef = closure.closureDef(); if(wts.isTargetProcedure(cDef)){ throw new SemanticException("Work Stealing doesn't support concurrent closure: " + cDef,n.position()); } } if(n instanceof AtEach){ throw new SemanticException("Work Stealing doesn't support ateach: " + n,n.position()); } if(n instanceof Offer){ throw new SemanticException("Work Stealing doesn't support collecting finish: " + n,n.position()); } // transform methods if(n instanceof MethodDecl) { MethodDecl mDecl = (MethodDecl)n; MethodDef mDef = mDecl.methodDef(); if(wts.isTargetProcedure(mDef)){ if(debugLevel > 3){ System.out.println("[WS_INFO] Start transforming target method: " + mDef.name()); } Job job = ((ClassType) mDef.container().get()).def().job(); WSMethodFrameClassGen mFrame = new WSMethodFrameClassGen(job, (X10NodeFactory) nf, (X10Context) context, mDef, mDecl, wts); n = mFrame.transform(); genClassDecls.addAll(mFrame.close()); genMethodDecls.add(mFrame.getWraperMethod()); if(debugLevel > 3){ System.out.println(mFrame.getFrameStructureDesc(4)); } } return n; } // transform classes if (n instanceof X10ClassDecl) { X10ClassDecl cDecl = (X10ClassDecl)n; ClassDef cDef = cDecl.classDef(); List<X10ClassDecl> classes = getClassDecls(cDef); if (classes.isEmpty()) { return n; //no change } else{ if(debugLevel > 3){ System.out.println(); System.out.println("[WS_INFO] Add new methods and nested classes to class: " + n); } cDecl = Synthesizer.addNestedClasses(cDecl, classes); cDecl = Synthesizer.addMethods(cDecl, getMethodDecls(cDef)); return cDecl; } } return n; }
protected Node leaveCall(Node parent, Node old, Node n, NodeVisitor v) throws SemanticException { // reject unsupported patterns if(n instanceof ConstructorDecl){ ConstructorDecl cDecl = (ConstructorDecl)n; ConstructorDef cDef = cDecl.constructorDef(); if(wts.isTargetProcedure(cDef)){ throw new SemanticException("Work Stealing doesn't support concurrent constructor: " + cDef,n.position()); } } if(n instanceof RemoteActivityInvocation){ RemoteActivityInvocation r = (RemoteActivityInvocation)n; if(!(r.place() instanceof Here)){ throw new SemanticException("Work-Stealing doesn't support at: " + r, n.position()); } } if(n instanceof Closure && !(n instanceof PlacedClosure)){ //match with WSCallGraph, not handle PlacedClosure Closure closure = (Closure)n; ClosureDef cDef = closure.closureDef(); if(wts.isTargetProcedure(cDef)){ throw new SemanticException("Work Stealing doesn't support concurrent closure: " + cDef,n.position()); } } if(n instanceof AtEach){ throw new SemanticException("Work Stealing doesn't support ateach: " + n,n.position()); } if(n instanceof Offer){ throw new SemanticException("Work Stealing doesn't support collecting finish: " + n,n.position()); } // transform methods if(n instanceof MethodDecl) { MethodDecl mDecl = (MethodDecl)n; MethodDef mDef = mDecl.methodDef(); if(wts.isTargetProcedure(mDef)){ if(debugLevel > 3){ System.out.println("[WS_INFO] Start transforming target method: " + mDef.name()); } Job job = ((ClassType) mDef.container().get()).def().job(); WSMethodFrameClassGen mFrame = new WSMethodFrameClassGen(job, (X10NodeFactory) nf, (X10Context) context, mDef, mDecl, wts); try{ n = mFrame.transform(); } catch(SemanticException e){ System.err.println("==========>" + e.getMessage()); e.printStackTrace(); System.exit(-1); } genClassDecls.addAll(mFrame.close()); genMethodDecls.add(mFrame.getWraperMethod()); if(debugLevel > 3){ System.out.println(mFrame.getFrameStructureDesc(4)); } } return n; } // transform classes if (n instanceof X10ClassDecl) { X10ClassDecl cDecl = (X10ClassDecl)n; ClassDef cDef = cDecl.classDef(); List<X10ClassDecl> classes = getClassDecls(cDef); if (classes.isEmpty()) { return n; //no change } else{ if(debugLevel > 3){ System.out.println(); System.out.println("[WS_INFO] Add new methods and nested classes to class: " + n); } cDecl = Synthesizer.addNestedClasses(cDecl, classes); cDecl = Synthesizer.addMethods(cDecl, getMethodDecls(cDef)); return cDecl; } } return n; }
diff --git a/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java b/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java index 90c53c96..0f5eec6b 100644 --- a/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java +++ b/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java @@ -1,155 +1,155 @@ /* * 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.vfs2.provider.http; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileSystemOptions; import org.apache.commons.vfs2.UserAuthenticationData; import org.apache.commons.vfs2.UserAuthenticator; import org.apache.commons.vfs2.util.UserAuthenticatorUtils; /** * Create a HttpClient instance. */ public final class HttpClientFactory { private HttpClientFactory() { } public static HttpClient createConnection(String scheme, String hostname, int port, String username, String password, FileSystemOptions fileSystemOptions) throws FileSystemException { return createConnection(HttpFileSystemConfigBuilder.getInstance(), scheme, hostname, port, username, password, fileSystemOptions); } /** * Creates a new connection to the server. * @param builder The HttpFileSystemConfigBuilder. * @param scheme The protocol. * @param hostname The hostname. * @param port The port number. * @param username The username. * @param password The password * @param fileSystemOptions The file system options. * @return a new HttpClient connection. * @throws FileSystemException if an error occurs. * @since 2.0 */ public static HttpClient createConnection(HttpFileSystemConfigBuilder builder, String scheme, String hostname, int port, String username, String password, FileSystemOptions fileSystemOptions) throws FileSystemException { HttpClient client; try { HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams connectionMgrParams = mgr.getParams(); client = new HttpClient(mgr); final HostConfiguration config = new HostConfiguration(); config.setHost(hostname, port, scheme); if (fileSystemOptions != null) { String proxyHost = builder.getProxyHost(fileSystemOptions); int proxyPort = builder.getProxyPort(fileSystemOptions); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { config.setProxy(proxyHost, proxyPort); } UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions); if (proxyAuth != null) { UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth, new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD }); if (authData != null) { final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials( UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, null)), UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, null))); AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT); client.getState().setProxyCredentials(scope, proxyCreds); } if (builder.isPreemptiveAuth(fileSystemOptions)) { HttpClientParams httpClientParams = new HttpClientParams(); httpClientParams.setAuthenticationPreemptive(true); client.setParams(httpClientParams); } } Cookie[] cookies = builder.getCookies(fileSystemOptions); if (cookies != null) { client.getState().addCookies(cookies); } } /** - * ConnectionManager set methodsmust be called after the host & port and proxy host & port + * ConnectionManager set methods must be called after the host & port and proxy host & port * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams * tries to locate the host configuration. */ connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions)); connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions)); client.setHostConfiguration(config); if (username != null) { final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT); client.getState().setCredentials(scope, creds); } client.executeMethod(new HeadMethod()); } catch (final Exception exc) { throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname); } return client; } }
true
true
public static HttpClient createConnection(HttpFileSystemConfigBuilder builder, String scheme, String hostname, int port, String username, String password, FileSystemOptions fileSystemOptions) throws FileSystemException { HttpClient client; try { HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams connectionMgrParams = mgr.getParams(); client = new HttpClient(mgr); final HostConfiguration config = new HostConfiguration(); config.setHost(hostname, port, scheme); if (fileSystemOptions != null) { String proxyHost = builder.getProxyHost(fileSystemOptions); int proxyPort = builder.getProxyPort(fileSystemOptions); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { config.setProxy(proxyHost, proxyPort); } UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions); if (proxyAuth != null) { UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth, new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD }); if (authData != null) { final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials( UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, null)), UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, null))); AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT); client.getState().setProxyCredentials(scope, proxyCreds); } if (builder.isPreemptiveAuth(fileSystemOptions)) { HttpClientParams httpClientParams = new HttpClientParams(); httpClientParams.setAuthenticationPreemptive(true); client.setParams(httpClientParams); } } Cookie[] cookies = builder.getCookies(fileSystemOptions); if (cookies != null) { client.getState().addCookies(cookies); } } /** * ConnectionManager set methodsmust be called after the host & port and proxy host & port * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams * tries to locate the host configuration. */ connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions)); connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions)); client.setHostConfiguration(config); if (username != null) { final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT); client.getState().setCredentials(scope, creds); } client.executeMethod(new HeadMethod()); } catch (final Exception exc) { throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname); } return client; }
public static HttpClient createConnection(HttpFileSystemConfigBuilder builder, String scheme, String hostname, int port, String username, String password, FileSystemOptions fileSystemOptions) throws FileSystemException { HttpClient client; try { HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams connectionMgrParams = mgr.getParams(); client = new HttpClient(mgr); final HostConfiguration config = new HostConfiguration(); config.setHost(hostname, port, scheme); if (fileSystemOptions != null) { String proxyHost = builder.getProxyHost(fileSystemOptions); int proxyPort = builder.getProxyPort(fileSystemOptions); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { config.setProxy(proxyHost, proxyPort); } UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions); if (proxyAuth != null) { UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth, new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD }); if (authData != null) { final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials( UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, null)), UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, null))); AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT); client.getState().setProxyCredentials(scope, proxyCreds); } if (builder.isPreemptiveAuth(fileSystemOptions)) { HttpClientParams httpClientParams = new HttpClientParams(); httpClientParams.setAuthenticationPreemptive(true); client.setParams(httpClientParams); } } Cookie[] cookies = builder.getCookies(fileSystemOptions); if (cookies != null) { client.getState().addCookies(cookies); } } /** * ConnectionManager set methods must be called after the host & port and proxy host & port * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams * tries to locate the host configuration. */ connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions)); connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions)); client.setHostConfiguration(config); if (username != null) { final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT); client.getState().setCredentials(scope, creds); } client.executeMethod(new HeadMethod()); } catch (final Exception exc) { throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname); } return client; }
diff --git a/src/main/java/org/datacite/mds/web/api/ApiResponseWrapper.java b/src/main/java/org/datacite/mds/web/api/ApiResponseWrapper.java index 37816bc..5fd2aca 100644 --- a/src/main/java/org/datacite/mds/web/api/ApiResponseWrapper.java +++ b/src/main/java/org/datacite/mds/web/api/ApiResponseWrapper.java @@ -1,40 +1,40 @@ package org.datacite.mds.web.api; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; /** * This is a wrapper around HttpServletResponse. By default the sendError * methods result in a html page generated by tomcat. This wrapper prints only * the error message to the response body (and sets the given response code) */ public class ApiResponseWrapper extends HttpServletResponseWrapper { static final String NEW_LINE = System.getProperty("line.separator"); Logger log = Logger.getLogger(ApiResponseWrapper.class); public ApiResponseWrapper(HttpServletResponse response) { super(response); } @Override public void sendError(int sc, String msg) throws IOException { msg = StringUtils.replace(msg, NEW_LINE, " - "); log.debug("sendError " + sc + ": " + msg); setStatus(sc); - getWriter().println(msg); + getWriter().print(msg); } @Override public void sendError(int sc) throws IOException { log.debug("sendError " + sc); sendError(sc, ""); } }
true
true
public void sendError(int sc, String msg) throws IOException { msg = StringUtils.replace(msg, NEW_LINE, " - "); log.debug("sendError " + sc + ": " + msg); setStatus(sc); getWriter().println(msg); }
public void sendError(int sc, String msg) throws IOException { msg = StringUtils.replace(msg, NEW_LINE, " - "); log.debug("sendError " + sc + ": " + msg); setStatus(sc); getWriter().print(msg); }
diff --git a/src/TandemTest.java b/src/TandemTest.java index 396483e..5bcde37 100644 --- a/src/TandemTest.java +++ b/src/TandemTest.java @@ -1,168 +1,172 @@ import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.TokenStream; import org.antlr.runtime.tree.CommonTree; import java.io.*; import org.antlr.runtime.*; import org.junit.Test; import org.junit.BeforeClass; import static org.junit.Assert.*; public class TandemTest { private static File currentDir = new File("."); private static String currentDirName; private static String testPath; private final static String whitespace = "misc/whitespace/"; private final static String comments = "misc/comments/"; private final static String expression = "expression/"; private final static String statement = "statement/"; private final static String failure = "failure/"; public static void main(String args[]) { try { currentDirName = currentDir.getCanonicalPath(); } catch(Exception e) { e.printStackTrace(); } testPath = currentDirName + "/test/"; } @BeforeClass public static void oneTimeSetUp() { try { currentDirName = currentDir.getCanonicalPath(); } catch(Exception e) { e.printStackTrace(); } testPath = currentDirName + "/test/"; } public static boolean parseFile(String filename) { boolean parsing_success = false; try { CharStream input = new ANTLRFileStream(filename); TanGLexer lexer = new TanGLexer(input); TokenStream ts = new CommonTokenStream(lexer); TanGParser parse = new TanGParser(ts); parse.tanG(); int errorsCount = parse.getNumberOfSyntaxErrors(); if(errorsCount == 0) { parsing_success = true; } + else + { + System.err.println("Number of syntax errors in " + filename + ": " + errorsCount + "\n"); + } } catch(Exception t) { // System.out.println("Exception: "+t); // t.printStackTrace(); parsing_success = false; return parsing_success; } return parsing_success; } public static File[] listTDFiles(File file) { File[] files = file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if(name.toLowerCase().endsWith(".td")) { return true; } else { return false; } } }); return files; } public static void run_success(File file) { File[] files = listTDFiles(file); for(File f : files) { if(f != null) { // System.out.println(f.getAbsolutePath()); assertTrue("Failed to parse " + f.getName(), parseFile(f.getAbsolutePath()) ); } } } public static void run_failure(File file) { File[] files = listTDFiles(file); for(File f : files) { if(f != null) { // System.out.println(f.getAbsolutePath()); assertFalse("Should not have parsed " + f.getName(), parseFile(f.getAbsolutePath()) ); } } } @Test public void test_whitespace() { // System.out.println(testPath + whitespace); File file = new File(testPath + whitespace); run_success(file); } @Test public void test_comments() { File file = new File(testPath + comments); run_success(file); } @Test public void test_expression() { File file = new File(testPath + expression); run_success(file); } @Test public void test_statement() { File file = new File(testPath + statement); run_success(file); } @Test public void test_failures() { File file = new File(testPath + failure); run_failure(file); } }
true
true
public static boolean parseFile(String filename) { boolean parsing_success = false; try { CharStream input = new ANTLRFileStream(filename); TanGLexer lexer = new TanGLexer(input); TokenStream ts = new CommonTokenStream(lexer); TanGParser parse = new TanGParser(ts); parse.tanG(); int errorsCount = parse.getNumberOfSyntaxErrors(); if(errorsCount == 0) { parsing_success = true; } } catch(Exception t) { // System.out.println("Exception: "+t); // t.printStackTrace(); parsing_success = false; return parsing_success; } return parsing_success; }
public static boolean parseFile(String filename) { boolean parsing_success = false; try { CharStream input = new ANTLRFileStream(filename); TanGLexer lexer = new TanGLexer(input); TokenStream ts = new CommonTokenStream(lexer); TanGParser parse = new TanGParser(ts); parse.tanG(); int errorsCount = parse.getNumberOfSyntaxErrors(); if(errorsCount == 0) { parsing_success = true; } else { System.err.println("Number of syntax errors in " + filename + ": " + errorsCount + "\n"); } } catch(Exception t) { // System.out.println("Exception: "+t); // t.printStackTrace(); parsing_success = false; return parsing_success; } return parsing_success; }
diff --git a/src/com/fsck/k9/mail/store/Pop3Store.java b/src/com/fsck/k9/mail/store/Pop3Store.java index 80711a48f..ab2133001 100644 --- a/src/com/fsck/k9/mail/store/Pop3Store.java +++ b/src/com/fsck/k9/mail/store/Pop3Store.java @@ -1,1174 +1,1174 @@ package com.fsck.k9.mail.store; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.K9; import com.fsck.k9.controller.MessageRetrievalListener; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.*; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.net.ssl.TrustManagerFactory; import com.fsck.k9.net.ssl.TrustedSocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManager; import java.io.*; import java.net.*; import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; public class Pop3Store extends Store { public static final String STORE_TYPE = "POP3"; public static final int CONNECTION_SECURITY_NONE = 0; public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1; public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2; public static final int CONNECTION_SECURITY_SSL_REQUIRED = 3; public static final int CONNECTION_SECURITY_SSL_OPTIONAL = 4; private enum AuthType { PLAIN, CRAM_MD5 } private static final String STLS_COMMAND = "STLS"; private static final String USER_COMMAND = "USER"; private static final String PASS_COMMAND = "PASS"; private static final String CAPA_COMMAND = "CAPA"; private static final String STAT_COMMAND = "STAT"; private static final String LIST_COMMAND = "LIST"; private static final String UIDL_COMMAND = "UIDL"; private static final String TOP_COMMAND = "TOP"; private static final String RETR_COMMAND = "RETR"; private static final String DELE_COMMAND = "DELE"; private static final String QUIT_COMMAND = "QUIT"; private static final String STLS_CAPABILITY = "STLS"; private static final String UIDL_CAPABILITY = "UIDL"; private static final String PIPELINING_CAPABILITY = "PIPELINING"; private static final String USER_CAPABILITY = "USER"; private static final String TOP_CAPABILITY = "TOP"; /** * Decodes a Pop3Store URI. * * <p>Possible forms:</p> * <pre> * pop3://user:password@server:port CONNECTION_SECURITY_NONE * pop3+tls://user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL * pop3+tls+://user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED * pop3+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED * pop3+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL * </pre> */ public static ServerSettings decodeUri(String uri) { String host; int port; ConnectionSecurity connectionSecurity; String username = null; String password = null; URI pop3Uri; try { pop3Uri = new URI(uri); } catch (URISyntaxException use) { throw new IllegalArgumentException("Invalid Pop3Store URI", use); } String scheme = pop3Uri.getScheme(); if (scheme.equals("pop3")) { connectionSecurity = ConnectionSecurity.NONE; port = 110; } else if (scheme.equals("pop3+tls")) { connectionSecurity = ConnectionSecurity.STARTTLS_OPTIONAL; port = 110; } else if (scheme.equals("pop3+tls+")) { connectionSecurity = ConnectionSecurity.STARTTLS_REQUIRED; port = 110; } else if (scheme.equals("pop3+ssl+")) { connectionSecurity = ConnectionSecurity.SSL_TLS_REQUIRED; port = 995; } else if (scheme.equals("pop3+ssl")) { connectionSecurity = ConnectionSecurity.SSL_TLS_OPTIONAL; port = 995; } else { throw new IllegalArgumentException("Unsupported protocol (" + scheme + ")"); } host = pop3Uri.getHost(); if (pop3Uri.getPort() != -1) { port = pop3Uri.getPort(); } String authType = AuthType.PLAIN.name(); if (pop3Uri.getUserInfo() != null) { try { int userIndex = 0, passwordIndex = 1; String userinfo = pop3Uri.getUserInfo(); String[] userInfoParts = userinfo.split(":"); if (userInfoParts.length > 2 || userinfo.endsWith(":") ) { // If 'userinfo' ends with ":" the password is empty. This can only happen // after an account was imported (so authType and username are present). userIndex++; passwordIndex++; authType = userInfoParts[0]; } username = URLDecoder.decode(userInfoParts[userIndex], "UTF-8"); if (userInfoParts.length > passwordIndex) { password = URLDecoder.decode(userInfoParts[passwordIndex], "UTF-8"); } } catch (UnsupportedEncodingException enc) { // This shouldn't happen since the encoding is hardcoded to UTF-8 throw new IllegalArgumentException("Couldn't urldecode username or password.", enc); } } return new ServerSettings(STORE_TYPE, host, port, connectionSecurity, authType, username, password); } /** * Creates a Pop3Store URI with the supplied settings. * * @param server * The {@link ServerSettings} object that holds the server settings. * * @return A Pop3Store URI that holds the same information as the {@code server} parameter. * * @see Account#getStoreUri() * @see Pop3Store#decodeUri(String) */ public static String createUri(ServerSettings server) { String userEnc; String passwordEnc; try { userEnc = URLEncoder.encode(server.username, "UTF-8"); passwordEnc = (server.password != null) ? URLEncoder.encode(server.password, "UTF-8") : ""; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Could not encode username or password", e); } String scheme; switch (server.connectionSecurity) { case SSL_TLS_OPTIONAL: scheme = "pop3+ssl"; break; case SSL_TLS_REQUIRED: scheme = "pop3+ssl+"; break; case STARTTLS_OPTIONAL: scheme = "pop3+tls"; break; case STARTTLS_REQUIRED: scheme = "pop3+tls+"; break; default: case NONE: scheme = "pop3"; break; } try { AuthType.valueOf(server.authenticationType); } catch (Exception e) { throw new IllegalArgumentException("Invalid authentication type (" + server.authenticationType + ")"); } String userInfo = server.authenticationType + ":" + userEnc + ":" + passwordEnc; try { return new URI(scheme, userInfo, server.host, server.port, null, null, null).toString(); } catch (URISyntaxException e) { throw new IllegalArgumentException("Can't create Pop3Store URI", e); } } private String mHost; private int mPort; private String mUsername; private String mPassword; private AuthType mAuthType; private int mConnectionSecurity; private HashMap<String, Folder> mFolders = new HashMap<String, Folder>(); private Pop3Capabilities mCapabilities; /** * This value is {@code true} if the server supports the CAPA command but doesn't advertise * support for the TOP command OR if the server doesn't support the CAPA command and we * already unsuccessfully tried to use the TOP command. */ private boolean mTopNotSupported; public Pop3Store(Account account) throws MessagingException { super(account); ServerSettings settings; try { settings = decodeUri(mAccount.getStoreUri()); } catch (IllegalArgumentException e) { throw new MessagingException("Error while decoding store URI", e); } mHost = settings.host; mPort = settings.port; switch (settings.connectionSecurity) { case NONE: mConnectionSecurity = CONNECTION_SECURITY_NONE; break; case STARTTLS_OPTIONAL: mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL; break; case STARTTLS_REQUIRED: mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED; break; case SSL_TLS_OPTIONAL: mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL; break; case SSL_TLS_REQUIRED: mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED; break; } mUsername = settings.username; mPassword = settings.password; mAuthType = AuthType.valueOf(settings.authenticationType); } @Override public Folder getFolder(String name) { Folder folder = mFolders.get(name); if (folder == null) { folder = new Pop3Folder(name); mFolders.put(folder.getName(), folder); } return folder; } @Override public List <? extends Folder > getPersonalNamespaces(boolean forceListAll) throws MessagingException { List<Folder> folders = new LinkedList<Folder>(); folders.add(getFolder(mAccount.getInboxFolderName())); return folders; } @Override public void checkSettings() throws MessagingException { Pop3Folder folder = new Pop3Folder(mAccount.getInboxFolderName()); folder.open(Folder.OPEN_MODE_RW); if (!mCapabilities.uidl) { /* * Run an additional test to see if UIDL is supported on the server. If it's not we * can't service this account. */ /* * If the server doesn't support UIDL it will return a - response, which causes * executeSimpleCommand to throw a MessagingException, exiting this method. */ folder.executeSimpleCommand(UIDL_COMMAND); } folder.close(); } @Override public boolean isSeenFlagSupported() { return false; } class Pop3Folder extends Folder { private Socket mSocket; private InputStream mIn; private OutputStream mOut; private HashMap<String, Pop3Message> mUidToMsgMap = new HashMap<String, Pop3Message>(); private HashMap<Integer, Pop3Message> mMsgNumToMsgMap = new HashMap<Integer, Pop3Message>(); private HashMap<String, Integer> mUidToMsgNumMap = new HashMap<String, Integer>(); private String mName; private int mMessageCount; public Pop3Folder(String name) { super(Pop3Store.this.mAccount); this.mName = name; if (mName.equalsIgnoreCase(mAccount.getInboxFolderName())) { mName = mAccount.getInboxFolderName(); } } @Override public synchronized void open(int mode) throws MessagingException { if (isOpen()) { return; } if (!mName.equalsIgnoreCase(mAccount.getInboxFolderName())) { throw new MessagingException("Folder does not exist"); } try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); final boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, mPort, secure) }, new SecureRandom()); mSocket = TrustedSocketFactory.createSocket(sslContext); } else { mSocket = new Socket(); } mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT); if (!isOpen()) { throw new MessagingException("Unable to connect socket"); } // Eat the banner executeSimpleCommand(null); if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { mCapabilities = getCapabilities(); if (mCapabilities.stls) { - writeLine(STLS_COMMAND); + executeSimpleCommand(STLS_COMMAND); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get( mHost, mPort, secure) }, new SecureRandom()); mSocket = TrustedSocketFactory.createSocket(sslContext, mSocket, mHost, mPort, true); mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT); mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); if (!isOpen()) { throw new MessagingException("Unable to connect socket"); } } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } if (mAuthType == AuthType.CRAM_MD5) { try { String b64Nonce = executeSimpleCommand("AUTH CRAM-MD5").replace("+ ", ""); String b64CRAM = Authentication.computeCramMd5(mUsername, mPassword, b64Nonce); executeSimpleCommand(b64CRAM); } catch (MessagingException me) { throw new AuthenticationFailedException(null, me); } } else { try { executeSimpleCommand(USER_COMMAND + " " + mUsername); executeSimpleCommand(PASS_COMMAND + " " + mPassword, true); } catch (MessagingException me) { throw new AuthenticationFailedException(null, me); } } mCapabilities = getCapabilities(); } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to POP server due to security error.", gse); } catch (IOException ioe) { throw new MessagingException("Unable to open connection to POP server.", ioe); } String response = executeSimpleCommand(STAT_COMMAND); String[] parts = response.split(" "); mMessageCount = Integer.parseInt(parts[1]); mUidToMsgMap.clear(); mMsgNumToMsgMap.clear(); mUidToMsgNumMap.clear(); } @Override public boolean isOpen() { return (mIn != null && mOut != null && mSocket != null && mSocket.isConnected() && !mSocket.isClosed()); } @Override public int getMode() { return Folder.OPEN_MODE_RW; } @Override public void close() { try { if (isOpen()) { executeSimpleCommand(QUIT_COMMAND); } } catch (Exception e) { /* * QUIT may fail if the connection is already closed. We don't care. It's just * being friendly. */ } closeIO(); } private void closeIO() { try { mIn.close(); } catch (Exception e) { /* * May fail if the connection is already closed. */ } try { mOut.close(); } catch (Exception e) { /* * May fail if the connection is already closed. */ } try { mSocket.close(); } catch (Exception e) { /* * May fail if the connection is already closed. */ } mIn = null; mOut = null; mSocket = null; } @Override public String getName() { return mName; } @Override public boolean create(FolderType type) throws MessagingException { return false; } @Override public boolean exists() throws MessagingException { return mName.equalsIgnoreCase(mAccount.getInboxFolderName()); } @Override public int getMessageCount() { return mMessageCount; } @Override public int getUnreadMessageCount() throws MessagingException { return -1; } @Override public int getFlaggedMessageCount() throws MessagingException { return -1; } @Override public Message getMessage(String uid) throws MessagingException { Pop3Message message = mUidToMsgMap.get(uid); if (message == null) { message = new Pop3Message(uid, this); } return message; } @Override public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener) throws MessagingException { if (start < 1 || end < 1 || end < start) { throw new MessagingException(String.format("Invalid message set %d %d", start, end)); } try { indexMsgNums(start, end); } catch (IOException ioe) { throw new MessagingException("getMessages", ioe); } ArrayList<Message> messages = new ArrayList<Message>(); int i = 0; for (int msgNum = start; msgNum <= end; msgNum++) { Pop3Message message = mMsgNumToMsgMap.get(msgNum); if (message == null) { /* * There could be gaps in the message numbers or malformed * responses which lead to "gaps" in mMsgNumToMsgMap. * * See issue 2252 */ continue; } if (listener != null) { listener.messageStarted(message.getUid(), i++, (end - start) + 1); } messages.add(message); if (listener != null) { listener.messageFinished(message, i++, (end - start) + 1); } } return messages.toArray(new Message[messages.size()]); } /** * Ensures that the given message set (from start to end inclusive) * has been queried so that uids are available in the local cache. * @param start * @param end * @throws MessagingException * @throws IOException */ private void indexMsgNums(int start, int end) throws MessagingException, IOException { int unindexedMessageCount = 0; for (int msgNum = start; msgNum <= end; msgNum++) { if (mMsgNumToMsgMap.get(msgNum) == null) { unindexedMessageCount++; } } if (unindexedMessageCount == 0) { return; } if (unindexedMessageCount < 50 && mMessageCount > 5000) { /* * In extreme cases we'll do a UIDL command per message instead of a bulk * download. */ for (int msgNum = start; msgNum <= end; msgNum++) { Pop3Message message = mMsgNumToMsgMap.get(msgNum); if (message == null) { String response = executeSimpleCommand(UIDL_COMMAND + " " + msgNum); // response = "+OK msgNum msgUid" String[] uidParts = response.split(" +"); if (uidParts.length < 3 || !"+OK".equals(uidParts[0])) { Log.e(K9.LOG_TAG, "ERR response: " + response); return; } String msgUid = uidParts[2]; message = new Pop3Message(msgUid, this); indexMessage(msgNum, message); } } } else { String response = executeSimpleCommand(UIDL_COMMAND); while ((response = readLine()) != null) { if (response.equals(".")) { break; } /* * Yet another work-around for buggy server software: * split the response into message number and unique identifier, no matter how many spaces it has * * Example for a malformed response: * 1 2011071307115510400ae3e9e00bmu9 * * Note the three spaces between message number and unique identifier. * See issue 3546 */ String[] uidParts = response.split(" +"); if ((uidParts.length >= 3) && "+OK".equals(uidParts[0])) { /* * At least one server software places a "+OK" in * front of every line in the unique-id listing. * * Fix up the array if we detected this behavior. * See Issue 1237 */ uidParts[0] = uidParts[1]; uidParts[1] = uidParts[2]; } if (uidParts.length >= 2) { Integer msgNum = Integer.valueOf(uidParts[0]); String msgUid = uidParts[1]; if (msgNum >= start && msgNum <= end) { Pop3Message message = mMsgNumToMsgMap.get(msgNum); if (message == null) { message = new Pop3Message(msgUid, this); indexMessage(msgNum, message); } } } } } } private void indexUids(ArrayList<String> uids) throws MessagingException, IOException { HashSet<String> unindexedUids = new HashSet<String>(); for (String uid : uids) { if (mUidToMsgMap.get(uid) == null) { if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { Log.d(K9.LOG_TAG, "Need to index UID " + uid); } unindexedUids.add(uid); } } if (unindexedUids.isEmpty()) { return; } /* * If we are missing uids in the cache the only sure way to * get them is to do a full UIDL list. A possible optimization * would be trying UIDL for the latest X messages and praying. */ String response = executeSimpleCommand(UIDL_COMMAND); while ((response = readLine()) != null) { if (response.equals(".")) { break; } String[] uidParts = response.split(" +"); // Ignore messages without a unique-id if (uidParts.length >= 2) { Integer msgNum = Integer.valueOf(uidParts[0]); String msgUid = uidParts[1]; if (unindexedUids.contains(msgUid)) { if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { Log.d(K9.LOG_TAG, "Got msgNum " + msgNum + " for UID " + msgUid); } Pop3Message message = mUidToMsgMap.get(msgUid); if (message == null) { message = new Pop3Message(msgUid, this); } indexMessage(msgNum, message); } } } } private void indexMessage(int msgNum, Pop3Message message) { if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { Log.d(K9.LOG_TAG, "Adding index for UID " + message.getUid() + " to msgNum " + msgNum); } mMsgNumToMsgMap.put(msgNum, message); mUidToMsgMap.put(message.getUid(), message); mUidToMsgNumMap.put(message.getUid(), msgNum); } @Override public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { throw new UnsupportedOperationException("Pop3: No getMessages"); } @Override public Message[] getMessages(String[] uids, MessageRetrievalListener listener) throws MessagingException { throw new UnsupportedOperationException("Pop3: No getMessages by uids"); } /** * Fetch the items contained in the FetchProfile into the given set of * Messages in as efficient a manner as possible. * @param messages * @param fp * @throws MessagingException */ @Override public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener) throws MessagingException { if (messages == null || messages.length == 0) { return; } ArrayList<String> uids = new ArrayList<String>(); for (Message message : messages) { uids.add(message.getUid()); } try { indexUids(uids); } catch (IOException ioe) { throw new MessagingException("fetch", ioe); } try { if (fp.contains(FetchProfile.Item.ENVELOPE)) { /* * We pass the listener only if there are other things to do in the * FetchProfile. Since fetchEnvelop works in bulk and eveything else * works one at a time if we let fetchEnvelope send events the * event would get sent twice. */ fetchEnvelope(messages, fp.size() == 1 ? listener : null); } } catch (IOException ioe) { throw new MessagingException("fetch", ioe); } for (int i = 0, count = messages.length; i < count; i++) { Message message = messages[i]; if (!(message instanceof Pop3Message)) { throw new MessagingException("Pop3Store.fetch called with non-Pop3 Message"); } Pop3Message pop3Message = (Pop3Message)message; try { if (listener != null && !fp.contains(FetchProfile.Item.ENVELOPE)) { listener.messageStarted(pop3Message.getUid(), i, count); } if (fp.contains(FetchProfile.Item.BODY)) { fetchBody(pop3Message, -1); } else if (fp.contains(FetchProfile.Item.BODY_SANE)) { /* * To convert the suggested download size we take the size * divided by the maximum line size (76). */ if (mAccount.getMaximumAutoDownloadMessageSize() > 0) { fetchBody(pop3Message, (mAccount.getMaximumAutoDownloadMessageSize() / 76)); } else { fetchBody(pop3Message, -1); } } else if (fp.contains(FetchProfile.Item.STRUCTURE)) { /* * If the user is requesting STRUCTURE we are required to set the body * to null since we do not support the function. */ pop3Message.setBody(null); } if (listener != null && !(fp.contains(FetchProfile.Item.ENVELOPE) && fp.size() == 1)) { listener.messageFinished(message, i, count); } } catch (IOException ioe) { throw new MessagingException("Unable to fetch message", ioe); } } } private void fetchEnvelope(Message[] messages, MessageRetrievalListener listener) throws IOException, MessagingException { int unsizedMessages = 0; for (Message message : messages) { if (message.getSize() == -1) { unsizedMessages++; } } if (unsizedMessages == 0) { return; } if (unsizedMessages < 50 && mMessageCount > 5000) { /* * In extreme cases we'll do a command per message instead of a bulk request * to hopefully save some time and bandwidth. */ for (int i = 0, count = messages.length; i < count; i++) { Message message = messages[i]; if (!(message instanceof Pop3Message)) { throw new MessagingException("Pop3Store.fetch called with non-Pop3 Message"); } Pop3Message pop3Message = (Pop3Message)message; if (listener != null) { listener.messageStarted(pop3Message.getUid(), i, count); } String response = executeSimpleCommand(String.format(LIST_COMMAND + " %d", mUidToMsgNumMap.get(pop3Message.getUid()))); String[] listParts = response.split(" "); //int msgNum = Integer.parseInt(listParts[1]); int msgSize = Integer.parseInt(listParts[2]); pop3Message.setSize(msgSize); if (listener != null) { listener.messageFinished(pop3Message, i, count); } } } else { HashSet<String> msgUidIndex = new HashSet<String>(); for (Message message : messages) { msgUidIndex.add(message.getUid()); } int i = 0, count = messages.length; String response = executeSimpleCommand(LIST_COMMAND); while ((response = readLine()) != null) { if (response.equals(".")) { break; } String[] listParts = response.split(" "); int msgNum = Integer.parseInt(listParts[0]); int msgSize = Integer.parseInt(listParts[1]); Pop3Message pop3Message = mMsgNumToMsgMap.get(msgNum); if (pop3Message != null && msgUidIndex.contains(pop3Message.getUid())) { if (listener != null) { listener.messageStarted(pop3Message.getUid(), i, count); } pop3Message.setSize(msgSize); if (listener != null) { listener.messageFinished(pop3Message, i, count); } i++; } } } } /** * Fetches the body of the given message, limiting the downloaded data to the specified * number of lines if possible. * * If lines is -1 the entire message is fetched. This is implemented with RETR for * lines = -1 or TOP for any other value. If the server does not support TOP, RETR is used * instead. */ private void fetchBody(Pop3Message message, int lines) throws IOException, MessagingException { String response = null; // Try hard to use the TOP command if we're not asked to download the whole message. if (lines != -1 && (!mTopNotSupported || mCapabilities.top)) { try { if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3 && !mCapabilities.top) { Log.d(K9.LOG_TAG, "This server doesn't support the CAPA command. " + "Checking to see if the TOP command is supported nevertheless."); } response = executeSimpleCommand(String.format(TOP_COMMAND + " %d %d", mUidToMsgNumMap.get(message.getUid()), lines)); // TOP command is supported. Remember this for the next time. mCapabilities.top = true; } catch (Pop3ErrorResponse e) { if (mCapabilities.top) { // The TOP command should be supported but something went wrong. throw e; } else { if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { Log.d(K9.LOG_TAG, "The server really doesn't support the TOP " + "command. Using RETR instead."); } // Don't try to use the TOP command again. mTopNotSupported = true; } } } if (response == null) { executeSimpleCommand(String.format(RETR_COMMAND + " %d", mUidToMsgNumMap.get(message.getUid()))); } try { message.parse(new Pop3ResponseInputStream(mIn)); // TODO: if we've received fewer lines than requested we also have the complete message. if (lines == -1 || !mCapabilities.top) { message.setFlag(Flag.X_DOWNLOADED_FULL, true); } } catch (MessagingException me) { /* * If we're only downloading headers it's possible * we'll get a broken MIME message which we're not * real worried about. If we've downloaded the body * and can't parse it we need to let the user know. */ if (lines == -1) { throw me; } } } @Override public Map<String, String> appendMessages(Message[] messages) throws MessagingException { return null; } @Override public void delete(boolean recurse) throws MessagingException { } @Override public void delete(Message[] msgs, String trashFolderName) throws MessagingException { setFlags(msgs, new Flag[] { Flag.DELETED }, true); } @Override public String getUidFromMessageId(Message message) throws MessagingException { return null; } @Override public void setFlags(Flag[] flags, boolean value) throws MessagingException { throw new UnsupportedOperationException("POP3: No setFlags(Flag[],boolean)"); } @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) throws MessagingException { if (!value || !Utility.arrayContains(flags, Flag.DELETED)) { /* * The only flagging we support is setting the Deleted flag. */ return; } ArrayList<String> uids = new ArrayList<String>(); try { for (Message message : messages) { uids.add(message.getUid()); } indexUids(uids); } catch (IOException ioe) { throw new MessagingException("Could not get message number for uid " + uids, ioe); } for (Message message : messages) { Integer msgNum = mUidToMsgNumMap.get(message.getUid()); if (msgNum == null) { MessagingException me = new MessagingException("Could not delete message " + message.getUid() + " because no msgNum found; permanent error"); me.setPermanentFailure(true); throw me; } executeSimpleCommand(String.format(DELE_COMMAND + " %s", msgNum)); } } private String readLine() throws IOException { StringBuilder sb = new StringBuilder(); int d = mIn.read(); if (d == -1) { throw new IOException("End of stream reached while trying to read line."); } do { if (((char)d) == '\r') { continue; } else if (((char)d) == '\n') { break; } else { sb.append((char)d); } } while ((d = mIn.read()) != -1); String ret = sb.toString(); if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { Log.d(K9.LOG_TAG, "<<< " + ret); } return ret; } private void writeLine(String s) throws IOException { mOut.write(s.getBytes()); mOut.write('\r'); mOut.write('\n'); mOut.flush(); } private Pop3Capabilities getCapabilities() throws IOException { Pop3Capabilities capabilities = new Pop3Capabilities(); try { String response = executeSimpleCommand(CAPA_COMMAND); while ((response = readLine()) != null) { if (response.equals(".")) { break; } if (response.equalsIgnoreCase(STLS_CAPABILITY)) { capabilities.stls = true; } else if (response.equalsIgnoreCase(UIDL_CAPABILITY)) { capabilities.uidl = true; } else if (response.equalsIgnoreCase(PIPELINING_CAPABILITY)) { capabilities.pipelining = true; } else if (response.equalsIgnoreCase(USER_CAPABILITY)) { capabilities.user = true; } else if (response.equalsIgnoreCase(TOP_CAPABILITY)) { capabilities.top = true; } } if (!capabilities.top) { /* * If the CAPA command is supported but it doesn't advertise support for the * TOP command, we won't check for it manually. */ mTopNotSupported = true; } } catch (MessagingException me) { /* * The server may not support the CAPA command, so we just eat this Exception * and allow the empty capabilities object to be returned. */ } return capabilities; } private String executeSimpleCommand(String command) throws MessagingException { return executeSimpleCommand(command, false); } private String executeSimpleCommand(String command, boolean sensitive) throws MessagingException { try { open(Folder.OPEN_MODE_RW); if (command != null) { if (K9.DEBUG && K9.DEBUG_PROTOCOL_POP3) { if (sensitive && !K9.DEBUG_SENSITIVE) { Log.d(K9.LOG_TAG, ">>> " + "[Command Hidden, Enable Sensitive Debug Logging To Show]"); } else { Log.d(K9.LOG_TAG, ">>> " + command); } } writeLine(command); } String response = readLine(); if (response.length() > 1 && response.charAt(0) == '-') { throw new Pop3ErrorResponse(response); } return response; } catch (MessagingException me) { throw me; } catch (Exception e) { closeIO(); throw new MessagingException("Unable to execute POP3 command", e); } } @Override public boolean isFlagSupported(Flag flag) { return (flag == Flag.DELETED); } @Override public boolean supportsFetchingFlags() { return false; } @Override public boolean equals(Object o) { if (o instanceof Pop3Folder) { return ((Pop3Folder) o).mName.equals(mName); } return super.equals(o); } @Override public int hashCode() { return mName.hashCode(); } }//Pop3Folder static class Pop3Message extends MimeMessage { public Pop3Message(String uid, Pop3Folder folder) { mUid = uid; mFolder = folder; mSize = -1; } public void setSize(int size) { mSize = size; } @Override protected void parse(InputStream in) throws IOException, MessagingException { super.parse(in); } @Override public void setFlag(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set); } @Override public void delete(String trashFolderName) throws MessagingException { // try // { // Poor POP3 users, we can't copy the message to the Trash folder, but they still want a delete setFlag(Flag.DELETED, true); // } // catch (MessagingException me) // { // Log.w(K9.LOG_TAG, "Could not delete non-existent message", me); // } } } static class Pop3Capabilities { public boolean stls; public boolean top; public boolean user; public boolean uidl; public boolean pipelining; @Override public String toString() { return String.format("STLS %b, TOP %b, USER %b, UIDL %b, PIPELINING %b", stls, top, user, uidl, pipelining); } } static class Pop3ResponseInputStream extends InputStream { InputStream mIn; boolean mStartOfLine = true; boolean mFinished; public Pop3ResponseInputStream(InputStream in) { mIn = in; } @Override public int read() throws IOException { if (mFinished) { return -1; } int d = mIn.read(); if (mStartOfLine && d == '.') { d = mIn.read(); if (d == '\r') { mFinished = true; mIn.read(); return -1; } } mStartOfLine = (d == '\n'); return d; } } /** * Exception that is thrown if the server returns an error response. */ static class Pop3ErrorResponse extends MessagingException { private static final long serialVersionUID = 3672087845857867174L; public Pop3ErrorResponse(String message) { super(message, true); } } }
true
true
public synchronized void open(int mode) throws MessagingException { if (isOpen()) { return; } if (!mName.equalsIgnoreCase(mAccount.getInboxFolderName())) { throw new MessagingException("Folder does not exist"); } try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); final boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, mPort, secure) }, new SecureRandom()); mSocket = TrustedSocketFactory.createSocket(sslContext); } else { mSocket = new Socket(); } mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT); if (!isOpen()) { throw new MessagingException("Unable to connect socket"); } // Eat the banner executeSimpleCommand(null); if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { mCapabilities = getCapabilities(); if (mCapabilities.stls) { writeLine(STLS_COMMAND); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get( mHost, mPort, secure) }, new SecureRandom()); mSocket = TrustedSocketFactory.createSocket(sslContext, mSocket, mHost, mPort, true); mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT); mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); if (!isOpen()) { throw new MessagingException("Unable to connect socket"); } } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } if (mAuthType == AuthType.CRAM_MD5) { try { String b64Nonce = executeSimpleCommand("AUTH CRAM-MD5").replace("+ ", ""); String b64CRAM = Authentication.computeCramMd5(mUsername, mPassword, b64Nonce); executeSimpleCommand(b64CRAM); } catch (MessagingException me) { throw new AuthenticationFailedException(null, me); } } else { try { executeSimpleCommand(USER_COMMAND + " " + mUsername); executeSimpleCommand(PASS_COMMAND + " " + mPassword, true); } catch (MessagingException me) { throw new AuthenticationFailedException(null, me); } } mCapabilities = getCapabilities(); } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to POP server due to security error.", gse); } catch (IOException ioe) { throw new MessagingException("Unable to open connection to POP server.", ioe); } String response = executeSimpleCommand(STAT_COMMAND); String[] parts = response.split(" "); mMessageCount = Integer.parseInt(parts[1]); mUidToMsgMap.clear(); mMsgNumToMsgMap.clear(); mUidToMsgNumMap.clear(); }
public synchronized void open(int mode) throws MessagingException { if (isOpen()) { return; } if (!mName.equalsIgnoreCase(mAccount.getInboxFolderName())) { throw new MessagingException("Folder does not exist"); } try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); final boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, mPort, secure) }, new SecureRandom()); mSocket = TrustedSocketFactory.createSocket(sslContext); } else { mSocket = new Socket(); } mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT); if (!isOpen()) { throw new MessagingException("Unable to connect socket"); } // Eat the banner executeSimpleCommand(null); if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { mCapabilities = getCapabilities(); if (mCapabilities.stls) { executeSimpleCommand(STLS_COMMAND); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get( mHost, mPort, secure) }, new SecureRandom()); mSocket = TrustedSocketFactory.createSocket(sslContext, mSocket, mHost, mPort, true); mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT); mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); if (!isOpen()) { throw new MessagingException("Unable to connect socket"); } } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } if (mAuthType == AuthType.CRAM_MD5) { try { String b64Nonce = executeSimpleCommand("AUTH CRAM-MD5").replace("+ ", ""); String b64CRAM = Authentication.computeCramMd5(mUsername, mPassword, b64Nonce); executeSimpleCommand(b64CRAM); } catch (MessagingException me) { throw new AuthenticationFailedException(null, me); } } else { try { executeSimpleCommand(USER_COMMAND + " " + mUsername); executeSimpleCommand(PASS_COMMAND + " " + mPassword, true); } catch (MessagingException me) { throw new AuthenticationFailedException(null, me); } } mCapabilities = getCapabilities(); } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to POP server due to security error.", gse); } catch (IOException ioe) { throw new MessagingException("Unable to open connection to POP server.", ioe); } String response = executeSimpleCommand(STAT_COMMAND); String[] parts = response.split(" "); mMessageCount = Integer.parseInt(parts[1]); mUidToMsgMap.clear(); mMsgNumToMsgMap.clear(); mUidToMsgNumMap.clear(); }
diff --git a/FamousEssentials/src/me/sinnoh/FamousEssentials/FEListener.java b/FamousEssentials/src/me/sinnoh/FamousEssentials/FEListener.java index 1ec36eb..468e3cf 100644 --- a/FamousEssentials/src/me/sinnoh/FamousEssentials/FEListener.java +++ b/FamousEssentials/src/me/sinnoh/FamousEssentials/FEListener.java @@ -1,46 +1,46 @@ package me.sinnoh.FamousEssentials; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.inventory.ItemStack; public class FEListener implements Listener { private FamousEssentials plugin; public FEListener(FamousEssentials instance) { plugin = instance; } public Map<Player, Integer>selectedworld = new HashMap<Player, Integer>(); @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); - if(plugin.getConfig().getStringList("DontDropitems.worlds").contains(player.getWorld().getName())) + if(plugin.getConfig().getStringList("DontDropItems.worlds").contains(player.getWorld().getName())) if(!player.hasPermission("FamousEssentials.keepitems")) { List<ItemStack> drops = event.getDrops(); if(player.getKiller() instanceof Player) { Player killer = player.getKiller(); for(ItemStack i : drops) { killer.getInventory().addItem(i); } drops.clear(); } } } }
true
true
public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); if(plugin.getConfig().getStringList("DontDropitems.worlds").contains(player.getWorld().getName())) if(!player.hasPermission("FamousEssentials.keepitems")) { List<ItemStack> drops = event.getDrops(); if(player.getKiller() instanceof Player) { Player killer = player.getKiller(); for(ItemStack i : drops) { killer.getInventory().addItem(i); } drops.clear(); } } }
public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); if(plugin.getConfig().getStringList("DontDropItems.worlds").contains(player.getWorld().getName())) if(!player.hasPermission("FamousEssentials.keepitems")) { List<ItemStack> drops = event.getDrops(); if(player.getKiller() instanceof Player) { Player killer = player.getKiller(); for(ItemStack i : drops) { killer.getInventory().addItem(i); } drops.clear(); } } }
diff --git a/src/republicaEternityEventIII/republica/devteam/EternityListener.java b/src/republicaEternityEventIII/republica/devteam/EternityListener.java index b393eba..a79c646 100644 --- a/src/republicaEternityEventIII/republica/devteam/EternityListener.java +++ b/src/republicaEternityEventIII/republica/devteam/EternityListener.java @@ -1,41 +1,41 @@ package republicaEternityEventIII.republica.devteam; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerInteractEvent; public class EternityListener implements Listener{ private EternityMain em; public EternityListener(EternityMain em) { super(); this.em = em; } @EventHandler public void onPlayerDamageMethod(EntityDamageEvent e){ if(e.getEntity() instanceof Player){ if(em.getZiminiarPlayer() == e.getEntity()){ - Player pl = (Player) e.getEntity(); + Player pl = (Player) (e.getEntity()); em.boss.ZiminiarHit((Player) pl.getLastDamageCause()); pl.setHealth(20); } } } @EventHandler public void onPlayerPunchThing(PlayerInteractEvent e) { SignPunchingOMatic.checkFor(e); if (em.boss != null) { em.boss.checkForSpells(e); } if (SignPunchingOMatic.changed()) { em.saveResultsSignLocation(); } } }
true
true
public void onPlayerDamageMethod(EntityDamageEvent e){ if(e.getEntity() instanceof Player){ if(em.getZiminiarPlayer() == e.getEntity()){ Player pl = (Player) e.getEntity(); em.boss.ZiminiarHit((Player) pl.getLastDamageCause()); pl.setHealth(20); } } }
public void onPlayerDamageMethod(EntityDamageEvent e){ if(e.getEntity() instanceof Player){ if(em.getZiminiarPlayer() == e.getEntity()){ Player pl = (Player) (e.getEntity()); em.boss.ZiminiarHit((Player) pl.getLastDamageCause()); pl.setHealth(20); } } }
diff --git a/openFaces/source/org/openfaces/renderkit/filter/param/ParametersEditor.java b/openFaces/source/org/openfaces/renderkit/filter/param/ParametersEditor.java index b17a8aa00..819aa4bcb 100644 --- a/openFaces/source/org/openfaces/renderkit/filter/param/ParametersEditor.java +++ b/openFaces/source/org/openfaces/renderkit/filter/param/ParametersEditor.java @@ -1,148 +1,150 @@ /* * OpenFaces - JSF Component Library 2.0 * Copyright (C) 2007-2010, TeamDev Ltd. * [email protected] * Unless agreed in writing the contents of this file are subject to * the GNU Lesser General Public License Version 2.1 (the "LGPL" 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. * Please visit http://openfaces.org/licensing/ for more details. */ package org.openfaces.renderkit.filter.param; import org.openfaces.component.filter.CompositeFilter; import org.openfaces.component.filter.ExpressionFilterCriterion; import org.openfaces.component.filter.FilterCondition; import org.openfaces.component.filter.FilterProperty; import org.openfaces.renderkit.filter.FilterRow; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import java.util.List; import java.util.Map; public abstract class ParametersEditor { protected ExpressionFilterCriterion criterion = new ExpressionFilterCriterion(); protected FilterProperty filterProperty; public ParametersEditor() { } protected ParametersEditor(FilterProperty filterProperty, FilterCondition operation) { this.filterProperty = filterProperty; criterion.setPropertyLocator(filterProperty.getPropertyLocator()); criterion.setCondition(operation); } public void prepare(FacesContext context, CompositeFilter compositeFilter, FilterRow filterRow, UIComponent container){ criterion.setInverse(filterRow.isInverse()); } public abstract void update(FacesContext context, CompositeFilter compositeFilter, FilterRow filterRow, UIComponent container); protected void clearContainer(UIComponent container) { List<UIComponent> children = container.getChildren(); children.clear(); } public ExpressionFilterCriterion getCriterion() { return criterion; } public void setParameters(Map<String, Object> parameters) { this.criterion.getParameters().clear(); this.criterion.getParameters().putAll(parameters); } public static enum ParameterEditorType { DROP_DOWN_PARAMETERS_EDITOR, DATE_CHOOSER_PARAMETERS_EDITOR, TWO_DATE_CHOOSER_PARAMETERS_EDITOR, SPINNER_PARAMETRS_EDITOR, TWO_SPINNER_PARAMETRS_EDITOR, INPUT_TEXT_PARAMETRS_EDITOR } public static ParameterEditorType getParameterEditorType(FilterProperty filterProperty, FilterCondition operation) { + if (operation == null) + operation = FilterCondition.EQUALS; switch (operation) { case LESS_OR_EQUAL: case GREATER_OR_EQUAL: case GREATER: case LESS: switch (filterProperty.getType()) { case DATE: return ParameterEditorType.DATE_CHOOSER_PARAMETERS_EDITOR; case NUMBER: return ParameterEditorType.SPINNER_PARAMETRS_EDITOR; default: return ParameterEditorType.INPUT_TEXT_PARAMETRS_EDITOR; } case BETWEEN: switch (filterProperty.getType()) { case DATE: return ParameterEditorType.TWO_DATE_CHOOSER_PARAMETERS_EDITOR; case NUMBER: return ParameterEditorType.TWO_SPINNER_PARAMETRS_EDITOR; default: throw new UnsupportedOperationException(); } case EQUALS: { switch (filterProperty.getType()) { case DATE: return ParameterEditorType.DATE_CHOOSER_PARAMETERS_EDITOR; case NUMBER: return ParameterEditorType.SPINNER_PARAMETRS_EDITOR; case SELECT: return ParameterEditorType.DROP_DOWN_PARAMETERS_EDITOR; default: if (filterProperty.getDataProvider() != null) { return ParameterEditorType.DROP_DOWN_PARAMETERS_EDITOR; } else { return ParameterEditorType.INPUT_TEXT_PARAMETRS_EDITOR; } } } case CONTAINS: case BEGINS_WITH: case ENDS_WITH: default: return ParameterEditorType.INPUT_TEXT_PARAMETRS_EDITOR; } } public static ParametersEditor getInstance(ParameterEditorType type, FilterProperty filterProperty, FilterCondition operation, Map<String, Object> parameters) { ParametersEditor result; switch (type) { case DROP_DOWN_PARAMETERS_EDITOR: result = new DropDownParametersEditor(filterProperty, operation); break; case DATE_CHOOSER_PARAMETERS_EDITOR: result = new DateChooserParametersEditor(filterProperty, operation); break; case TWO_DATE_CHOOSER_PARAMETERS_EDITOR: result = new TwoDateChooserParametersEditor(filterProperty, operation); break; case SPINNER_PARAMETRS_EDITOR: result = new SpinnerParametersEditor(filterProperty, operation); break; case TWO_SPINNER_PARAMETRS_EDITOR: result = new TwoSpinnerParametersEditor(filterProperty, operation); break; case INPUT_TEXT_PARAMETRS_EDITOR: result = new InputTextParametersEditor(filterProperty, operation); break; default: throw new UnsupportedOperationException(); } if (parameters != null) result.setParameters(parameters); return result; } }
true
true
public static ParameterEditorType getParameterEditorType(FilterProperty filterProperty, FilterCondition operation) { switch (operation) { case LESS_OR_EQUAL: case GREATER_OR_EQUAL: case GREATER: case LESS: switch (filterProperty.getType()) { case DATE: return ParameterEditorType.DATE_CHOOSER_PARAMETERS_EDITOR; case NUMBER: return ParameterEditorType.SPINNER_PARAMETRS_EDITOR; default: return ParameterEditorType.INPUT_TEXT_PARAMETRS_EDITOR; } case BETWEEN: switch (filterProperty.getType()) { case DATE: return ParameterEditorType.TWO_DATE_CHOOSER_PARAMETERS_EDITOR; case NUMBER: return ParameterEditorType.TWO_SPINNER_PARAMETRS_EDITOR; default: throw new UnsupportedOperationException(); } case EQUALS: { switch (filterProperty.getType()) { case DATE: return ParameterEditorType.DATE_CHOOSER_PARAMETERS_EDITOR; case NUMBER: return ParameterEditorType.SPINNER_PARAMETRS_EDITOR; case SELECT: return ParameterEditorType.DROP_DOWN_PARAMETERS_EDITOR; default: if (filterProperty.getDataProvider() != null) { return ParameterEditorType.DROP_DOWN_PARAMETERS_EDITOR; } else { return ParameterEditorType.INPUT_TEXT_PARAMETRS_EDITOR; } } } case CONTAINS: case BEGINS_WITH: case ENDS_WITH: default: return ParameterEditorType.INPUT_TEXT_PARAMETRS_EDITOR; } }
public static ParameterEditorType getParameterEditorType(FilterProperty filterProperty, FilterCondition operation) { if (operation == null) operation = FilterCondition.EQUALS; switch (operation) { case LESS_OR_EQUAL: case GREATER_OR_EQUAL: case GREATER: case LESS: switch (filterProperty.getType()) { case DATE: return ParameterEditorType.DATE_CHOOSER_PARAMETERS_EDITOR; case NUMBER: return ParameterEditorType.SPINNER_PARAMETRS_EDITOR; default: return ParameterEditorType.INPUT_TEXT_PARAMETRS_EDITOR; } case BETWEEN: switch (filterProperty.getType()) { case DATE: return ParameterEditorType.TWO_DATE_CHOOSER_PARAMETERS_EDITOR; case NUMBER: return ParameterEditorType.TWO_SPINNER_PARAMETRS_EDITOR; default: throw new UnsupportedOperationException(); } case EQUALS: { switch (filterProperty.getType()) { case DATE: return ParameterEditorType.DATE_CHOOSER_PARAMETERS_EDITOR; case NUMBER: return ParameterEditorType.SPINNER_PARAMETRS_EDITOR; case SELECT: return ParameterEditorType.DROP_DOWN_PARAMETERS_EDITOR; default: if (filterProperty.getDataProvider() != null) { return ParameterEditorType.DROP_DOWN_PARAMETERS_EDITOR; } else { return ParameterEditorType.INPUT_TEXT_PARAMETRS_EDITOR; } } } case CONTAINS: case BEGINS_WITH: case ENDS_WITH: default: return ParameterEditorType.INPUT_TEXT_PARAMETRS_EDITOR; } }
diff --git a/java/marytts/tools/voiceimport/HMMVoiceDataPreparation.java b/java/marytts/tools/voiceimport/HMMVoiceDataPreparation.java index 22d07d995..7b8a976e0 100644 --- a/java/marytts/tools/voiceimport/HMMVoiceDataPreparation.java +++ b/java/marytts/tools/voiceimport/HMMVoiceDataPreparation.java @@ -1,336 +1,336 @@ /** * The HMM-Based Speech Synthesis System (HTS) * HTS Working Group * * Department of Computer Science * Nagoya Institute of Technology * and * Interdisciplinary Graduate School of Science and Engineering * Tokyo Institute of Technology * * Portions Copyright (c) 2001-2006 * All Rights Reserved. * * Portions Copyright 2000-2007 DFKI GmbH. * All Rights Reserved. * * Permission is hereby granted, free of charge, to use and * distribute this software and its documentation without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of this work, and to permit persons to whom this * work is furnished to do so, subject to the following conditions: * * 1. The source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Any modifications to the source code must be clearly * marked as such. * * 3. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. Otherwise, one * must contact the HTS working group. * * NAGOYA INSTITUTE OF TECHNOLOGY, TOKYO INSTITUTE OF TECHNOLOGY, * HTS WORKING GROUP, AND THE CONTRIBUTORS TO THIS WORK DISCLAIM * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT * SHALL NAGOYA INSTITUTE OF TECHNOLOGY, TOKYO INSTITUTE OF * TECHNOLOGY, HTS WORKING GROUP, NOR THE CONTRIBUTORS BE LIABLE * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTUOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. * */ package marytts.tools.voiceimport; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.SortedMap; import java.util.TreeMap; import marytts.util.io.FileUtils; /** * This program was modified from previous version to: * 1. copy $MARY_BASE/lib/external/hts directory to the voice building directory * 2. check again that all the external necessary programs are installed. * 3. check as before that wav and text directories exist and make convertions: * voiceDir/wav -> voiceDir/hts/data/raw * userProvidedDir/utts (festival format) -> voiceDir/text (one file per transcription) * userProvidedDir/raw move to voiceDir/hts/data/raw * * @author marcela * */ public class HMMVoiceDataPreparation extends VoiceImportComponent{ private DatabaseLayout db; private String name = "HMMVoiceDataPreparation"; public final String USERRAWDIR = name + ".userRawDirectory"; public final String USERUTTDIR = name + ".userUttDirectory"; private String marybase; private String voiceDir; private String soxPath; private String sep; private String dataDir; private String scriptsDir; public String getName(){ return name; } /** * Get the map of properties2values * containing the default values * @return map of props2values */ public SortedMap<String,String> getDefaultProps(DatabaseLayout db){ this.db = db; if (props == null){ props = new TreeMap<String,String>(); props.put(USERRAWDIR, ""); props.put(USERUTTDIR, ""); } return props; } protected void setupHelp(){ props2Help = new TreeMap<String,String>(); props2Help.put(USERRAWDIR, "raw files directory, user provided directory (default empty)"); props2Help.put(USERUTTDIR, "utterance directory (transcriptions in festival format), user provided directory (default empty)"); } /** * Do the computations required by this component. * * @return true on success, false on failure */ public boolean compute() throws Exception{ boolean raw = false; boolean text = false; marybase = db.getProp(db.MARYBASE); voiceDir = db.getProp(db.ROOTDIR); soxPath = db.getExternal(db.SOXPATH); sep = System.getProperty("file.separator"); dataDir = voiceDir + "hts" + sep + "data" + sep; scriptsDir = dataDir + "scripts" + sep; // 1. copy from $MARY_TTS/lib/external/hts directory in the voice building directory - String sourceFolder = marybase + "lib" + sep + "external" + sep + "hts"; + String sourceFolder = marybase + sep + "lib" + sep + "external" + sep + "hts"; String htsFolder = voiceDir + sep + "hts"; FileUtils.copyFolderRecursive(sourceFolder, htsFolder, false); // 2. check again that all the external necessary programs are installed. System.out.println("\nHMMVoiceDataPreparation:\nChecking paths of external programs"); if( !checkExternalPaths() ) return false; // 3. check as before that wav, raw and text directories exist and are in the correct place System.out.println("\nChecking directories and files for running HTS training scripts..."); // default locations of directories: String wavDirName = voiceDir + "wav"; String textDirName = voiceDir + "text"; String rawDirName = dataDir + "raw"; // 3.1 check raw and wav files: String userRawDirName = getProp(USERRAWDIR); if( existWithFiles(rawDirName) ) { raw = true; } else { // check if the user has provided a raw directory if( !userRawDirName.isEmpty() ) { File userRawDir = new File(userRawDirName); // check if user provided raw dir contains files if( existWithFiles(userRawDirName) ) { // copy the user provided raw directory to hts/data/raw/ System.out.println("Copying files from: " + userRawDirName + " to: " + rawDirName); FileUtils.copyFolder(userRawDirName, rawDirName); // the raw files should be the same as in wav file, if wav file empty convert from raw --> wav if( !existWithFiles(wavDirName)) convertRaw2Wav(rawDirName, wavDirName); raw = true; } else System.out.println("User provided raw directory: " + userRawDirName + " does not exist or does not contain files\n"); } // if we still do not have raw files... // then there must be a wav directory, check that it contains files, if so convert wav --> raw if(!raw) { System.out.println("Checking if " + wavDirName + " contains files"); if( existWithFiles(wavDirName) ){ convertWav2Raw(wavDirName, rawDirName); raw = true; } else { System.out.println("There are no wav files in " + wavDirName); } } } // 3.2 check text files: if( existWithFiles(textDirName) ) { text = true; } else { // check if the user has provided a utterance directory String userUttDirName = getProp(USERUTTDIR); if( !userUttDirName.isEmpty() ) { // check if user provided utt dir contains files if( existWithFiles(userUttDirName) ) { // convert utt --> text (transcriptions festival format --> MARY format) convertUtt2Text(userUttDirName, textDirName); text = true; } else System.out.println("User provided utterance directory: " + userUttDirName + " does not exist or does not contain files\n"); } else System.out.println("\nThere are no text files in " + textDirName); } if( raw && text ){ System.out.println("\nHMMVoiceDataPreparation finished:\n" + "HTS scripts copied in current voice building directory\n" + "wav/raw and text directories in place."); return true; } else return false; } /** * Check the paths of all the necessary external programs * @return true if all the paths are defined */ private boolean checkExternalPaths() throws Exception{ boolean result = true; if ( db.getExternal(db.AWKPATH) == null ){ System.out.println(" *Missing path for awk"); result = false; } if (db.getExternal(db.PERLPATH) == null){ System.out.println(" *Missing path for perl"); result = false; } if (db.getExternal(db.BCPATH) == null){ System.out.println(" *Missing path for bc"); result = false; } if (db.getExternal(db.TCLPATH) == null){ System.out.println(" *Missing path for tclsh"); result = false; } if (db.getExternal(db.SOXPATH) == null){ System.out.println(" *Missing path for sox"); result = false; } if(db.getExternal(db.HTSPATH) == null){ System.out.println(" *Missing path for hts/htk"); result = false; } if(db.getExternal(db.HTSENGINEPATH) == null){ System.out.println(" *Missing path for hts_engine"); result = false; } if(db.getExternal(db.SPTKPATH) == null){ System.out.println(" *Missing path for sptk"); result = false; } if(db.getExternal(db.EHMMPATH) == null){ System.out.println(" *Missing path for ehmm"); result = false; } if(!result) System.out.println("Please run MARYBASE/lib/external/check_install_external_programs.sh and check/install the missing programs"); else System.out.println("Paths for all external programs are defined."); return result; } /** * Checks if the directory exist and has files * @param dir * @return */ private boolean existWithFiles(String dirName) { File dir = new File(dirName); if( dir.exists() && dir.list().length>0 ) return true; else return false; } private void convertRaw2Wav(String rawDirName, String wavDirName) { String cmdLine; String raw2wavCmd = scriptsDir + "raw2wav.sh"; System.out.println("Converting raw files to wav from: " + rawDirName + " to: " + wavDirName); File wavDir = new File(wavDirName); if(!wavDir.exists()) wavDir.mkdir(); cmdLine = "chmod +x " + raw2wavCmd; General.launchProc(cmdLine, "raw2wav", voiceDir); cmdLine = raw2wavCmd + " " + soxPath + " " + rawDirName + " " + wavDirName ; General.launchProc(cmdLine, "raw2wav", voiceDir); } private void convertWav2Raw(String wavDirName, String rawDirName) { String cmdLine; String wav2rawCmd = scriptsDir + "wav2raw.sh"; System.out.println("Converting wav files to raw from: " + wavDirName + " to: " + rawDirName); File rawDir = new File(rawDirName); if(!rawDir.exists()) rawDir.mkdir(); cmdLine = "chmod +x " + wav2rawCmd; General.launchProc(cmdLine, "wav2raw", voiceDir); cmdLine = wav2rawCmd + " " + soxPath + " " + wavDirName + " " + rawDirName ; General.launchProc(cmdLine, "wav2raw", voiceDir); } private void convertUtt2Text(String userUttDirName, String textDirName) { String cmdLine; String utt2transCmd = scriptsDir + "utt2trans.sh"; // festival to mary format System.out.println("\nConverting transcription files (festival format) to text from: " + userUttDirName + " to: " + textDirName); File textDir = new File(textDirName); if(!textDir.exists()) textDir.mkdir(); cmdLine = "chmod +x " + utt2transCmd; General.launchProc(cmdLine, "utt2trans", voiceDir); cmdLine = utt2transCmd + " " + userUttDirName + " " + textDirName; General.launchProc(cmdLine, "utt2trans", voiceDir); } /** * Provide the progress of computation, in percent, or -1 if * that feature is not implemented. * @return -1 if not implemented, or an integer between 0 and 100. */ public int getProgress(){ return -1; } }
true
true
public boolean compute() throws Exception{ boolean raw = false; boolean text = false; marybase = db.getProp(db.MARYBASE); voiceDir = db.getProp(db.ROOTDIR); soxPath = db.getExternal(db.SOXPATH); sep = System.getProperty("file.separator"); dataDir = voiceDir + "hts" + sep + "data" + sep; scriptsDir = dataDir + "scripts" + sep; // 1. copy from $MARY_TTS/lib/external/hts directory in the voice building directory String sourceFolder = marybase + "lib" + sep + "external" + sep + "hts"; String htsFolder = voiceDir + sep + "hts"; FileUtils.copyFolderRecursive(sourceFolder, htsFolder, false); // 2. check again that all the external necessary programs are installed. System.out.println("\nHMMVoiceDataPreparation:\nChecking paths of external programs"); if( !checkExternalPaths() ) return false; // 3. check as before that wav, raw and text directories exist and are in the correct place System.out.println("\nChecking directories and files for running HTS training scripts..."); // default locations of directories: String wavDirName = voiceDir + "wav"; String textDirName = voiceDir + "text"; String rawDirName = dataDir + "raw"; // 3.1 check raw and wav files: String userRawDirName = getProp(USERRAWDIR); if( existWithFiles(rawDirName) ) { raw = true; } else { // check if the user has provided a raw directory if( !userRawDirName.isEmpty() ) { File userRawDir = new File(userRawDirName); // check if user provided raw dir contains files if( existWithFiles(userRawDirName) ) { // copy the user provided raw directory to hts/data/raw/ System.out.println("Copying files from: " + userRawDirName + " to: " + rawDirName); FileUtils.copyFolder(userRawDirName, rawDirName); // the raw files should be the same as in wav file, if wav file empty convert from raw --> wav if( !existWithFiles(wavDirName)) convertRaw2Wav(rawDirName, wavDirName); raw = true; } else System.out.println("User provided raw directory: " + userRawDirName + " does not exist or does not contain files\n"); } // if we still do not have raw files... // then there must be a wav directory, check that it contains files, if so convert wav --> raw if(!raw) { System.out.println("Checking if " + wavDirName + " contains files"); if( existWithFiles(wavDirName) ){ convertWav2Raw(wavDirName, rawDirName); raw = true; } else { System.out.println("There are no wav files in " + wavDirName); } } } // 3.2 check text files: if( existWithFiles(textDirName) ) { text = true; } else { // check if the user has provided a utterance directory String userUttDirName = getProp(USERUTTDIR); if( !userUttDirName.isEmpty() ) { // check if user provided utt dir contains files if( existWithFiles(userUttDirName) ) { // convert utt --> text (transcriptions festival format --> MARY format) convertUtt2Text(userUttDirName, textDirName); text = true; } else System.out.println("User provided utterance directory: " + userUttDirName + " does not exist or does not contain files\n"); } else System.out.println("\nThere are no text files in " + textDirName); } if( raw && text ){ System.out.println("\nHMMVoiceDataPreparation finished:\n" + "HTS scripts copied in current voice building directory\n" + "wav/raw and text directories in place."); return true; } else return false; }
public boolean compute() throws Exception{ boolean raw = false; boolean text = false; marybase = db.getProp(db.MARYBASE); voiceDir = db.getProp(db.ROOTDIR); soxPath = db.getExternal(db.SOXPATH); sep = System.getProperty("file.separator"); dataDir = voiceDir + "hts" + sep + "data" + sep; scriptsDir = dataDir + "scripts" + sep; // 1. copy from $MARY_TTS/lib/external/hts directory in the voice building directory String sourceFolder = marybase + sep + "lib" + sep + "external" + sep + "hts"; String htsFolder = voiceDir + sep + "hts"; FileUtils.copyFolderRecursive(sourceFolder, htsFolder, false); // 2. check again that all the external necessary programs are installed. System.out.println("\nHMMVoiceDataPreparation:\nChecking paths of external programs"); if( !checkExternalPaths() ) return false; // 3. check as before that wav, raw and text directories exist and are in the correct place System.out.println("\nChecking directories and files for running HTS training scripts..."); // default locations of directories: String wavDirName = voiceDir + "wav"; String textDirName = voiceDir + "text"; String rawDirName = dataDir + "raw"; // 3.1 check raw and wav files: String userRawDirName = getProp(USERRAWDIR); if( existWithFiles(rawDirName) ) { raw = true; } else { // check if the user has provided a raw directory if( !userRawDirName.isEmpty() ) { File userRawDir = new File(userRawDirName); // check if user provided raw dir contains files if( existWithFiles(userRawDirName) ) { // copy the user provided raw directory to hts/data/raw/ System.out.println("Copying files from: " + userRawDirName + " to: " + rawDirName); FileUtils.copyFolder(userRawDirName, rawDirName); // the raw files should be the same as in wav file, if wav file empty convert from raw --> wav if( !existWithFiles(wavDirName)) convertRaw2Wav(rawDirName, wavDirName); raw = true; } else System.out.println("User provided raw directory: " + userRawDirName + " does not exist or does not contain files\n"); } // if we still do not have raw files... // then there must be a wav directory, check that it contains files, if so convert wav --> raw if(!raw) { System.out.println("Checking if " + wavDirName + " contains files"); if( existWithFiles(wavDirName) ){ convertWav2Raw(wavDirName, rawDirName); raw = true; } else { System.out.println("There are no wav files in " + wavDirName); } } } // 3.2 check text files: if( existWithFiles(textDirName) ) { text = true; } else { // check if the user has provided a utterance directory String userUttDirName = getProp(USERUTTDIR); if( !userUttDirName.isEmpty() ) { // check if user provided utt dir contains files if( existWithFiles(userUttDirName) ) { // convert utt --> text (transcriptions festival format --> MARY format) convertUtt2Text(userUttDirName, textDirName); text = true; } else System.out.println("User provided utterance directory: " + userUttDirName + " does not exist or does not contain files\n"); } else System.out.println("\nThere are no text files in " + textDirName); } if( raw && text ){ System.out.println("\nHMMVoiceDataPreparation finished:\n" + "HTS scripts copied in current voice building directory\n" + "wav/raw and text directories in place."); return true; } else return false; }
diff --git a/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/resolve/BuildMarkerResolutionGenerator.java b/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/resolve/BuildMarkerResolutionGenerator.java index b9a59338..39dab6a2 100644 --- a/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/resolve/BuildMarkerResolutionGenerator.java +++ b/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/resolve/BuildMarkerResolutionGenerator.java @@ -1,310 +1,314 @@ package net.sf.eclipsefp.haskell.ui.internal.resolve; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import net.sf.eclipsefp.haskell.browser.BrowserPlugin; import net.sf.eclipsefp.haskell.browser.Database; import net.sf.eclipsefp.haskell.browser.items.DeclarationId; import net.sf.eclipsefp.haskell.buildwrapper.types.CabalMessages; import net.sf.eclipsefp.haskell.buildwrapper.types.GhcMessages; import net.sf.eclipsefp.haskell.core.HaskellCorePlugin; import net.sf.eclipsefp.haskell.hlint.HLintFixer; import net.sf.eclipsefp.haskell.hlint.Suggestion; import net.sf.eclipsefp.haskell.ui.HaskellUIPlugin; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.ui.IMarkerResolution; import org.eclipse.ui.IMarkerResolutionGenerator; /** * <p>Provides resolutions for markers</p> * * @author JP Moresmau */ public class BuildMarkerResolutionGenerator implements IMarkerResolutionGenerator { @Override public IMarkerResolution[] getResolutions( final IMarker marker ) { if (marker==null || !marker.exists()){ return new IMarkerResolution[0]; } List<IMarkerResolution> res=new ArrayList<IMarkerResolution>(); IMarkerResolution hlr=getHLintResolution( marker ); if (hlr!=null){ res.add( hlr ); } else { if (marker.getAttribute( IMarker.SEVERITY , IMarker.SEVERITY_ERROR)==IMarker.SEVERITY_WARNING || (marker.getAttribute( IMarker.SEVERITY , IMarker.SEVERITY_ERROR)==IMarker.SEVERITY_ERROR)){ String msg=marker.getAttribute(IMarker.MESSAGE,""); //$NON-NLS-1$ if (msg!=null){ String msgL=msg.toLowerCase(Locale.ENGLISH); int ix=-1; // Type signature not found if (msgL.indexOf( GhcMessages.WARNING_NOTYPE_CONTAINS )>-1){ res.add(new MissingTypeWarningResolution(GhcMessages.WARNING_INFERREDTYPE_START)); } else if (msgL.indexOf( GhcMessages.WARNING_NOTYPE_TOPLEVEL_CONTAINS )>-1){ // type is given on next line res.add(new MissingTypeWarningResolution(GhcMessages.WARNING_NOTYPE_TOPLEVEL_CONTAINS)); } // Useless import else if (msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_CONTAINS )>-1){ res.add(new RemoveImportResolution()); int ix2=msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_START ); if (ix2>-1){ String newImport=msg.substring( ix2+GhcMessages.WARNING_IMPORT_USELESS_START.length() ).trim(); res.add( new ReplaceImportResolution( newImport ) ); } } else if (msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_CONTAINS2 )>-1){ if (msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_ELEMENT2 ) > -1) { // Redundant element // 1. Find redundant element int backQuote1 = msg.indexOf( '`' ); int endQuote1 = msg.indexOf( '\'' ); String redundantElement = msg.substring( backQuote1 + 1, endQuote1 ); /*String rest = msg.substring( endQuote1 + 1 ); int backQuote2 = rest.indexOf( '`' ); int endQuote2 = rest.indexOf( '\'' ); String inImport = rest.substring( backQuote2 + 1, endQuote2 );*/ res.add( new RemoveRedundantElementInImportResolution( redundantElement ) ); } else { // Redundant entire import res.add(new RemoveImportResolution()); int ix2=msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_START2 ); if (ix2>-1){ String newImport=msg.substring( ix2+GhcMessages.WARNING_IMPORT_USELESS_START2.length() ).trim(); res.add( new ReplaceImportResolution( newImport ) ); } } } // Language pragma needed else if (addFlagPragma(res,msg,msgL, GhcMessages.WARNING_USEFLAG_CONTAINS,GhcMessages.WARNING_USEFLAG_CONTAINS2,GhcMessages.WARNING_USEFLAG_CONTAINS3)){ // } else if ((ix=msgL.indexOf( GhcMessages.WARNING_SUPPRESS_CONTAINS ))>-1){ int end=ix-2; int ix2=msg.lastIndexOf( ' ',end); if (ix2>-1){ String flag=msg.substring( ix2+1,end+1 ).trim(); addPragma(res,flag); } } else if ((ix=msgL.indexOf( GhcMessages.NOT_ENABLED ))>1){ String flag=msg.substring( 0,ix ).trim(); res.add( new AddLanguagePragmaResolution( flag ) ); } else if ((ix=msgL.indexOf( GhcMessages.PERMITS_THIS ))>1){ int ix2=msg.substring(0,ix).lastIndexOf("(-X"); String flag=msg.substring( ix2+1,ix ).trim(); addPragma(res,flag); } else if ((ix=msgL.indexOf( GhcMessages.TRY ))>1){ int ix2=msg.indexOf(" ",ix+GhcMessages.TRY.length()); if (ix2>-1){ String flag=msg.substring( ix+GhcMessages.TRY.length()-2,ix2).trim(); addPragma(res,flag); } } else if ((ix=msgL.indexOf( GhcMessages.YOU_NEED ))>1){ int ix2=msg.indexOf(" ",ix+GhcMessages.YOU_NEED.length()); if (ix2>-1){ String flag=msg.substring( ix+GhcMessages.YOU_NEED.length()-2,ix2).trim(); addPragma(res,flag); } } else if ((ix=msgL.indexOf( GhcMessages.CAST_FROM_CHAR ))>1){ addPragma( res, "-XOverloadedStrings" ); } // Import a package else if (msgL.indexOf(GhcMessages.MISSING_MODULE)>-1){ int start=GhcMessages.MISSING_MODULE.length(); ix=msgL.indexOf( GhcMessages.MISSING_MODULE_ADD_START,start ); + Set<String> pkgs=new HashSet<String>(); while (ix>-1){ int ix2=msgL.indexOf( GhcMessages.MISSING_MODULE_ADD_END,ix); if (ix2>-1){ String pkg=msg.substring( ix+GhcMessages.MISSING_MODULE_ADD_START.length(),ix2 ); - res.add(new AddPackageDependency( pkg )); + // if the dependency can be found in several versions, we'll get several messages + if (pkgs.add( pkg )){ + res.add(new AddPackageDependency( pkg )); + } ix=ix2; } ix=msgL.indexOf( GhcMessages.MISSING_MODULE_ADD_START,ix+1 ); } } // Not in scope else if (msgL.indexOf( GhcMessages.NOT_IN_SCOPE_START )>-1){ int start = msgL.indexOf( '`',msgL.indexOf( GhcMessages.NOT_IN_SCOPE_START )); int l=msgL.indexOf( "\n",start+1 ); List<String> suggestions=null; if (l>-1){ String sug=msg.substring( l ); suggestions=ReplaceTextResolution.getSuggestionsFromGHCMessage( sug,msgL.substring( l ) ); msgL=msgL.substring( 0,l ); } int end = msgL.lastIndexOf( GhcMessages.NOT_IN_SCOPE_END ); String notInScope = msg.substring( start + 1, end ); String name, qualified; int pointPos = notInScope.lastIndexOf( '.' ); if (pointPos != -1) { name = notInScope.substring( pointPos + 1 ); qualified = notInScope.substring( 0, pointPos ); } else { name = notInScope; qualified = null; } if (suggestions!=null){ for (String suggestion:suggestions){ res.add( new ReplaceTextResolution( notInScope, suggestion ) ); } } try { if (BrowserPlugin.getSharedInstance().isAnyDatabaseLoaded() && !BrowserPlugin.getSharedInstance().isRunning()) { //BrowserPlugin.getSharedInstance().setCurrentDatabase( DatabaseType.ALL, null ); DeclarationId[] availableMods = BrowserPlugin.getSharedInstance().findModulesForDeclaration(Database.ALL, name ); /*ArrayList<String> places = new ArrayList<String>(); for (DeclarationId avMod : availableMods) { if (!places.contains( avMod.getName() )) { places.add( avMod.getName() ); } } Collections.sort( places );*/ Arrays.sort(availableMods,new Comparator<DeclarationId>() { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare( final DeclarationId o1, final DeclarationId o2 ) { int c=o1.getModule().getName().compareToIgnoreCase( o2.getModule().getName() ); if (c==0){ c=o1.getName().compareTo( o2.getName() ); } return c; } }); Set<String> modules=new HashSet<String>(); for (DeclarationId place : availableMods) { String module=place.getModule().getName(); if (!modules.contains(module )){ modules.add(module); if (place.getName().length()>0){ res.add( new AddImportResolution( place.getName()+"(..)", module, qualified ) ); res.add( new AddImportResolution( place.getName()+"("+name+")", module, qualified ) ); } else { res.add( new AddImportResolution( name, module, qualified ) ); } } } } } catch (Exception e) { // Do nothing } } else if (msgL.indexOf( GhcMessages.IS_A_DATA_CONSTRUCTOR )>-1){ int btix=msg.indexOf('`'); int sqix=msg.indexOf('\'',btix); //String module=msg.substring(btix+1,sqix); btix=msg.indexOf('`',sqix); sqix=msg.indexOf('\'',btix); String constructor=msg.substring(btix+1,sqix); btix=msg.indexOf('`',sqix); sqix=msg.indexOf('\'',btix); String type=msg.substring(btix+1,sqix); res.add( new ReplaceImportElement( constructor, type+"("+constructor+")" ) ); res.add( new ReplaceImportElement( constructor, type+"(..)" ) ); /* btix=msg.indexOf('`',btix+1); sqix=msg.indexOf('\'',btix); String import1=msg.substring(btix+1,sqix); btix=msg.indexOf('`',sqix); sqix=msg.indexOf('\'',btix); String import2=msg.substring(btix+1,sqix); res.add(new ReplaceImportResolution( import1 )); res.add(new ReplaceImportResolution( import2 ));*/ /* Description Resource Path Location Type ID In module `System.Exit': `ExitFailure' is a data constructor of `ExitCode' To import it use `import System.Exit (ExitCode (ExitFailure))' or `import System.Exit (ExitCode (..))' Main.hs /nxt/test line 16 Haskell Problem 39935*/ } else if (msgL.indexOf( GhcMessages.DO_DISCARDED_START )>-1){ res.add(new AddGhcPragmaResolution( "-fno-warn-unused-do-bind" )); res.add(new AddGHCOptionResolution( "-fno-warn-unused-do-bind" )); // int fixIx=msgL.indexOf( GhcMessages.DO_DISCARDED_FIX ); // if (fixIx>-1){ // // } } else if ((ix=msgL.indexOf( CabalMessages.DEPENDENCIES_MISSING ))>-1){ int nlid=msg.indexOf( "\n",ix ); Set<String> all=new HashSet<String>(); for (String s:msg.substring( nlid ).split( "\\n" )){ s=s.trim(); if (s.length()>0){ if (s.endsWith( CabalMessages.ANY)){ s=s.substring( 0,s.length()-CabalMessages.ANY.length() ).trim(); } all.add(s); res.add(new InstallMissingPackage( Collections.singleton( s ) )); } } if (all.size()>1){ res.add(new InstallMissingPackage( all )); } } } } } return res.toArray( new IMarkerResolution[res.size()] ); } private IMarkerResolution getHLintResolution(final IMarker marker) { try { if (marker.getType().equals(HaskellCorePlugin.ID_HLINT_MARKER)){ Suggestion s=new Suggestion(); s.fromString( marker.getAttribute( HaskellCorePlugin.ATT_HLINT_SUGGESTION,"" )); if (HLintFixer.canFix( s )){ return new HLintResolution(); } } }catch (CoreException ce){ HaskellUIPlugin.log( ce ); } return null; } private boolean addFlagPragma(final List<IMarkerResolution> res,final String msg,final String msgL,final String... toSearch){ int ix=-1; for (String s:toSearch){ if ((ix=msgL.indexOf( s ))>-1){ if (s.endsWith( " -x" )){ s=s.substring( s.length()-3 ); } int start=ix+1+s.length(); int ix2=start; for (;ix2<msg.length();ix2++){ if (Character.isWhitespace( msg.charAt( ix2 ) )){ break; } } if (ix2<msg.length()){ String flag=msg.substring( start,ix2 ).trim(); addPragma(res,flag); } else { String flag=msg.substring( start).trim(); addPragma(res,flag); } return true; } } return false; } private void addPragma(final List<IMarkerResolution> res,final String flag){ if (flag!=null && flag.length()>2 && flag.startsWith( "-X" )){ //$NON-NLS-1$ res.add( new AddLanguagePragmaResolution( flag.substring( 2 ) ) ); } } }
false
true
public IMarkerResolution[] getResolutions( final IMarker marker ) { if (marker==null || !marker.exists()){ return new IMarkerResolution[0]; } List<IMarkerResolution> res=new ArrayList<IMarkerResolution>(); IMarkerResolution hlr=getHLintResolution( marker ); if (hlr!=null){ res.add( hlr ); } else { if (marker.getAttribute( IMarker.SEVERITY , IMarker.SEVERITY_ERROR)==IMarker.SEVERITY_WARNING || (marker.getAttribute( IMarker.SEVERITY , IMarker.SEVERITY_ERROR)==IMarker.SEVERITY_ERROR)){ String msg=marker.getAttribute(IMarker.MESSAGE,""); //$NON-NLS-1$ if (msg!=null){ String msgL=msg.toLowerCase(Locale.ENGLISH); int ix=-1; // Type signature not found if (msgL.indexOf( GhcMessages.WARNING_NOTYPE_CONTAINS )>-1){ res.add(new MissingTypeWarningResolution(GhcMessages.WARNING_INFERREDTYPE_START)); } else if (msgL.indexOf( GhcMessages.WARNING_NOTYPE_TOPLEVEL_CONTAINS )>-1){ // type is given on next line res.add(new MissingTypeWarningResolution(GhcMessages.WARNING_NOTYPE_TOPLEVEL_CONTAINS)); } // Useless import else if (msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_CONTAINS )>-1){ res.add(new RemoveImportResolution()); int ix2=msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_START ); if (ix2>-1){ String newImport=msg.substring( ix2+GhcMessages.WARNING_IMPORT_USELESS_START.length() ).trim(); res.add( new ReplaceImportResolution( newImport ) ); } } else if (msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_CONTAINS2 )>-1){ if (msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_ELEMENT2 ) > -1) { // Redundant element // 1. Find redundant element int backQuote1 = msg.indexOf( '`' ); int endQuote1 = msg.indexOf( '\'' ); String redundantElement = msg.substring( backQuote1 + 1, endQuote1 ); /*String rest = msg.substring( endQuote1 + 1 ); int backQuote2 = rest.indexOf( '`' ); int endQuote2 = rest.indexOf( '\'' ); String inImport = rest.substring( backQuote2 + 1, endQuote2 );*/ res.add( new RemoveRedundantElementInImportResolution( redundantElement ) ); } else { // Redundant entire import res.add(new RemoveImportResolution()); int ix2=msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_START2 ); if (ix2>-1){ String newImport=msg.substring( ix2+GhcMessages.WARNING_IMPORT_USELESS_START2.length() ).trim(); res.add( new ReplaceImportResolution( newImport ) ); } } } // Language pragma needed else if (addFlagPragma(res,msg,msgL, GhcMessages.WARNING_USEFLAG_CONTAINS,GhcMessages.WARNING_USEFLAG_CONTAINS2,GhcMessages.WARNING_USEFLAG_CONTAINS3)){ // } else if ((ix=msgL.indexOf( GhcMessages.WARNING_SUPPRESS_CONTAINS ))>-1){ int end=ix-2; int ix2=msg.lastIndexOf( ' ',end); if (ix2>-1){ String flag=msg.substring( ix2+1,end+1 ).trim(); addPragma(res,flag); } } else if ((ix=msgL.indexOf( GhcMessages.NOT_ENABLED ))>1){ String flag=msg.substring( 0,ix ).trim(); res.add( new AddLanguagePragmaResolution( flag ) ); } else if ((ix=msgL.indexOf( GhcMessages.PERMITS_THIS ))>1){ int ix2=msg.substring(0,ix).lastIndexOf("(-X"); String flag=msg.substring( ix2+1,ix ).trim(); addPragma(res,flag); } else if ((ix=msgL.indexOf( GhcMessages.TRY ))>1){ int ix2=msg.indexOf(" ",ix+GhcMessages.TRY.length()); if (ix2>-1){ String flag=msg.substring( ix+GhcMessages.TRY.length()-2,ix2).trim(); addPragma(res,flag); } } else if ((ix=msgL.indexOf( GhcMessages.YOU_NEED ))>1){ int ix2=msg.indexOf(" ",ix+GhcMessages.YOU_NEED.length()); if (ix2>-1){ String flag=msg.substring( ix+GhcMessages.YOU_NEED.length()-2,ix2).trim(); addPragma(res,flag); } } else if ((ix=msgL.indexOf( GhcMessages.CAST_FROM_CHAR ))>1){ addPragma( res, "-XOverloadedStrings" ); } // Import a package else if (msgL.indexOf(GhcMessages.MISSING_MODULE)>-1){ int start=GhcMessages.MISSING_MODULE.length(); ix=msgL.indexOf( GhcMessages.MISSING_MODULE_ADD_START,start ); while (ix>-1){ int ix2=msgL.indexOf( GhcMessages.MISSING_MODULE_ADD_END,ix); if (ix2>-1){ String pkg=msg.substring( ix+GhcMessages.MISSING_MODULE_ADD_START.length(),ix2 ); res.add(new AddPackageDependency( pkg )); ix=ix2; } ix=msgL.indexOf( GhcMessages.MISSING_MODULE_ADD_START,ix+1 ); } } // Not in scope else if (msgL.indexOf( GhcMessages.NOT_IN_SCOPE_START )>-1){ int start = msgL.indexOf( '`',msgL.indexOf( GhcMessages.NOT_IN_SCOPE_START )); int l=msgL.indexOf( "\n",start+1 ); List<String> suggestions=null; if (l>-1){ String sug=msg.substring( l ); suggestions=ReplaceTextResolution.getSuggestionsFromGHCMessage( sug,msgL.substring( l ) ); msgL=msgL.substring( 0,l ); } int end = msgL.lastIndexOf( GhcMessages.NOT_IN_SCOPE_END ); String notInScope = msg.substring( start + 1, end ); String name, qualified; int pointPos = notInScope.lastIndexOf( '.' ); if (pointPos != -1) { name = notInScope.substring( pointPos + 1 ); qualified = notInScope.substring( 0, pointPos ); } else { name = notInScope; qualified = null; } if (suggestions!=null){ for (String suggestion:suggestions){ res.add( new ReplaceTextResolution( notInScope, suggestion ) ); } } try { if (BrowserPlugin.getSharedInstance().isAnyDatabaseLoaded() && !BrowserPlugin.getSharedInstance().isRunning()) { //BrowserPlugin.getSharedInstance().setCurrentDatabase( DatabaseType.ALL, null ); DeclarationId[] availableMods = BrowserPlugin.getSharedInstance().findModulesForDeclaration(Database.ALL, name ); /*ArrayList<String> places = new ArrayList<String>(); for (DeclarationId avMod : availableMods) { if (!places.contains( avMod.getName() )) { places.add( avMod.getName() ); } } Collections.sort( places );*/ Arrays.sort(availableMods,new Comparator<DeclarationId>() { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare( final DeclarationId o1, final DeclarationId o2 ) { int c=o1.getModule().getName().compareToIgnoreCase( o2.getModule().getName() ); if (c==0){ c=o1.getName().compareTo( o2.getName() ); } return c; } }); Set<String> modules=new HashSet<String>(); for (DeclarationId place : availableMods) { String module=place.getModule().getName(); if (!modules.contains(module )){ modules.add(module); if (place.getName().length()>0){ res.add( new AddImportResolution( place.getName()+"(..)", module, qualified ) ); res.add( new AddImportResolution( place.getName()+"("+name+")", module, qualified ) ); } else { res.add( new AddImportResolution( name, module, qualified ) ); } } } } } catch (Exception e) { // Do nothing } } else if (msgL.indexOf( GhcMessages.IS_A_DATA_CONSTRUCTOR )>-1){ int btix=msg.indexOf('`'); int sqix=msg.indexOf('\'',btix); //String module=msg.substring(btix+1,sqix); btix=msg.indexOf('`',sqix); sqix=msg.indexOf('\'',btix); String constructor=msg.substring(btix+1,sqix); btix=msg.indexOf('`',sqix); sqix=msg.indexOf('\'',btix); String type=msg.substring(btix+1,sqix); res.add( new ReplaceImportElement( constructor, type+"("+constructor+")" ) ); res.add( new ReplaceImportElement( constructor, type+"(..)" ) ); /* btix=msg.indexOf('`',btix+1); sqix=msg.indexOf('\'',btix); String import1=msg.substring(btix+1,sqix); btix=msg.indexOf('`',sqix); sqix=msg.indexOf('\'',btix); String import2=msg.substring(btix+1,sqix); res.add(new ReplaceImportResolution( import1 )); res.add(new ReplaceImportResolution( import2 ));*/ /* Description Resource Path Location Type ID In module `System.Exit': `ExitFailure' is a data constructor of `ExitCode' To import it use `import System.Exit (ExitCode (ExitFailure))' or `import System.Exit (ExitCode (..))' Main.hs /nxt/test line 16 Haskell Problem 39935*/ } else if (msgL.indexOf( GhcMessages.DO_DISCARDED_START )>-1){ res.add(new AddGhcPragmaResolution( "-fno-warn-unused-do-bind" )); res.add(new AddGHCOptionResolution( "-fno-warn-unused-do-bind" )); // int fixIx=msgL.indexOf( GhcMessages.DO_DISCARDED_FIX ); // if (fixIx>-1){ // // } } else if ((ix=msgL.indexOf( CabalMessages.DEPENDENCIES_MISSING ))>-1){ int nlid=msg.indexOf( "\n",ix ); Set<String> all=new HashSet<String>(); for (String s:msg.substring( nlid ).split( "\\n" )){ s=s.trim(); if (s.length()>0){ if (s.endsWith( CabalMessages.ANY)){ s=s.substring( 0,s.length()-CabalMessages.ANY.length() ).trim(); } all.add(s); res.add(new InstallMissingPackage( Collections.singleton( s ) )); } } if (all.size()>1){ res.add(new InstallMissingPackage( all )); } } } } } return res.toArray( new IMarkerResolution[res.size()] ); }
public IMarkerResolution[] getResolutions( final IMarker marker ) { if (marker==null || !marker.exists()){ return new IMarkerResolution[0]; } List<IMarkerResolution> res=new ArrayList<IMarkerResolution>(); IMarkerResolution hlr=getHLintResolution( marker ); if (hlr!=null){ res.add( hlr ); } else { if (marker.getAttribute( IMarker.SEVERITY , IMarker.SEVERITY_ERROR)==IMarker.SEVERITY_WARNING || (marker.getAttribute( IMarker.SEVERITY , IMarker.SEVERITY_ERROR)==IMarker.SEVERITY_ERROR)){ String msg=marker.getAttribute(IMarker.MESSAGE,""); //$NON-NLS-1$ if (msg!=null){ String msgL=msg.toLowerCase(Locale.ENGLISH); int ix=-1; // Type signature not found if (msgL.indexOf( GhcMessages.WARNING_NOTYPE_CONTAINS )>-1){ res.add(new MissingTypeWarningResolution(GhcMessages.WARNING_INFERREDTYPE_START)); } else if (msgL.indexOf( GhcMessages.WARNING_NOTYPE_TOPLEVEL_CONTAINS )>-1){ // type is given on next line res.add(new MissingTypeWarningResolution(GhcMessages.WARNING_NOTYPE_TOPLEVEL_CONTAINS)); } // Useless import else if (msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_CONTAINS )>-1){ res.add(new RemoveImportResolution()); int ix2=msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_START ); if (ix2>-1){ String newImport=msg.substring( ix2+GhcMessages.WARNING_IMPORT_USELESS_START.length() ).trim(); res.add( new ReplaceImportResolution( newImport ) ); } } else if (msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_CONTAINS2 )>-1){ if (msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_ELEMENT2 ) > -1) { // Redundant element // 1. Find redundant element int backQuote1 = msg.indexOf( '`' ); int endQuote1 = msg.indexOf( '\'' ); String redundantElement = msg.substring( backQuote1 + 1, endQuote1 ); /*String rest = msg.substring( endQuote1 + 1 ); int backQuote2 = rest.indexOf( '`' ); int endQuote2 = rest.indexOf( '\'' ); String inImport = rest.substring( backQuote2 + 1, endQuote2 );*/ res.add( new RemoveRedundantElementInImportResolution( redundantElement ) ); } else { // Redundant entire import res.add(new RemoveImportResolution()); int ix2=msgL.indexOf( GhcMessages.WARNING_IMPORT_USELESS_START2 ); if (ix2>-1){ String newImport=msg.substring( ix2+GhcMessages.WARNING_IMPORT_USELESS_START2.length() ).trim(); res.add( new ReplaceImportResolution( newImport ) ); } } } // Language pragma needed else if (addFlagPragma(res,msg,msgL, GhcMessages.WARNING_USEFLAG_CONTAINS,GhcMessages.WARNING_USEFLAG_CONTAINS2,GhcMessages.WARNING_USEFLAG_CONTAINS3)){ // } else if ((ix=msgL.indexOf( GhcMessages.WARNING_SUPPRESS_CONTAINS ))>-1){ int end=ix-2; int ix2=msg.lastIndexOf( ' ',end); if (ix2>-1){ String flag=msg.substring( ix2+1,end+1 ).trim(); addPragma(res,flag); } } else if ((ix=msgL.indexOf( GhcMessages.NOT_ENABLED ))>1){ String flag=msg.substring( 0,ix ).trim(); res.add( new AddLanguagePragmaResolution( flag ) ); } else if ((ix=msgL.indexOf( GhcMessages.PERMITS_THIS ))>1){ int ix2=msg.substring(0,ix).lastIndexOf("(-X"); String flag=msg.substring( ix2+1,ix ).trim(); addPragma(res,flag); } else if ((ix=msgL.indexOf( GhcMessages.TRY ))>1){ int ix2=msg.indexOf(" ",ix+GhcMessages.TRY.length()); if (ix2>-1){ String flag=msg.substring( ix+GhcMessages.TRY.length()-2,ix2).trim(); addPragma(res,flag); } } else if ((ix=msgL.indexOf( GhcMessages.YOU_NEED ))>1){ int ix2=msg.indexOf(" ",ix+GhcMessages.YOU_NEED.length()); if (ix2>-1){ String flag=msg.substring( ix+GhcMessages.YOU_NEED.length()-2,ix2).trim(); addPragma(res,flag); } } else if ((ix=msgL.indexOf( GhcMessages.CAST_FROM_CHAR ))>1){ addPragma( res, "-XOverloadedStrings" ); } // Import a package else if (msgL.indexOf(GhcMessages.MISSING_MODULE)>-1){ int start=GhcMessages.MISSING_MODULE.length(); ix=msgL.indexOf( GhcMessages.MISSING_MODULE_ADD_START,start ); Set<String> pkgs=new HashSet<String>(); while (ix>-1){ int ix2=msgL.indexOf( GhcMessages.MISSING_MODULE_ADD_END,ix); if (ix2>-1){ String pkg=msg.substring( ix+GhcMessages.MISSING_MODULE_ADD_START.length(),ix2 ); // if the dependency can be found in several versions, we'll get several messages if (pkgs.add( pkg )){ res.add(new AddPackageDependency( pkg )); } ix=ix2; } ix=msgL.indexOf( GhcMessages.MISSING_MODULE_ADD_START,ix+1 ); } } // Not in scope else if (msgL.indexOf( GhcMessages.NOT_IN_SCOPE_START )>-1){ int start = msgL.indexOf( '`',msgL.indexOf( GhcMessages.NOT_IN_SCOPE_START )); int l=msgL.indexOf( "\n",start+1 ); List<String> suggestions=null; if (l>-1){ String sug=msg.substring( l ); suggestions=ReplaceTextResolution.getSuggestionsFromGHCMessage( sug,msgL.substring( l ) ); msgL=msgL.substring( 0,l ); } int end = msgL.lastIndexOf( GhcMessages.NOT_IN_SCOPE_END ); String notInScope = msg.substring( start + 1, end ); String name, qualified; int pointPos = notInScope.lastIndexOf( '.' ); if (pointPos != -1) { name = notInScope.substring( pointPos + 1 ); qualified = notInScope.substring( 0, pointPos ); } else { name = notInScope; qualified = null; } if (suggestions!=null){ for (String suggestion:suggestions){ res.add( new ReplaceTextResolution( notInScope, suggestion ) ); } } try { if (BrowserPlugin.getSharedInstance().isAnyDatabaseLoaded() && !BrowserPlugin.getSharedInstance().isRunning()) { //BrowserPlugin.getSharedInstance().setCurrentDatabase( DatabaseType.ALL, null ); DeclarationId[] availableMods = BrowserPlugin.getSharedInstance().findModulesForDeclaration(Database.ALL, name ); /*ArrayList<String> places = new ArrayList<String>(); for (DeclarationId avMod : availableMods) { if (!places.contains( avMod.getName() )) { places.add( avMod.getName() ); } } Collections.sort( places );*/ Arrays.sort(availableMods,new Comparator<DeclarationId>() { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare( final DeclarationId o1, final DeclarationId o2 ) { int c=o1.getModule().getName().compareToIgnoreCase( o2.getModule().getName() ); if (c==0){ c=o1.getName().compareTo( o2.getName() ); } return c; } }); Set<String> modules=new HashSet<String>(); for (DeclarationId place : availableMods) { String module=place.getModule().getName(); if (!modules.contains(module )){ modules.add(module); if (place.getName().length()>0){ res.add( new AddImportResolution( place.getName()+"(..)", module, qualified ) ); res.add( new AddImportResolution( place.getName()+"("+name+")", module, qualified ) ); } else { res.add( new AddImportResolution( name, module, qualified ) ); } } } } } catch (Exception e) { // Do nothing } } else if (msgL.indexOf( GhcMessages.IS_A_DATA_CONSTRUCTOR )>-1){ int btix=msg.indexOf('`'); int sqix=msg.indexOf('\'',btix); //String module=msg.substring(btix+1,sqix); btix=msg.indexOf('`',sqix); sqix=msg.indexOf('\'',btix); String constructor=msg.substring(btix+1,sqix); btix=msg.indexOf('`',sqix); sqix=msg.indexOf('\'',btix); String type=msg.substring(btix+1,sqix); res.add( new ReplaceImportElement( constructor, type+"("+constructor+")" ) ); res.add( new ReplaceImportElement( constructor, type+"(..)" ) ); /* btix=msg.indexOf('`',btix+1); sqix=msg.indexOf('\'',btix); String import1=msg.substring(btix+1,sqix); btix=msg.indexOf('`',sqix); sqix=msg.indexOf('\'',btix); String import2=msg.substring(btix+1,sqix); res.add(new ReplaceImportResolution( import1 )); res.add(new ReplaceImportResolution( import2 ));*/ /* Description Resource Path Location Type ID In module `System.Exit': `ExitFailure' is a data constructor of `ExitCode' To import it use `import System.Exit (ExitCode (ExitFailure))' or `import System.Exit (ExitCode (..))' Main.hs /nxt/test line 16 Haskell Problem 39935*/ } else if (msgL.indexOf( GhcMessages.DO_DISCARDED_START )>-1){ res.add(new AddGhcPragmaResolution( "-fno-warn-unused-do-bind" )); res.add(new AddGHCOptionResolution( "-fno-warn-unused-do-bind" )); // int fixIx=msgL.indexOf( GhcMessages.DO_DISCARDED_FIX ); // if (fixIx>-1){ // // } } else if ((ix=msgL.indexOf( CabalMessages.DEPENDENCIES_MISSING ))>-1){ int nlid=msg.indexOf( "\n",ix ); Set<String> all=new HashSet<String>(); for (String s:msg.substring( nlid ).split( "\\n" )){ s=s.trim(); if (s.length()>0){ if (s.endsWith( CabalMessages.ANY)){ s=s.substring( 0,s.length()-CabalMessages.ANY.length() ).trim(); } all.add(s); res.add(new InstallMissingPackage( Collections.singleton( s ) )); } } if (all.size()>1){ res.add(new InstallMissingPackage( all )); } } } } } return res.toArray( new IMarkerResolution[res.size()] ); }
diff --git a/src/co/networkery/uvbeenzaned/Round.java b/src/co/networkery/uvbeenzaned/Round.java index c9b6044..6789dc6 100644 --- a/src/co/networkery/uvbeenzaned/Round.java +++ b/src/co/networkery/uvbeenzaned/Round.java @@ -1,126 +1,120 @@ package co.networkery.uvbeenzaned; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.Timer; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; public class Round { public static String pg = ChatColor.GOLD + "[" + ChatColor.AQUA + "Snowballer" + ChatColor.GOLD + "] " + ChatColor.RESET; public static ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { if(SnowballerListener.timergame == true && SnowballerListener.gameon == false) { if(!SnowballerListener.teamcyan.isEmpty() && !SnowballerListener.teamlime.isEmpty()) { Chat.sendAllTeamsMsg(pg + "Starting next round...."); randomMap(); SnowballerListener.gameon = true; } else { if(SnowballerListener.teamlime.isEmpty()) { Chat.cyanMsg(pg + "There are no players on team " + ChatColor.GREEN + "LIME " + ChatColor.RESET + "to play with."); Chat.cyanMsg(pg + "Stopping game and waiting for another player to join...."); timer.stop(); SnowballerListener.gameon = false; SnowballerListener.timergame = false; } if(SnowballerListener.teamcyan.isEmpty()) { Chat.limeMsg(pg + "There are no players on team " + ChatColor.AQUA + "CYAN " + ChatColor.RESET + "to play with."); Chat.limeMsg(pg + "Stopping game and waiting for another player to join...."); timer.stop(); SnowballerListener.gameon = false; SnowballerListener.timergame = false; } } } } }; public static Timer timer; public static void startIndependentTimerRound() { if(SnowballerListener.timergame == true && SnowballerListener.gameon == false) { if(!SnowballerListener.teamcyan.isEmpty() && !SnowballerListener.teamlime.isEmpty()) { timer = new Timer(SnowballerListener.config.getConfig().getInt("timerdelay"), taskPerformer); timer.setRepeats(false); timer.start(); Chat.sendAllTeamsMsg(pg + "Next round starts in " + Integer.toString(SnowballerListener.config.getConfig().getInt("timerdelay") / 1000) + " seconds!"); } else { if(SnowballerListener.teamlime.isEmpty()) { Chat.cyanMsg(pg + "There are no players on team " + ChatColor.GREEN + "LIME " + ChatColor.RESET + "to play with."); Chat.cyanMsg(pg + "Waiting for another player to join...."); } if(SnowballerListener.teamcyan.isEmpty()) { Chat.limeMsg(pg + "There are no players on team " + ChatColor.AQUA + "CYAN " + ChatColor.RESET + "to play with."); Chat.limeMsg(pg + "Waiting for another player to join...."); } } } } public static Random r = new Random(); public static void randomMap() { SnowballerListener.hitcnts.clear(); r.setSeed(System.currentTimeMillis()); int mapnum = r.nextInt(SnowballerListener.config.getConfig().getConfigurationSection("teamcyanarenasides").getKeys(false).size()); int i = 0; for(String key : SnowballerListener.config.getConfig().getConfigurationSection("teamcyanarenasides").getKeys(false)) { if(mapnum == i) { //attempt at the invis tp glitch for(String pl : SnowballerListener.teamcyan) { Bukkit.getPlayer(pl).setRemoveWhenFarAway(false); } for(String pl : SnowballerListener.teamlime) { Bukkit.getPlayer(pl).setRemoveWhenFarAway(false); } for(String pl : SnowballerListener.teamcyan) { Bukkit.getPlayer(pl).getInventory().clear(); SnowballerListener.giveSnowballs(Bukkit.getPlayer(pl)); SnowballerListener.teamcyaninarena.add(pl); Bukkit.getPlayer(pl).teleport(LTSTL.str2loc(SnowballerListener.config.getConfig().getString("teamcyanarenasides." + key))); - if(Bukkit.getPlayer(pl).getGameMode() == GameMode.CREATIVE) - { - Bukkit.getPlayer(pl).setGameMode(GameMode.SURVIVAL); - } + Bukkit.getPlayer(pl).setGameMode(GameMode.SURVIVAL); } for(String pl : SnowballerListener.teamlime) { Bukkit.getPlayer(pl).getInventory().clear(); SnowballerListener.giveSnowballs(Bukkit.getPlayer(pl)); SnowballerListener.teamlimeinarena.add(pl); Bukkit.getPlayer(pl).teleport(LTSTL.str2loc(SnowballerListener.config.getConfig().getString("teamlimearenasides." + key))); - if(Bukkit.getPlayer(pl).getGameMode() == GameMode.CREATIVE) - { - Bukkit.getPlayer(pl).setGameMode(GameMode.SURVIVAL); - } + Bukkit.getPlayer(pl).setGameMode(GameMode.SURVIVAL); } - Utils.checkPlayerStuck(500); + Utils.checkPlayerStuck(300); } i++; } } }
false
true
public static void randomMap() { SnowballerListener.hitcnts.clear(); r.setSeed(System.currentTimeMillis()); int mapnum = r.nextInt(SnowballerListener.config.getConfig().getConfigurationSection("teamcyanarenasides").getKeys(false).size()); int i = 0; for(String key : SnowballerListener.config.getConfig().getConfigurationSection("teamcyanarenasides").getKeys(false)) { if(mapnum == i) { //attempt at the invis tp glitch for(String pl : SnowballerListener.teamcyan) { Bukkit.getPlayer(pl).setRemoveWhenFarAway(false); } for(String pl : SnowballerListener.teamlime) { Bukkit.getPlayer(pl).setRemoveWhenFarAway(false); } for(String pl : SnowballerListener.teamcyan) { Bukkit.getPlayer(pl).getInventory().clear(); SnowballerListener.giveSnowballs(Bukkit.getPlayer(pl)); SnowballerListener.teamcyaninarena.add(pl); Bukkit.getPlayer(pl).teleport(LTSTL.str2loc(SnowballerListener.config.getConfig().getString("teamcyanarenasides." + key))); if(Bukkit.getPlayer(pl).getGameMode() == GameMode.CREATIVE) { Bukkit.getPlayer(pl).setGameMode(GameMode.SURVIVAL); } } for(String pl : SnowballerListener.teamlime) { Bukkit.getPlayer(pl).getInventory().clear(); SnowballerListener.giveSnowballs(Bukkit.getPlayer(pl)); SnowballerListener.teamlimeinarena.add(pl); Bukkit.getPlayer(pl).teleport(LTSTL.str2loc(SnowballerListener.config.getConfig().getString("teamlimearenasides." + key))); if(Bukkit.getPlayer(pl).getGameMode() == GameMode.CREATIVE) { Bukkit.getPlayer(pl).setGameMode(GameMode.SURVIVAL); } } Utils.checkPlayerStuck(500); } i++; } }
public static void randomMap() { SnowballerListener.hitcnts.clear(); r.setSeed(System.currentTimeMillis()); int mapnum = r.nextInt(SnowballerListener.config.getConfig().getConfigurationSection("teamcyanarenasides").getKeys(false).size()); int i = 0; for(String key : SnowballerListener.config.getConfig().getConfigurationSection("teamcyanarenasides").getKeys(false)) { if(mapnum == i) { //attempt at the invis tp glitch for(String pl : SnowballerListener.teamcyan) { Bukkit.getPlayer(pl).setRemoveWhenFarAway(false); } for(String pl : SnowballerListener.teamlime) { Bukkit.getPlayer(pl).setRemoveWhenFarAway(false); } for(String pl : SnowballerListener.teamcyan) { Bukkit.getPlayer(pl).getInventory().clear(); SnowballerListener.giveSnowballs(Bukkit.getPlayer(pl)); SnowballerListener.teamcyaninarena.add(pl); Bukkit.getPlayer(pl).teleport(LTSTL.str2loc(SnowballerListener.config.getConfig().getString("teamcyanarenasides." + key))); Bukkit.getPlayer(pl).setGameMode(GameMode.SURVIVAL); } for(String pl : SnowballerListener.teamlime) { Bukkit.getPlayer(pl).getInventory().clear(); SnowballerListener.giveSnowballs(Bukkit.getPlayer(pl)); SnowballerListener.teamlimeinarena.add(pl); Bukkit.getPlayer(pl).teleport(LTSTL.str2loc(SnowballerListener.config.getConfig().getString("teamlimearenasides." + key))); Bukkit.getPlayer(pl).setGameMode(GameMode.SURVIVAL); } Utils.checkPlayerStuck(300); } i++; } }
diff --git a/GoogleWrapperSample/src/org/osmdroid/google/sample/GoogleWrapperSample.java b/GoogleWrapperSample/src/org/osmdroid/google/sample/GoogleWrapperSample.java index cb27fc2..e93f8f2 100644 --- a/GoogleWrapperSample/src/org/osmdroid/google/sample/GoogleWrapperSample.java +++ b/GoogleWrapperSample/src/org/osmdroid/google/sample/GoogleWrapperSample.java @@ -1,115 +1,115 @@ package org.osmdroid.google.sample; import org.osmdroid.api.IMapView; import org.osmdroid.api.IMyLocationOverlay; import org.osmdroid.util.GeoPoint; import android.view.Menu; import android.view.MenuItem; import com.google.android.maps.MapActivity; public class GoogleWrapperSample extends MapActivity { private static final int GOOGLE_MAP_VIEW_ID = 1; private static final int OSM_MAP_VIEW_ID = 2; private static final int ENABLE_MY_LOCATION_ID = 3; private static final int DISABLE_MY_LOCATION_ID = 4; private MenuItem mGoogleMenuItem; private MenuItem mOsmMenuItem; private MenuItem mEnableMyLocationOverlayMenuItem; private MenuItem mDisableMyLocationOverlayMenuItem; private MapViewSelection mMapViewSelection = MapViewSelection.OSM; private IMapView mMapView; private IMyLocationOverlay mMyLocationOverlay; @Override protected boolean isRouteDisplayed() { return false; } @Override protected void onResume() { super.onResume(); setMapView(); } @Override protected void onPause() { super.onPause(); mMyLocationOverlay.disableMyLocation(); } @Override public boolean onCreateOptionsMenu(final Menu pMenu) { mGoogleMenuItem = pMenu.add(0, GOOGLE_MAP_VIEW_ID, Menu.NONE, R.string.map_view_google); mOsmMenuItem = pMenu.add(0, OSM_MAP_VIEW_ID, Menu.NONE, R.string.map_view_osm); mEnableMyLocationOverlayMenuItem = pMenu.add(0, ENABLE_MY_LOCATION_ID, Menu.NONE, R.string.enable_my_location); mDisableMyLocationOverlayMenuItem = pMenu.add(0, DISABLE_MY_LOCATION_ID, Menu.NONE, R.string.disable_my_location); return true; } @Override public boolean onPrepareOptionsMenu(final Menu pMenu) { mGoogleMenuItem.setVisible(mMapViewSelection == MapViewSelection.OSM); mOsmMenuItem.setVisible(mMapViewSelection == MapViewSelection.Google); mEnableMyLocationOverlayMenuItem.setVisible(!mMyLocationOverlay.isMyLocationEnabled()); mDisableMyLocationOverlayMenuItem.setVisible(mMyLocationOverlay.isMyLocationEnabled()); return super.onPrepareOptionsMenu(pMenu); } @Override public boolean onOptionsItemSelected(final MenuItem pItem) { if (pItem == mGoogleMenuItem) { // switch to google mMapViewSelection = MapViewSelection.Google; setMapView(); return true; } if (pItem == mOsmMenuItem) { // switch to osm mMapViewSelection = MapViewSelection.OSM; setMapView(); return true; } if (pItem == mEnableMyLocationOverlayMenuItem) { mMyLocationOverlay.enableMyLocation(); } if (pItem == mDisableMyLocationOverlayMenuItem) { mMyLocationOverlay.disableMyLocation(); } return false; } private void setMapView() { if (mMapViewSelection == MapViewSelection.OSM) { final org.osmdroid.views.MapView mapView = new org.osmdroid.views.MapView(this, 256); setContentView(mapView); mMapView = mapView; final org.osmdroid.views.overlay.MyLocationOverlay mlo = new org.osmdroid.views.overlay.MyLocationOverlay(this, mapView); mapView.getOverlays().add(mlo); mMyLocationOverlay = mlo; } if (mMapViewSelection == MapViewSelection.Google) { final com.google.android.maps.MapView mapView = new com.google.android.maps.MapView(this, getString(R.string.google_maps_api_key)); setContentView(mapView); - mMapView = new org.osmdroid.google.MapView(mapView); + mMapView = new org.osmdroid.google.wrapper.MapView(mapView); - final org.osmdroid.google.MyLocationOverlay mlo = new org.osmdroid.google.MyLocationOverlay(this, mapView); + final org.osmdroid.google.wrapper.MyLocationOverlay mlo = new org.osmdroid.google.wrapper.MyLocationOverlay(this, mapView); mapView.getOverlays().add(mlo); mMyLocationOverlay = mlo; } mMapView.getController().setZoom(14); mMapView.getController().setCenter(new GeoPoint(52370816, 9735936)); // Hannover mMyLocationOverlay.disableMyLocation(); } private enum MapViewSelection { Google, OSM }; }
false
true
private void setMapView() { if (mMapViewSelection == MapViewSelection.OSM) { final org.osmdroid.views.MapView mapView = new org.osmdroid.views.MapView(this, 256); setContentView(mapView); mMapView = mapView; final org.osmdroid.views.overlay.MyLocationOverlay mlo = new org.osmdroid.views.overlay.MyLocationOverlay(this, mapView); mapView.getOverlays().add(mlo); mMyLocationOverlay = mlo; } if (mMapViewSelection == MapViewSelection.Google) { final com.google.android.maps.MapView mapView = new com.google.android.maps.MapView(this, getString(R.string.google_maps_api_key)); setContentView(mapView); mMapView = new org.osmdroid.google.MapView(mapView); final org.osmdroid.google.MyLocationOverlay mlo = new org.osmdroid.google.MyLocationOverlay(this, mapView); mapView.getOverlays().add(mlo); mMyLocationOverlay = mlo; } mMapView.getController().setZoom(14); mMapView.getController().setCenter(new GeoPoint(52370816, 9735936)); // Hannover mMyLocationOverlay.disableMyLocation(); }
private void setMapView() { if (mMapViewSelection == MapViewSelection.OSM) { final org.osmdroid.views.MapView mapView = new org.osmdroid.views.MapView(this, 256); setContentView(mapView); mMapView = mapView; final org.osmdroid.views.overlay.MyLocationOverlay mlo = new org.osmdroid.views.overlay.MyLocationOverlay(this, mapView); mapView.getOverlays().add(mlo); mMyLocationOverlay = mlo; } if (mMapViewSelection == MapViewSelection.Google) { final com.google.android.maps.MapView mapView = new com.google.android.maps.MapView(this, getString(R.string.google_maps_api_key)); setContentView(mapView); mMapView = new org.osmdroid.google.wrapper.MapView(mapView); final org.osmdroid.google.wrapper.MyLocationOverlay mlo = new org.osmdroid.google.wrapper.MyLocationOverlay(this, mapView); mapView.getOverlays().add(mlo); mMyLocationOverlay = mlo; } mMapView.getController().setZoom(14); mMapView.getController().setCenter(new GeoPoint(52370816, 9735936)); // Hannover mMyLocationOverlay.disableMyLocation(); }
diff --git a/core/src/main/java/org/remus/core/RemusApplet.java b/core/src/main/java/org/remus/core/RemusApplet.java index 8a8a9c8..20a52cb 100644 --- a/core/src/main/java/org/remus/core/RemusApplet.java +++ b/core/src/main/java/org/remus/core/RemusApplet.java @@ -1,519 +1,519 @@ package org.remus.core; 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.Set; import org.apache.thrift.TException; import org.remus.RemusAttach; import org.remus.RemusDB; import org.remus.RemusDatabaseException; import org.remus.thrift.AppletRef; import org.remus.thrift.NotImplemented; import org.remus.work.AgentGenerator; import org.remus.work.MapGenerator; import org.remus.work.MatchGenerator; import org.remus.work.MergeGenerator; import org.remus.work.PipeGenerator; import org.remus.work.ReduceGenerator; import org.remus.work.SplitGenerator; import org.remus.work.WorkGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RemusApplet { public static final int MAPPER = 1; public static final int MERGER = 2; public static final int MATCHER = 3; public static final int SPLITTER = 4; public static final int REDUCER = 5; public static final int PIPE = 6; public static final int STORE = 7; public static final int OUTPUT = 8; public static final int AGENT = 9; public static final String CODE_FIELD = "_code"; public static final String MODE_FIELD = "_mode"; public static final String TYPE_FIELD = "_type"; public static final String LEFT_SRC = "_srcLeft"; public static final String RIGHT_SRC = "_srcRight"; public static final String SRC = "_src"; public static final String OUTPUT_FIELD = "_output"; Logger logger; @SuppressWarnings("unchecked") Class workGenerator = null; private String id; List<String> inputs = null, lInputs = null, rInputs = null; int mode; private String type; LinkedList<RemusInstance> activeInstances; private RemusPipeline pipeline; private RemusDB datastore; private RemusAttach attachstore; private ArrayList<String> outputs; public RemusApplet(RemusPipeline pipeline, String name, RemusDB datastore, RemusAttach attachstore) throws TException, NotImplemented, RemusDatabaseException { logger = LoggerFactory.getLogger(RemusApplet.class); id = name; this.pipeline = pipeline; this.datastore = datastore; this.attachstore = attachstore; AppletRef arApplet = new AppletRef(pipeline.getID(), RemusInstance.STATIC_INSTANCE_STR, "/@pipeline"); Object appletDesc = null; for (Object obj : datastore.get(arApplet, name)) { appletDesc = obj; } if (appletDesc == null) { throw new RemusDatabaseException("Applet Description not found"); } load((Map) appletDesc); /* if ( out != null ) { out.id = id; out.mode = mode; out.type = type; out.inputs = null; out.activeInstances = new LinkedList<RemusInstance>(); } */ } void setMode(int mode) { switch (mode) { case MAPPER: { workGenerator = MapGenerator.class; break; } case REDUCER: { workGenerator = ReduceGenerator.class; break; } case SPLITTER: { workGenerator = SplitGenerator.class; break; } case MERGER: { workGenerator = MergeGenerator.class; break; } case MATCHER: { workGenerator = MatchGenerator.class; break; } case PIPE: { workGenerator = PipeGenerator.class; break; } case AGENT: { workGenerator = AgentGenerator.class; break; } default: { workGenerator = null; break; } } this.mode = mode; } public void load(Map appletObj) throws RemusDatabaseException { String modeStr = (String) appletObj.get(MODE_FIELD); type = (String) appletObj.get(TYPE_FIELD); Integer appletType = null; if (modeStr.compareTo("map") == 0) { appletType = MAPPER; } if (modeStr.compareTo("reduce") == 0) { appletType = REDUCER; } if (modeStr.compareTo("pipe") == 0) { appletType = PIPE; } if (modeStr.compareTo("merge") == 0) { appletType = MERGER; } if (modeStr.compareTo("match") == 0) { appletType = MATCHER; } if (modeStr.compareTo("split") == 0) { appletType = SPLITTER; } if (modeStr.compareTo("store") == 0) { appletType = STORE; } if (modeStr.compareTo("agent") == 0) { appletType = AGENT; } if (modeStr.compareTo("output") == 0) { appletType = OUTPUT; } if (appletType == null) { throw new RemusDatabaseException("Invalid Applet Type"); } setMode(appletType); if (appletType == MATCHER || appletType == MERGER) { //try { String lInput = (String) appletObj.get(LEFT_SRC); //RemusPath path = new RemusPath( this, (String)input, pipelineName, name ); addLeftInput(lInput); //} catch (FileNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); //} //try { String rInput = (String) appletObj.get(RIGHT_SRC); //RemusPath path = new RemusPath( this, (String)input, pipelineName, name ); addRightInput(rInput); //} catch (FileNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); //} } else { //try { Object src = appletObj.get(SRC); if (src instanceof String) { String input = (String) src; //RemusPath path = new RemusPath( this, (String)input, pipelineName, name ); addInput(input); } if (src instanceof List) { for (Object obj : (List) src) { //RemusPath path = new RemusPath( this, (String)obj, pipelineName, name ); addInput((String) obj); } } //} catch (FileNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); //} } if (appletObj.containsKey(OUTPUT_FIELD)) { List outs = (List) appletObj.get(OUTPUT_FIELD); for (Object outName : outs) { addOutput((String) outName); } } } private void addOutput(String outName) { if (outputs == null) { outputs = new ArrayList<String>(); } outputs.add(outName); } private void addInput(String in) { if (inputs == null) { inputs = new ArrayList<String>(); } inputs.add(in); } private void addLeftInput(String in) { if (lInputs == null) { lInputs = new LinkedList<String>(); } lInputs.add(in); addInput(in); } private void addRightInput(String in) { if (rInputs == null) { rInputs = new LinkedList<String>(); } rInputs.add(in); addInput(in); } public String getInput() { return inputs.get(0); } public String getLeftInput() { return lInputs.get(0); } public String getRightInput() { return rInputs.get(0); } public String getType() { return type; } public List<String> getInputs() { if ( inputs != null ) return inputs; return new ArrayList<String>(); } public int getMode() { return mode; } public boolean hasInputs() { if (inputs == null) { return false; } return true; } public Set<AppletInstance> getActiveApplets() { HashSet<AppletInstance> out = new HashSet<AppletInstance>(); for (RemusInstance inst : getInstanceList()) { AppletInstance ai = new AppletInstance(pipeline, inst, this, datastore); if (!ai.isComplete()) { if (ai.isReady()) { if (workGenerator != null) { try { long infoTime = ai.getStatusTimeStamp(); long dataTime = ai.inputTimeStamp(); if (infoTime < dataTime || !WorkStatus.hasStatus(pipeline, this, inst)) { try { logger.info("GENERATE WORK: " + pipeline.getID() + "/" + getID() + " " + inst.toString()); WorkGenerator gen = (WorkGenerator) workGenerator.newInstance(); gen.writeWorkTable(pipeline, this, inst, datastore); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { //logger.info("Active Work Stack: " + inst.toString() + ":" + this.getID()); } out.add(ai); } catch (TException e) { e.printStackTrace(); } catch (NotImplemented e) { e.printStackTrace(); } } } } else { /* if (hasInputs()) { try { long thisTime = ai.getStatusTimeStamp(); long inTime = ai.inputTimeStamp(); //System.err.println( this.getPath() + ":" + thisTime + " " + "IN:" + inTime ); if (inTime > thisTime) { logger.info("YOUNG INPUT (applet reset):" + getID()); WorkStatus.unsetComplete(pipeline, this, inst); } } catch (TException e){ e.printStackTrace(); } catch (NotImplemented e) { // TODO Auto-generated catch block e.printStackTrace(); } } */ } } return out; } public Collection<RemusInstance> getInstanceList() { Collection<RemusInstance> out = new HashSet<RemusInstance>(); AppletRef applet = new AppletRef(pipeline.getID(), RemusInstance.STATIC_INSTANCE_STR, getID() + "/@instance"); for (String key : datastore.listKeys(applet)) { out.add(new RemusInstance(key)); } return out; } public void deleteInstance(RemusInstance instance) throws TException, NotImplemented { AppletRef applet = new AppletRef(pipeline.getID(), instance.toString(), getID()); datastore.deleteStack(applet); applet.applet = getID() + "/@done"; datastore.deleteStack(applet); applet.applet = getID() + "/@work"; datastore.deleteStack(applet); applet.applet = getID() + "/@error"; datastore.deleteStack(applet); applet.instance = RemusInstance.STATIC_INSTANCE_STR; applet.applet = getID() + "/@instance"; datastore.deleteStack(applet); applet.applet = getID() + "/@work"; datastore.deleteStack(applet); applet.applet = getID() + WorkStatus.WorkStatusName; datastore.deleteStack(applet); if (attachstore != null) { attachstore.deleteStack(applet); } } @SuppressWarnings("unchecked") public boolean createInstance(String submitKey, Map params, RemusInstance inst) throws TException, NotImplemented { logger.info("Creating instance of " + getID() + " for " + inst.toString()); AppletRef instApplet = new AppletRef(pipeline.getID(), RemusInstance.STATIC_INSTANCE_STR, getID() + "/@instance"); if (datastore.containsKey(instApplet, inst.toString())) { return false; } Map baseMap = new HashMap(); if (params != null) { for (Object key : params.keySet()) { baseMap.put(key, params.get(key)); } } AppletRef pipelineApplet = new AppletRef(pipeline.getID(), RemusInstance.STATIC_INSTANCE_STR, "/@pipeline"); for (Object i : datastore.get(pipelineApplet, getID())) { for (Object key : ((Map) i).keySet()) { baseMap.put(key, ((Map) i).get(key)); } } if (baseMap == null) { baseMap = new HashMap(); } baseMap.put("_instance", inst.toString()); baseMap.put("_submitKey", submitKey); if (getMode() == MERGER || getMode() == MATCHER) { Map inMap = new HashMap(); Map lMap = new HashMap(); Map rMap = new HashMap(); lMap.put("_instance", inst.toString()); lMap.put("_applet", getLeftInput()); rMap.put("_instance", inst.toString()); rMap.put("_applet", getRightInput()); inMap.put("_left", lMap); inMap.put("_right", rMap); inMap.put("_axis", "_left"); baseMap.put("_input", inMap); } else if (getMode() == AGENT) { Map inMap = new HashMap(); inMap.put("_instance", RemusInstance.STATIC_INSTANCE_STR); - inMap.put("_applet", "/@agent"); + inMap.put("_applet", "/@agent?" + pipeline.getID()); baseMap.put("_input", inMap); } else if (getMode() == PIPE) { if (getInput().compareTo("?") != 0) { List outList = new ArrayList(); for (String input : getInputs()) { Map inMap = new HashMap(); inMap.put("_instance", inst.toString()); inMap.put("_applet", input); outList.add(inMap); } baseMap.put("_input", outList); } } else if (hasInputs() && getInput().compareTo("?") != 0) { Map inMap = new HashMap(); inMap.put("_instance", inst.toString()); inMap.put("_applet", getInput()); baseMap.put("_input", inMap); } if (getMode() == STORE || getMode() == AGENT) { // baseMap.put(WORKDONE_OP, true); } PipelineSubmission instInfo = new PipelineSubmission(baseMap); if (outputs != null) { for (String output : outputs) { try { PipelineSubmission outputInfo = new PipelineSubmission(new HashMap(baseMap)); outputInfo.setInstance(inst); outputInfo.setMode("output"); RemusApplet outApplet = new RemusApplet(pipeline, getID() + ":" + output, datastore, attachstore); AppletInstance ai = new AppletInstance(pipeline, inst, outApplet, datastore); ai.updateInstanceInfo(outputInfo); } catch (RemusDatabaseException e) { } } } AppletInstance ai = new AppletInstance(pipeline, inst, this, datastore); ai.updateInstanceInfo(instInfo); return true; }; public void errorWork(RemusInstance inst, long jobID, String workerID, String error) throws TException, NotImplemented { AppletRef applet = new AppletRef(pipeline.getID(), inst.toString(), getID() + "/@error"); datastore.add(applet, 0L, 0L, Long.toString(jobID), error); } public void deleteErrors(RemusInstance inst) throws TException, NotImplemented { AppletRef applet = new AppletRef(pipeline.getID(), inst.toString(), getID() + "/@error"); datastore.deleteStack(applet); }; @Override public int hashCode() { return getID().hashCode(); }; @Override public boolean equals(Object obj) { RemusApplet a = (RemusApplet) obj; return a.getID().equals(getID()); } public RemusDB getDataStore() { return datastore; } public String getID() { return id; } public RemusAttach getAttachStore() { return attachstore; } public AppletInstance getAppletInstance(String inst) throws TException, NotImplemented { AppletInstance ai = new AppletInstance(pipeline, RemusInstance.getInstance(datastore, pipeline.getID(), inst), this, datastore); return ai; } }
true
true
public boolean createInstance(String submitKey, Map params, RemusInstance inst) throws TException, NotImplemented { logger.info("Creating instance of " + getID() + " for " + inst.toString()); AppletRef instApplet = new AppletRef(pipeline.getID(), RemusInstance.STATIC_INSTANCE_STR, getID() + "/@instance"); if (datastore.containsKey(instApplet, inst.toString())) { return false; } Map baseMap = new HashMap(); if (params != null) { for (Object key : params.keySet()) { baseMap.put(key, params.get(key)); } } AppletRef pipelineApplet = new AppletRef(pipeline.getID(), RemusInstance.STATIC_INSTANCE_STR, "/@pipeline"); for (Object i : datastore.get(pipelineApplet, getID())) { for (Object key : ((Map) i).keySet()) { baseMap.put(key, ((Map) i).get(key)); } } if (baseMap == null) { baseMap = new HashMap(); } baseMap.put("_instance", inst.toString()); baseMap.put("_submitKey", submitKey); if (getMode() == MERGER || getMode() == MATCHER) { Map inMap = new HashMap(); Map lMap = new HashMap(); Map rMap = new HashMap(); lMap.put("_instance", inst.toString()); lMap.put("_applet", getLeftInput()); rMap.put("_instance", inst.toString()); rMap.put("_applet", getRightInput()); inMap.put("_left", lMap); inMap.put("_right", rMap); inMap.put("_axis", "_left"); baseMap.put("_input", inMap); } else if (getMode() == AGENT) { Map inMap = new HashMap(); inMap.put("_instance", RemusInstance.STATIC_INSTANCE_STR); inMap.put("_applet", "/@agent"); baseMap.put("_input", inMap); } else if (getMode() == PIPE) { if (getInput().compareTo("?") != 0) { List outList = new ArrayList(); for (String input : getInputs()) { Map inMap = new HashMap(); inMap.put("_instance", inst.toString()); inMap.put("_applet", input); outList.add(inMap); } baseMap.put("_input", outList); } } else if (hasInputs() && getInput().compareTo("?") != 0) { Map inMap = new HashMap(); inMap.put("_instance", inst.toString()); inMap.put("_applet", getInput()); baseMap.put("_input", inMap); } if (getMode() == STORE || getMode() == AGENT) { // baseMap.put(WORKDONE_OP, true); } PipelineSubmission instInfo = new PipelineSubmission(baseMap); if (outputs != null) { for (String output : outputs) { try { PipelineSubmission outputInfo = new PipelineSubmission(new HashMap(baseMap)); outputInfo.setInstance(inst); outputInfo.setMode("output"); RemusApplet outApplet = new RemusApplet(pipeline, getID() + ":" + output, datastore, attachstore); AppletInstance ai = new AppletInstance(pipeline, inst, outApplet, datastore); ai.updateInstanceInfo(outputInfo); } catch (RemusDatabaseException e) { } } } AppletInstance ai = new AppletInstance(pipeline, inst, this, datastore); ai.updateInstanceInfo(instInfo); return true; };
public boolean createInstance(String submitKey, Map params, RemusInstance inst) throws TException, NotImplemented { logger.info("Creating instance of " + getID() + " for " + inst.toString()); AppletRef instApplet = new AppletRef(pipeline.getID(), RemusInstance.STATIC_INSTANCE_STR, getID() + "/@instance"); if (datastore.containsKey(instApplet, inst.toString())) { return false; } Map baseMap = new HashMap(); if (params != null) { for (Object key : params.keySet()) { baseMap.put(key, params.get(key)); } } AppletRef pipelineApplet = new AppletRef(pipeline.getID(), RemusInstance.STATIC_INSTANCE_STR, "/@pipeline"); for (Object i : datastore.get(pipelineApplet, getID())) { for (Object key : ((Map) i).keySet()) { baseMap.put(key, ((Map) i).get(key)); } } if (baseMap == null) { baseMap = new HashMap(); } baseMap.put("_instance", inst.toString()); baseMap.put("_submitKey", submitKey); if (getMode() == MERGER || getMode() == MATCHER) { Map inMap = new HashMap(); Map lMap = new HashMap(); Map rMap = new HashMap(); lMap.put("_instance", inst.toString()); lMap.put("_applet", getLeftInput()); rMap.put("_instance", inst.toString()); rMap.put("_applet", getRightInput()); inMap.put("_left", lMap); inMap.put("_right", rMap); inMap.put("_axis", "_left"); baseMap.put("_input", inMap); } else if (getMode() == AGENT) { Map inMap = new HashMap(); inMap.put("_instance", RemusInstance.STATIC_INSTANCE_STR); inMap.put("_applet", "/@agent?" + pipeline.getID()); baseMap.put("_input", inMap); } else if (getMode() == PIPE) { if (getInput().compareTo("?") != 0) { List outList = new ArrayList(); for (String input : getInputs()) { Map inMap = new HashMap(); inMap.put("_instance", inst.toString()); inMap.put("_applet", input); outList.add(inMap); } baseMap.put("_input", outList); } } else if (hasInputs() && getInput().compareTo("?") != 0) { Map inMap = new HashMap(); inMap.put("_instance", inst.toString()); inMap.put("_applet", getInput()); baseMap.put("_input", inMap); } if (getMode() == STORE || getMode() == AGENT) { // baseMap.put(WORKDONE_OP, true); } PipelineSubmission instInfo = new PipelineSubmission(baseMap); if (outputs != null) { for (String output : outputs) { try { PipelineSubmission outputInfo = new PipelineSubmission(new HashMap(baseMap)); outputInfo.setInstance(inst); outputInfo.setMode("output"); RemusApplet outApplet = new RemusApplet(pipeline, getID() + ":" + output, datastore, attachstore); AppletInstance ai = new AppletInstance(pipeline, inst, outApplet, datastore); ai.updateInstanceInfo(outputInfo); } catch (RemusDatabaseException e) { } } } AppletInstance ai = new AppletInstance(pipeline, inst, this, datastore); ai.updateInstanceInfo(instInfo); return true; };
diff --git a/src/jvm/final_project/control/SMSReceiver.java b/src/jvm/final_project/control/SMSReceiver.java index 87e3e99..9fb12d8 100644 --- a/src/jvm/final_project/control/SMSReceiver.java +++ b/src/jvm/final_project/control/SMSReceiver.java @@ -1,235 +1,234 @@ package final_project.control; import java.io.*; import java.net.*; import java.util.Scanner; import java.util.TimerTask; /** * The SMSReceiver task extends the * @author Miranda * */ public class SMSReceiver extends TimerTask implements Constants{ private SMSController _control; private String _username, _password; //Not the most secure but who cares. private int _lastRetrievedID; private boolean _flushed; public SMSReceiver(SMSController ctrl, String username, String password) { _control = ctrl; _username = username; _password = password; _lastRetrievedID = 0; _flushed = false; } public void run() { this.getInbox(); } /** * GET INBOX METHOD * Calls on the API to get all of the messages not previously */ public boolean getInbox() { - System.out.println("GET INBOX CALLED: " + _flushed); if(!_flushed) { this.flushInbox(); return false; } OutputStreamWriter wr = null; BufferedReader rd = null; boolean toReturn = false; try { //Constructing data String data = ""; data += "username=" + URLEncoder.encode(_username, "ISO-8859-1"); data += "&password=" + URLEncoder.encode(_password, "ISO-8859-1"); data += "&last_retrieved_id=" + _lastRetrievedID; URL url = new URL(API_RECEIVE_URL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; boolean firstLine = true; while ((line = rd.readLine()) != null) { //Parsing the very first line if(firstLine) { //First line from API looks something like: //0|records to follow|3 --> only care about status code (the zero) Scanner s = new Scanner(line); s.useDelimiter("\\|"); if(!s.hasNextInt()) { toReturn = false; break; } int status_code = s.nextInt(); if(status_code == 0) { toReturn = true; //SMS in progress } else if(status_code == 23) { //Authentication failure _control.alertGUI("Authentication failure: SMS send could not go through", _control.getTime()); toReturn = false; break; } else if(status_code == 25) { _control.alertGUI("SMS API needs more credits! Send failure!", _control.getTime()); toReturn = false; break; } else { _control.alertGUI("Send SMS Failure", _control.getTime()); toReturn = false; break; } //Eating the second (empty) line line = rd.readLine(); firstLine = false; } else { //Example input: //19|4412312345|Hi there|2004-01-20 16:06:40|44771234567|0 Scanner s = new Scanner(line); s.useDelimiter("\\|"); //Must escape bar to satisfy regex //First, getting out the message id & storing it if(!s.hasNextInt()) { toReturn = false; break; } _lastRetrievedID = s.nextInt(); //Next, getting the phone number the text was sent from if(!s.hasNext()) { toReturn = false; break; } String number = s.next().substring(1); //Eating the first one //Lastly, getting the message receieved. Don't care about the rest. if(!s.hasNext()) { toReturn = false; break; } String message = s.next(); System.out.println("Received message!!! " + number + " " + message); //Calling control's parse output method _control.parseOutput(message, number); } } toReturn = true; //Input successfully processed } catch (UnknownHostException e) { //Letting the GUI know it ain't got no internet _control.alertGUI("You are not currently connected to the internet. SMS notification system disabled", _control.getTime()); } catch (Exception e) { e.printStackTrace(); //What to do with these?? } finally { try { if(wr!=null) wr.close(); if(wr!=null) rd.close(); } catch (IOException e) { e.printStackTrace(); } } return toReturn; } /** * Gets inbox without parsing messages */ public void flushInbox() { OutputStreamWriter wr = null; BufferedReader rd = null; try { //Constructing data String data = ""; data += "username=" + URLEncoder.encode(_username, "ISO-8859-1"); data += "&password=" + URLEncoder.encode(_password, "ISO-8859-1"); data += "&last_retrieved_id=" + _lastRetrievedID; URL url = new URL(API_RECEIVE_URL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; boolean firstLine = true; while ((line = rd.readLine()) != null) { //Parsing the very first line if(firstLine) { //First line from API looks something like: //0|records to follow|3 --> only care about status code (the zero) Scanner s = new Scanner(line); s.useDelimiter("\\|"); if(!s.hasNextInt()) { break; } int status_code = s.nextInt(); if(status_code == 0) { //Do nothing --> no error } else if(status_code == 23) { //Authentication failure _control.alertGUI("Authentication failure: SMS send could not go through", _control.getTime()); break; } else if(status_code == 25) { _control.alertGUI("SMS API needs more credits! Send failure!", _control.getTime()); break; } else { _control.alertGUI("Send SMS Failure", _control.getTime()); break; } //Eating the second (empty) line line = rd.readLine(); firstLine = false; } else { //Example input: //19|4412312345|Hi there|2004-01-20 16:06:40|44771234567|0 Scanner s = new Scanner(line); s.useDelimiter("\\|"); //Must escape bar to satisfy regex //First, getting out the message id & storing it if(!s.hasNextInt()) { break; } _lastRetrievedID = s.nextInt(); } } } catch (UnknownHostException e) { //Letting the GUI know it ain't got no internet _control.alertGUI("You are not currently connected to the internet. SMS notification system disabled", _control.getTime()); } catch (Exception e) { e.printStackTrace(); //What to do with these?? } finally { try { if(wr!=null) wr.close(); if(wr!=null) rd.close(); } catch (IOException e) { e.printStackTrace(); } } _flushed = true; } }
true
true
public boolean getInbox() { System.out.println("GET INBOX CALLED: " + _flushed); if(!_flushed) { this.flushInbox(); return false; } OutputStreamWriter wr = null; BufferedReader rd = null; boolean toReturn = false; try { //Constructing data String data = ""; data += "username=" + URLEncoder.encode(_username, "ISO-8859-1"); data += "&password=" + URLEncoder.encode(_password, "ISO-8859-1"); data += "&last_retrieved_id=" + _lastRetrievedID; URL url = new URL(API_RECEIVE_URL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; boolean firstLine = true; while ((line = rd.readLine()) != null) { //Parsing the very first line if(firstLine) { //First line from API looks something like: //0|records to follow|3 --> only care about status code (the zero) Scanner s = new Scanner(line); s.useDelimiter("\\|"); if(!s.hasNextInt()) { toReturn = false; break; } int status_code = s.nextInt(); if(status_code == 0) { toReturn = true; //SMS in progress } else if(status_code == 23) { //Authentication failure _control.alertGUI("Authentication failure: SMS send could not go through", _control.getTime()); toReturn = false; break; } else if(status_code == 25) { _control.alertGUI("SMS API needs more credits! Send failure!", _control.getTime()); toReturn = false; break; } else { _control.alertGUI("Send SMS Failure", _control.getTime()); toReturn = false; break; } //Eating the second (empty) line line = rd.readLine(); firstLine = false; } else { //Example input: //19|4412312345|Hi there|2004-01-20 16:06:40|44771234567|0 Scanner s = new Scanner(line); s.useDelimiter("\\|"); //Must escape bar to satisfy regex //First, getting out the message id & storing it if(!s.hasNextInt()) { toReturn = false; break; } _lastRetrievedID = s.nextInt(); //Next, getting the phone number the text was sent from if(!s.hasNext()) { toReturn = false; break; } String number = s.next().substring(1); //Eating the first one //Lastly, getting the message receieved. Don't care about the rest. if(!s.hasNext()) { toReturn = false; break; } String message = s.next(); System.out.println("Received message!!! " + number + " " + message); //Calling control's parse output method _control.parseOutput(message, number); } } toReturn = true; //Input successfully processed } catch (UnknownHostException e) { //Letting the GUI know it ain't got no internet _control.alertGUI("You are not currently connected to the internet. SMS notification system disabled", _control.getTime()); } catch (Exception e) { e.printStackTrace(); //What to do with these?? } finally { try { if(wr!=null) wr.close(); if(wr!=null) rd.close(); } catch (IOException e) { e.printStackTrace(); } } return toReturn; }
public boolean getInbox() { if(!_flushed) { this.flushInbox(); return false; } OutputStreamWriter wr = null; BufferedReader rd = null; boolean toReturn = false; try { //Constructing data String data = ""; data += "username=" + URLEncoder.encode(_username, "ISO-8859-1"); data += "&password=" + URLEncoder.encode(_password, "ISO-8859-1"); data += "&last_retrieved_id=" + _lastRetrievedID; URL url = new URL(API_RECEIVE_URL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; boolean firstLine = true; while ((line = rd.readLine()) != null) { //Parsing the very first line if(firstLine) { //First line from API looks something like: //0|records to follow|3 --> only care about status code (the zero) Scanner s = new Scanner(line); s.useDelimiter("\\|"); if(!s.hasNextInt()) { toReturn = false; break; } int status_code = s.nextInt(); if(status_code == 0) { toReturn = true; //SMS in progress } else if(status_code == 23) { //Authentication failure _control.alertGUI("Authentication failure: SMS send could not go through", _control.getTime()); toReturn = false; break; } else if(status_code == 25) { _control.alertGUI("SMS API needs more credits! Send failure!", _control.getTime()); toReturn = false; break; } else { _control.alertGUI("Send SMS Failure", _control.getTime()); toReturn = false; break; } //Eating the second (empty) line line = rd.readLine(); firstLine = false; } else { //Example input: //19|4412312345|Hi there|2004-01-20 16:06:40|44771234567|0 Scanner s = new Scanner(line); s.useDelimiter("\\|"); //Must escape bar to satisfy regex //First, getting out the message id & storing it if(!s.hasNextInt()) { toReturn = false; break; } _lastRetrievedID = s.nextInt(); //Next, getting the phone number the text was sent from if(!s.hasNext()) { toReturn = false; break; } String number = s.next().substring(1); //Eating the first one //Lastly, getting the message receieved. Don't care about the rest. if(!s.hasNext()) { toReturn = false; break; } String message = s.next(); System.out.println("Received message!!! " + number + " " + message); //Calling control's parse output method _control.parseOutput(message, number); } } toReturn = true; //Input successfully processed } catch (UnknownHostException e) { //Letting the GUI know it ain't got no internet _control.alertGUI("You are not currently connected to the internet. SMS notification system disabled", _control.getTime()); } catch (Exception e) { e.printStackTrace(); //What to do with these?? } finally { try { if(wr!=null) wr.close(); if(wr!=null) rd.close(); } catch (IOException e) { e.printStackTrace(); } } return toReturn; }
diff --git a/OpenGov/src/main/java/za/org/opengov/ussd/service/stockout/cm/CMUssdStockoutServiceImpl.java b/OpenGov/src/main/java/za/org/opengov/ussd/service/stockout/cm/CMUssdStockoutServiceImpl.java index 6bbcfbb..0f8b9f1 100644 --- a/OpenGov/src/main/java/za/org/opengov/ussd/service/stockout/cm/CMUssdStockoutServiceImpl.java +++ b/OpenGov/src/main/java/za/org/opengov/ussd/service/stockout/cm/CMUssdStockoutServiceImpl.java @@ -1,379 +1,379 @@ package za.org.opengov.ussd.service.stockout.cm; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import za.org.opengov.stockout.entity.Facility; import za.org.opengov.stockout.entity.Stockout; import za.org.opengov.stockout.entity.StockoutReport; import za.org.opengov.stockout.entity.medical.Product; import za.org.opengov.stockout.service.FacilityService; import za.org.opengov.stockout.service.StockoutReportService; import za.org.opengov.stockout.service.StockoutService; import za.org.opengov.stockout.service.medical.ProductService; import za.org.opengov.ussd.controller.cm.CMUssdRequest; import za.org.opengov.ussd.controller.cm.CMUssdResponse; import za.org.opengov.ussd.service.stockout.UssdStockoutDao; import za.org.opengov.ussd.util.KeyValueStore; /** * Take note: When a REST call is made, the request will be delegated to the * service which matches the name as specified below. */ @Service("cm.stockout") public class CMUssdStockoutServiceImpl implements CMUssdStockoutService { @Autowired private KeyValueStore keyValueStore; @Autowired private UssdStockoutDao stockoutDao; @Autowired private StockoutReportService stockoutReportService; @Autowired private FacilityService facilityService; @Autowired private ProductService productService; @Autowired private StockoutService stockoutService; @Override public CMUssdResponse createUssdResponse(CMUssdRequest request) { CMUssdResponse response = new CMUssdResponse(); String displayText = ""; String sessionId = ""; int menuRequest = 0; try { // get the stage at which the user is in,in the ussd session menuRequest = Integer.parseInt(request.getRequestid()); // session id identifies session specific data stored in the key // value store sessionId = request.getUssdSessionId(); switch (menuRequest) { case 0: // welcome message..clinic code prompt displayText = stockoutDao.getMenu(0); ++menuRequest; break; case 1: // validate clinic and display ussd stock out services displayText = request.getRequest(); // stockoutDao.checkClinic(request.getRequest());****database // call //----------------------------------------------------------------------------- //String clinicName = displayText; //matches the best matching facility Facility facility = facilityService.getClosestMatch(displayText); //----------------------------------------------------------------------------- - if (!facility.equals(null)) { + if (facility != null) { // Need to set clinic name so that it can be re-used later keyValueStore.put( "facilityName." + request.getUssdSessionId(), facility); displayText = facility.getLocalName() + " " + stockoutDao.getMenu(1); ++menuRequest; } else { // displayed failed message and redisplay same menu displayText += " " + stockoutDao.getMenu(92); throw new NumberFormatException(); } break; case 2: // process service request,get list of recent medicines displayText = stockoutDao.getMenu(91); // set error message for // incorrect string // input and invalid // integer selection int requestSelection = Integer.parseInt(request.getRequest()); if (requestSelection >= 1 && requestSelection <= 3) { displayText = stockoutDao.getMenu(21); //displayText += "1.Medicine1 \n2.Medicine2 \n3.Medicine3 \n4.Medicine4"; //String[] recentStockouts = { "Medicine1", "Medicine2", // "Medicine3", "Medicine4" }; //keyValueStore.put("recentStockouts." + sessionId, //recentStockouts); // method that retrieves commonly reported stock out, from a // clinic // *****Need clinic name entered earlier // StockoutDao.retrieveCommonStockouts(keyValueStore.get("facilityName."+request.getUssdSessionId())); // ************************************************************** //----------------------------------------------------------------------------- int limit = 5; //must be facility code, not facility name String facilityCode = ((Facility) (keyValueStore.get("facilityName." + sessionId))).getUid(); //facilityCode. List<Stockout> stockouts = stockoutService.getMostCommonlyReportedStockoutsForFacility(facilityCode, limit); keyValueStore.put("commonStockouts." + sessionId,stockouts); for(int index=0;index<stockouts.size();index++){ displayText += (index+1) + "." + stockouts.get(index).getProduct().getName() + "\n"; } //or //this returns most recent reports, though I could also just return most recent actual stockouts //since multiple recent reports could be for same stockouts //List<StockoutReport> recentReports = stockoutReportService.getRecentlyReportedStockouts(limit); //----------------------------------------------------------------------------- displayText += stockoutDao.getMenu(22); keyValueStore.put("service." + sessionId, Integer.toString(requestSelection)); ++menuRequest; } else { // number greater 3 or less than 1 was chosen throw new NumberFormatException(); } break; case 3: // process user selection of recent reports or manual // medicine name entry displayText = stockoutDao.getMenu(91); int requestMedicine = Integer.parseInt(request.getRequest()); if (requestMedicine >= 1 && requestMedicine <= 7) { // process // medicine // selection // 1-8 List<Stockout> stockouts = (List<Stockout>) keyValueStore.get("commonStockouts." + sessionId); Product selectedProduct = stockouts.get(requestMedicine - 1).getProduct(); displayText = selectedProduct.getName(); keyValueStore.put("productName." + sessionId,selectedProduct); displayText += " " + stockoutDao.getMenu(4); menuRequest += 2; } else if (requestMedicine == 8) { // display enter medicine // name prompt displayText = stockoutDao.getMenu(3); ++menuRequest; } else {// user enters a number less than 1 or greater than 8 throw new NumberFormatException(); } break; case 4: // validate/find nearest match to medicine name+display // appropriate menu as above // displayText = // stockoutDao.CheckAndFindNearestMatch(request.getRequest()); //----------------------------------------------------------------------------- displayText = request.getRequest(); //String productName = "foobar"; Product searchProduct = productService.getClosestMatch(displayText); //----------------------------------------------------------------------------- if ((searchProduct != null)) { // medicine name found, go // to next menu keyValueStore.put("productName." + sessionId,searchProduct); displayText = searchProduct.getName() + " " + stockoutDao.getMenu(4); ++menuRequest; } else { // medicine name not found displayText += " " + stockoutDao.getMenu(92); throw new NumberFormatException(); } break; case 5: // run methods for each of the different services+display // result. String serviceRequest = (String) keyValueStore.get("service." + sessionId); Product selectedProduct = (Product) keyValueStore .get("productName." + sessionId); Facility selectedFacility = (Facility) keyValueStore .get("facilityName." + sessionId); int service = Integer.parseInt(serviceRequest); int requestOption = Integer.parseInt(request.getRequest()); if (requestOption == 1) { switch (service) { case 1: // StockoutDao.reportStockout(medicineName,facilityName); //----------------------------------------------------------------------------- //must be the correct facility and product code String productCode = selectedProduct.getUid(); String facilityCode = selectedFacility.getUid(); stockoutReportService.submitStockoutReport(productCode, facilityCode, null, null, null, false, false); //----------------------------------------------------------------------------- displayText = selectedProduct.getName() + " in " + selectedFacility.getLocalName() + " " + stockoutDao.getMenu(5); break; case 2: // displayText = // StockoutDao.getStatus(MedicineName,facilityName); //----------------------------------------------------------------------------- //against must be proper facility code and product code (no matching is done) String selectedFacilityCode = selectedFacility.getUid(); String selectedProductCode = selectedProduct.getUid(); Stockout stockout = stockoutService.getStockout(selectedFacilityCode, selectedProductCode); //----------------------------------------------------------------------------- displayText = stockoutDao.getMenu(6) + " " + stockout.getIssue().getState().toString(); break; case 3: // displayText = // stockoutDao.findNearestNeighbourWithStock(medicineName,facilityName); //----------------------------------------------------------------------------- Facility closestFacility = facilityService.getNearestFacilityWithStock(selectedProduct, selectedFacility); //----------------------------------------------------------------------------- displayText = stockoutDao.getMenu(7) + " " + closestFacility.getLocalName(); break; } menuRequest = 99; } else if (requestOption == 2) { displayText = stockoutDao.getMenu(21); //displayText += "1.Medicine1 \n2.Medicine2 \n3.Medicine3 \n4.Medicine4"; //String[] recentStockouts = { "Medicine1", "Medicine2", // "Medicine3", "Medicine4" }; //keyValueStore.put("recentStockouts." + sessionId, // recentStockouts); // method that retrieves commonly reported stock out, from a // clinic // *****Need clinic name entered earlier // StockoutDao.retrieveCommonStockouts(keyValueStore.get("facilityName."+request.getUssdSessionId())); // ************************************************************** //----------------------------------------------------------------------------- int limit = 5; //must be facility code, not facility name String facilityCode = ((Facility) (keyValueStore.get("facilityName." + sessionId))).getUid(); //facilityCode. List<Stockout> stockouts = stockoutService.getMostCommonlyReportedStockoutsForFacility(facilityCode, limit); keyValueStore.put("commonStockouts." + sessionId,stockouts); for(int index=0;index<stockouts.size();index++){ displayText += (index+1) + "." + stockouts.get(index).getProduct().getName() + "\n"; } //----------------------------------------------------------------------------- displayText += stockoutDao.getMenu(22); menuRequest = 3; } else if (requestOption == 3) { displayText = ((Facility)keyValueStore .get("facilityName." + sessionId)).getLocalName() + " " + stockoutDao.getMenu(1); menuRequest = 2; } else { displayText = stockoutDao.getMenu(91); throw new NumberFormatException(); } break; case 99: keyValueStore.remove("facilityName." + sessionId); keyValueStore.remove("service." + sessionId); keyValueStore.remove("productName." + sessionId); keyValueStore.remove("displayText." + sessionId); keyValueStore.remove("requestId." + sessionId); keyValueStore.remove("commonStockouts." +sessionId); } } catch (NumberFormatException e) { // reload data from the last request if an error in the users input // was detected // do not call setResponse as there is no need to overwrite // previously saved menu // text with the exact same text. Also avoid concatenating multiple // error messages String strMenuRequest = (String) keyValueStore.get("requestId." + sessionId); displayText += (String) keyValueStore.get("displayText." + sessionId); response.setDisplayText(displayText); response.setRequestID(strMenuRequest); return response; } // set response once menu logic processing is complete setResponse(response, displayText, menuRequest, sessionId); return response; } // set the response object with menu text and menu level(request id), store // these variables in // key value store so they can be used for error handling if needed. private void setResponse(CMUssdResponse response, String menuText, int requestId, String sessionId) { response.setDisplayText(menuText); response.setRequestID(Integer.toString(requestId)); keyValueStore.put("displayText." + sessionId, menuText); keyValueStore .put("requestId." + sessionId, Integer.toString(requestId)); } }
true
true
public CMUssdResponse createUssdResponse(CMUssdRequest request) { CMUssdResponse response = new CMUssdResponse(); String displayText = ""; String sessionId = ""; int menuRequest = 0; try { // get the stage at which the user is in,in the ussd session menuRequest = Integer.parseInt(request.getRequestid()); // session id identifies session specific data stored in the key // value store sessionId = request.getUssdSessionId(); switch (menuRequest) { case 0: // welcome message..clinic code prompt displayText = stockoutDao.getMenu(0); ++menuRequest; break; case 1: // validate clinic and display ussd stock out services displayText = request.getRequest(); // stockoutDao.checkClinic(request.getRequest());****database // call //----------------------------------------------------------------------------- //String clinicName = displayText; //matches the best matching facility Facility facility = facilityService.getClosestMatch(displayText); //----------------------------------------------------------------------------- if (!facility.equals(null)) { // Need to set clinic name so that it can be re-used later keyValueStore.put( "facilityName." + request.getUssdSessionId(), facility); displayText = facility.getLocalName() + " " + stockoutDao.getMenu(1); ++menuRequest; } else { // displayed failed message and redisplay same menu displayText += " " + stockoutDao.getMenu(92); throw new NumberFormatException(); } break; case 2: // process service request,get list of recent medicines displayText = stockoutDao.getMenu(91); // set error message for // incorrect string // input and invalid // integer selection int requestSelection = Integer.parseInt(request.getRequest()); if (requestSelection >= 1 && requestSelection <= 3) { displayText = stockoutDao.getMenu(21); //displayText += "1.Medicine1 \n2.Medicine2 \n3.Medicine3 \n4.Medicine4"; //String[] recentStockouts = { "Medicine1", "Medicine2", // "Medicine3", "Medicine4" }; //keyValueStore.put("recentStockouts." + sessionId, //recentStockouts); // method that retrieves commonly reported stock out, from a // clinic // *****Need clinic name entered earlier // StockoutDao.retrieveCommonStockouts(keyValueStore.get("facilityName."+request.getUssdSessionId())); // ************************************************************** //----------------------------------------------------------------------------- int limit = 5; //must be facility code, not facility name String facilityCode = ((Facility) (keyValueStore.get("facilityName." + sessionId))).getUid(); //facilityCode. List<Stockout> stockouts = stockoutService.getMostCommonlyReportedStockoutsForFacility(facilityCode, limit); keyValueStore.put("commonStockouts." + sessionId,stockouts); for(int index=0;index<stockouts.size();index++){ displayText += (index+1) + "." + stockouts.get(index).getProduct().getName() + "\n"; } //or //this returns most recent reports, though I could also just return most recent actual stockouts //since multiple recent reports could be for same stockouts //List<StockoutReport> recentReports = stockoutReportService.getRecentlyReportedStockouts(limit); //----------------------------------------------------------------------------- displayText += stockoutDao.getMenu(22); keyValueStore.put("service." + sessionId, Integer.toString(requestSelection)); ++menuRequest; } else { // number greater 3 or less than 1 was chosen throw new NumberFormatException(); } break; case 3: // process user selection of recent reports or manual // medicine name entry displayText = stockoutDao.getMenu(91); int requestMedicine = Integer.parseInt(request.getRequest()); if (requestMedicine >= 1 && requestMedicine <= 7) { // process // medicine // selection // 1-8 List<Stockout> stockouts = (List<Stockout>) keyValueStore.get("commonStockouts." + sessionId); Product selectedProduct = stockouts.get(requestMedicine - 1).getProduct(); displayText = selectedProduct.getName(); keyValueStore.put("productName." + sessionId,selectedProduct); displayText += " " + stockoutDao.getMenu(4); menuRequest += 2; } else if (requestMedicine == 8) { // display enter medicine // name prompt displayText = stockoutDao.getMenu(3); ++menuRequest; } else {// user enters a number less than 1 or greater than 8 throw new NumberFormatException(); } break; case 4: // validate/find nearest match to medicine name+display // appropriate menu as above // displayText = // stockoutDao.CheckAndFindNearestMatch(request.getRequest()); //----------------------------------------------------------------------------- displayText = request.getRequest(); //String productName = "foobar"; Product searchProduct = productService.getClosestMatch(displayText); //----------------------------------------------------------------------------- if ((searchProduct != null)) { // medicine name found, go // to next menu keyValueStore.put("productName." + sessionId,searchProduct); displayText = searchProduct.getName() + " " + stockoutDao.getMenu(4); ++menuRequest; } else { // medicine name not found displayText += " " + stockoutDao.getMenu(92); throw new NumberFormatException(); } break; case 5: // run methods for each of the different services+display // result. String serviceRequest = (String) keyValueStore.get("service." + sessionId); Product selectedProduct = (Product) keyValueStore .get("productName." + sessionId); Facility selectedFacility = (Facility) keyValueStore .get("facilityName." + sessionId); int service = Integer.parseInt(serviceRequest); int requestOption = Integer.parseInt(request.getRequest()); if (requestOption == 1) { switch (service) { case 1: // StockoutDao.reportStockout(medicineName,facilityName); //----------------------------------------------------------------------------- //must be the correct facility and product code String productCode = selectedProduct.getUid(); String facilityCode = selectedFacility.getUid(); stockoutReportService.submitStockoutReport(productCode, facilityCode, null, null, null, false, false); //----------------------------------------------------------------------------- displayText = selectedProduct.getName() + " in " + selectedFacility.getLocalName() + " " + stockoutDao.getMenu(5); break; case 2: // displayText = // StockoutDao.getStatus(MedicineName,facilityName); //----------------------------------------------------------------------------- //against must be proper facility code and product code (no matching is done) String selectedFacilityCode = selectedFacility.getUid(); String selectedProductCode = selectedProduct.getUid(); Stockout stockout = stockoutService.getStockout(selectedFacilityCode, selectedProductCode); //----------------------------------------------------------------------------- displayText = stockoutDao.getMenu(6) + " " + stockout.getIssue().getState().toString(); break; case 3: // displayText = // stockoutDao.findNearestNeighbourWithStock(medicineName,facilityName); //----------------------------------------------------------------------------- Facility closestFacility = facilityService.getNearestFacilityWithStock(selectedProduct, selectedFacility); //----------------------------------------------------------------------------- displayText = stockoutDao.getMenu(7) + " " + closestFacility.getLocalName(); break; } menuRequest = 99; } else if (requestOption == 2) { displayText = stockoutDao.getMenu(21); //displayText += "1.Medicine1 \n2.Medicine2 \n3.Medicine3 \n4.Medicine4"; //String[] recentStockouts = { "Medicine1", "Medicine2", // "Medicine3", "Medicine4" }; //keyValueStore.put("recentStockouts." + sessionId, // recentStockouts); // method that retrieves commonly reported stock out, from a // clinic // *****Need clinic name entered earlier // StockoutDao.retrieveCommonStockouts(keyValueStore.get("facilityName."+request.getUssdSessionId())); // ************************************************************** //----------------------------------------------------------------------------- int limit = 5; //must be facility code, not facility name String facilityCode = ((Facility) (keyValueStore.get("facilityName." + sessionId))).getUid(); //facilityCode. List<Stockout> stockouts = stockoutService.getMostCommonlyReportedStockoutsForFacility(facilityCode, limit); keyValueStore.put("commonStockouts." + sessionId,stockouts); for(int index=0;index<stockouts.size();index++){ displayText += (index+1) + "." + stockouts.get(index).getProduct().getName() + "\n"; } //----------------------------------------------------------------------------- displayText += stockoutDao.getMenu(22); menuRequest = 3; } else if (requestOption == 3) { displayText = ((Facility)keyValueStore .get("facilityName." + sessionId)).getLocalName() + " " + stockoutDao.getMenu(1); menuRequest = 2; } else { displayText = stockoutDao.getMenu(91); throw new NumberFormatException(); } break; case 99: keyValueStore.remove("facilityName." + sessionId); keyValueStore.remove("service." + sessionId); keyValueStore.remove("productName." + sessionId); keyValueStore.remove("displayText." + sessionId); keyValueStore.remove("requestId." + sessionId); keyValueStore.remove("commonStockouts." +sessionId); } } catch (NumberFormatException e) { // reload data from the last request if an error in the users input // was detected // do not call setResponse as there is no need to overwrite // previously saved menu // text with the exact same text. Also avoid concatenating multiple // error messages String strMenuRequest = (String) keyValueStore.get("requestId." + sessionId); displayText += (String) keyValueStore.get("displayText." + sessionId); response.setDisplayText(displayText); response.setRequestID(strMenuRequest); return response; } // set response once menu logic processing is complete setResponse(response, displayText, menuRequest, sessionId); return response; }
public CMUssdResponse createUssdResponse(CMUssdRequest request) { CMUssdResponse response = new CMUssdResponse(); String displayText = ""; String sessionId = ""; int menuRequest = 0; try { // get the stage at which the user is in,in the ussd session menuRequest = Integer.parseInt(request.getRequestid()); // session id identifies session specific data stored in the key // value store sessionId = request.getUssdSessionId(); switch (menuRequest) { case 0: // welcome message..clinic code prompt displayText = stockoutDao.getMenu(0); ++menuRequest; break; case 1: // validate clinic and display ussd stock out services displayText = request.getRequest(); // stockoutDao.checkClinic(request.getRequest());****database // call //----------------------------------------------------------------------------- //String clinicName = displayText; //matches the best matching facility Facility facility = facilityService.getClosestMatch(displayText); //----------------------------------------------------------------------------- if (facility != null) { // Need to set clinic name so that it can be re-used later keyValueStore.put( "facilityName." + request.getUssdSessionId(), facility); displayText = facility.getLocalName() + " " + stockoutDao.getMenu(1); ++menuRequest; } else { // displayed failed message and redisplay same menu displayText += " " + stockoutDao.getMenu(92); throw new NumberFormatException(); } break; case 2: // process service request,get list of recent medicines displayText = stockoutDao.getMenu(91); // set error message for // incorrect string // input and invalid // integer selection int requestSelection = Integer.parseInt(request.getRequest()); if (requestSelection >= 1 && requestSelection <= 3) { displayText = stockoutDao.getMenu(21); //displayText += "1.Medicine1 \n2.Medicine2 \n3.Medicine3 \n4.Medicine4"; //String[] recentStockouts = { "Medicine1", "Medicine2", // "Medicine3", "Medicine4" }; //keyValueStore.put("recentStockouts." + sessionId, //recentStockouts); // method that retrieves commonly reported stock out, from a // clinic // *****Need clinic name entered earlier // StockoutDao.retrieveCommonStockouts(keyValueStore.get("facilityName."+request.getUssdSessionId())); // ************************************************************** //----------------------------------------------------------------------------- int limit = 5; //must be facility code, not facility name String facilityCode = ((Facility) (keyValueStore.get("facilityName." + sessionId))).getUid(); //facilityCode. List<Stockout> stockouts = stockoutService.getMostCommonlyReportedStockoutsForFacility(facilityCode, limit); keyValueStore.put("commonStockouts." + sessionId,stockouts); for(int index=0;index<stockouts.size();index++){ displayText += (index+1) + "." + stockouts.get(index).getProduct().getName() + "\n"; } //or //this returns most recent reports, though I could also just return most recent actual stockouts //since multiple recent reports could be for same stockouts //List<StockoutReport> recentReports = stockoutReportService.getRecentlyReportedStockouts(limit); //----------------------------------------------------------------------------- displayText += stockoutDao.getMenu(22); keyValueStore.put("service." + sessionId, Integer.toString(requestSelection)); ++menuRequest; } else { // number greater 3 or less than 1 was chosen throw new NumberFormatException(); } break; case 3: // process user selection of recent reports or manual // medicine name entry displayText = stockoutDao.getMenu(91); int requestMedicine = Integer.parseInt(request.getRequest()); if (requestMedicine >= 1 && requestMedicine <= 7) { // process // medicine // selection // 1-8 List<Stockout> stockouts = (List<Stockout>) keyValueStore.get("commonStockouts." + sessionId); Product selectedProduct = stockouts.get(requestMedicine - 1).getProduct(); displayText = selectedProduct.getName(); keyValueStore.put("productName." + sessionId,selectedProduct); displayText += " " + stockoutDao.getMenu(4); menuRequest += 2; } else if (requestMedicine == 8) { // display enter medicine // name prompt displayText = stockoutDao.getMenu(3); ++menuRequest; } else {// user enters a number less than 1 or greater than 8 throw new NumberFormatException(); } break; case 4: // validate/find nearest match to medicine name+display // appropriate menu as above // displayText = // stockoutDao.CheckAndFindNearestMatch(request.getRequest()); //----------------------------------------------------------------------------- displayText = request.getRequest(); //String productName = "foobar"; Product searchProduct = productService.getClosestMatch(displayText); //----------------------------------------------------------------------------- if ((searchProduct != null)) { // medicine name found, go // to next menu keyValueStore.put("productName." + sessionId,searchProduct); displayText = searchProduct.getName() + " " + stockoutDao.getMenu(4); ++menuRequest; } else { // medicine name not found displayText += " " + stockoutDao.getMenu(92); throw new NumberFormatException(); } break; case 5: // run methods for each of the different services+display // result. String serviceRequest = (String) keyValueStore.get("service." + sessionId); Product selectedProduct = (Product) keyValueStore .get("productName." + sessionId); Facility selectedFacility = (Facility) keyValueStore .get("facilityName." + sessionId); int service = Integer.parseInt(serviceRequest); int requestOption = Integer.parseInt(request.getRequest()); if (requestOption == 1) { switch (service) { case 1: // StockoutDao.reportStockout(medicineName,facilityName); //----------------------------------------------------------------------------- //must be the correct facility and product code String productCode = selectedProduct.getUid(); String facilityCode = selectedFacility.getUid(); stockoutReportService.submitStockoutReport(productCode, facilityCode, null, null, null, false, false); //----------------------------------------------------------------------------- displayText = selectedProduct.getName() + " in " + selectedFacility.getLocalName() + " " + stockoutDao.getMenu(5); break; case 2: // displayText = // StockoutDao.getStatus(MedicineName,facilityName); //----------------------------------------------------------------------------- //against must be proper facility code and product code (no matching is done) String selectedFacilityCode = selectedFacility.getUid(); String selectedProductCode = selectedProduct.getUid(); Stockout stockout = stockoutService.getStockout(selectedFacilityCode, selectedProductCode); //----------------------------------------------------------------------------- displayText = stockoutDao.getMenu(6) + " " + stockout.getIssue().getState().toString(); break; case 3: // displayText = // stockoutDao.findNearestNeighbourWithStock(medicineName,facilityName); //----------------------------------------------------------------------------- Facility closestFacility = facilityService.getNearestFacilityWithStock(selectedProduct, selectedFacility); //----------------------------------------------------------------------------- displayText = stockoutDao.getMenu(7) + " " + closestFacility.getLocalName(); break; } menuRequest = 99; } else if (requestOption == 2) { displayText = stockoutDao.getMenu(21); //displayText += "1.Medicine1 \n2.Medicine2 \n3.Medicine3 \n4.Medicine4"; //String[] recentStockouts = { "Medicine1", "Medicine2", // "Medicine3", "Medicine4" }; //keyValueStore.put("recentStockouts." + sessionId, // recentStockouts); // method that retrieves commonly reported stock out, from a // clinic // *****Need clinic name entered earlier // StockoutDao.retrieveCommonStockouts(keyValueStore.get("facilityName."+request.getUssdSessionId())); // ************************************************************** //----------------------------------------------------------------------------- int limit = 5; //must be facility code, not facility name String facilityCode = ((Facility) (keyValueStore.get("facilityName." + sessionId))).getUid(); //facilityCode. List<Stockout> stockouts = stockoutService.getMostCommonlyReportedStockoutsForFacility(facilityCode, limit); keyValueStore.put("commonStockouts." + sessionId,stockouts); for(int index=0;index<stockouts.size();index++){ displayText += (index+1) + "." + stockouts.get(index).getProduct().getName() + "\n"; } //----------------------------------------------------------------------------- displayText += stockoutDao.getMenu(22); menuRequest = 3; } else if (requestOption == 3) { displayText = ((Facility)keyValueStore .get("facilityName." + sessionId)).getLocalName() + " " + stockoutDao.getMenu(1); menuRequest = 2; } else { displayText = stockoutDao.getMenu(91); throw new NumberFormatException(); } break; case 99: keyValueStore.remove("facilityName." + sessionId); keyValueStore.remove("service." + sessionId); keyValueStore.remove("productName." + sessionId); keyValueStore.remove("displayText." + sessionId); keyValueStore.remove("requestId." + sessionId); keyValueStore.remove("commonStockouts." +sessionId); } } catch (NumberFormatException e) { // reload data from the last request if an error in the users input // was detected // do not call setResponse as there is no need to overwrite // previously saved menu // text with the exact same text. Also avoid concatenating multiple // error messages String strMenuRequest = (String) keyValueStore.get("requestId." + sessionId); displayText += (String) keyValueStore.get("displayText." + sessionId); response.setDisplayText(displayText); response.setRequestID(strMenuRequest); return response; } // set response once menu logic processing is complete setResponse(response, displayText, menuRequest, sessionId); return response; }
diff --git a/main/java/org/spoutcraft/spoutcraftapi/addon/SimpleAddonManager.java b/main/java/org/spoutcraft/spoutcraftapi/addon/SimpleAddonManager.java index d145b00c..806e6922 100644 --- a/main/java/org/spoutcraft/spoutcraftapi/addon/SimpleAddonManager.java +++ b/main/java/org/spoutcraft/spoutcraftapi/addon/SimpleAddonManager.java @@ -1,332 +1,332 @@ /* * This file is part of Spoutcraft API (http://wiki.getspout.org/). * * Spoutcraft API 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. * * Spoutcraft API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.spoutcraft.spoutcraftapi.addon; import java.io.File; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bukkit.util.FileUtil; import org.spoutcraft.spoutcraftapi.Client; import org.spoutcraft.spoutcraftapi.command.AddonCommandYamlParser; import org.spoutcraft.spoutcraftapi.command.Command; import org.spoutcraft.spoutcraftapi.command.SimpleCommandMap; import org.spoutcraft.spoutcraftapi.event.Event; import org.spoutcraft.spoutcraftapi.event.HandlerList; import org.spoutcraft.spoutcraftapi.event.Listener; public class SimpleAddonManager implements AddonManager { private Client client; private final Map<Pattern, AddonLoader> fileAssociations = new HashMap<Pattern, AddonLoader>(); private final List<Addon> addons = new ArrayList<Addon>(); private final Map<String, Addon> lookupNames = new HashMap<String, Addon>(); private static File updateDirectory = null; private final SimpleCommandMap commandMap; public SimpleAddonManager(Client instance, SimpleCommandMap commandMap) { client = instance; this.commandMap = commandMap; } /** * Registers the specified addon loader * * @param loader Class name of the AddonLoader to register * @throws IllegalArgumentException Thrown when the given Class is not a valid AddonLoader */ public void registerInterface(Class<? extends AddonLoader> loader) throws IllegalArgumentException { AddonLoader instance; if (AddonLoader.class.isAssignableFrom(loader)) { Constructor<? extends AddonLoader> constructor; try { constructor = loader.getConstructor(Client.class); instance = constructor.newInstance(client); } catch (NoSuchMethodException ex) { String className = loader.getName(); throw new IllegalArgumentException(String.format("Class %s does not have a public %s(Spoutcraft) constructor", className, className), ex); } catch (Exception ex) { throw new IllegalArgumentException(String.format("Unexpected exception %s while attempting to construct a new instance of %s", ex.getClass().getName(), loader.getName()), ex); } } else { throw new IllegalArgumentException(String.format("Class %s does not implement interface AddonLoader", loader.getName())); } Pattern[] patterns = instance.getAddonFileFilters(); synchronized (this) { for (Pattern pattern : patterns) { fileAssociations.put(pattern, instance); } } } /** * Loads the addons contained within the specified directory * * @param directory Directory to check for addons * @return A list of all addons loaded */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Addon[] loadAddons(File directory) { List<Addon> result = new ArrayList<Addon>(); File[] files = directory.listFiles(); boolean allFailed = false; boolean finalPass = false; LinkedList<File> filesList = new LinkedList(Arrays.asList(files)); if (!(client.getUpdateFolder().equals(""))) { - updateDirectory = new File(directory, client.getUpdateFolder()); + updateDirectory = client.getUpdateFolder(); } while (!allFailed || finalPass) { allFailed = true; Iterator<File> itr = filesList.iterator(); while (itr.hasNext()) { File file = itr.next(); Addon addon = null; try { addon = loadAddon(file, finalPass); itr.remove(); } catch (UnknownDependencyException ex) { if (finalPass) { client.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': " + ex.getMessage(), ex); itr.remove(); } else { addon = null; } } catch (InvalidAddonException ex) { client.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': ", ex.getCause()); itr.remove(); } catch (InvalidDescriptionException ex) { client.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': " + ex.getMessage(), ex); itr.remove(); } if (addon != null) { result.add(addon); allFailed = false; finalPass = false; } } if (finalPass) { break; } else if (allFailed) { finalPass = true; } } return result.toArray(new Addon[result.size()]); } /** * Loads the addon in the specified file * * File must be valid according to the current enabled Addon interfaces * * @param file File containing the addon to load * @return The Addon loaded, or null if it was invalid * @throws InvalidAddonException Thrown when the specified file is not a valid addon * @throws InvalidDescriptionException Thrown when the specified file contains an invalid description */ public synchronized Addon loadAddon(File file) throws InvalidAddonException, InvalidDescriptionException, UnknownDependencyException { return loadAddon(file, true); } /** * Loads the addon in the specified file * * File must be valid according to the current enabled Addon interfaces * * @param file File containing the addon to load * @param ignoreSoftDependencies Loader will ignore soft dependencies if this flag is set to true * @return The Addon loaded, or null if it was invalid * @throws InvalidAddonException Thrown when the specified file is not a valid addon * @throws InvalidDescriptionException Thrown when the specified file contains an invalid description */ public synchronized Addon loadAddon(File file, boolean ignoreSoftDependencies) throws InvalidAddonException, InvalidDescriptionException, UnknownDependencyException { File updateFile = null; if (updateDirectory != null && updateDirectory.isDirectory() && (updateFile = new File(updateDirectory, file.getName())).isFile()) { if (FileUtil.copy(updateFile, file)) { updateFile.delete(); } } Set<Pattern> filters = fileAssociations.keySet(); Addon result = null; for (Pattern filter : filters) { String name = file.getName(); Matcher match = filter.matcher(name); if (match.find()) { AddonLoader loader = fileAssociations.get(filter); result = loader.loadAddon(file, ignoreSoftDependencies); } } if (result != null) { addons.add(result); lookupNames.put(result.getDescription().getName(), result); } return result; } /** * Checks if the given addon is loaded and returns it when applicable * * Please note that the name of the addon is case-sensitive * * @param name Name of the addon to check * @return Addon if it exists, otherwise null */ public synchronized Addon getAddon(String name) { return lookupNames.get(name); } public synchronized Addon[] getAddons() { return addons.toArray(new Addon[0]); } /** * Checks if the given addon is enabled or not * * Please note that the name of the addon is case-sensitive. * * @param name Name of the addon to check * @return true if the addon is enabled, otherwise false */ public boolean isAddonEnabled(String name) { Addon addon = getAddon(name); return isAddonEnabled(addon); } /** * Checks if the given addon is enabled or not * * @param addon Addon to check * @return true if the addon is enabled, otherwise false */ public boolean isAddonEnabled(Addon addon) { if ((addon != null) && (addons.contains(addon))) { return addon.isEnabled(); } else { return false; } } public void enableAddon(final Addon addon) { if (!addon.isEnabled()) { List<Command> addonCommands = AddonCommandYamlParser.parse(addon); if (!addonCommands.isEmpty()) { commandMap.registerAll(addon.getDescription().getName(), addonCommands); } try { addon.getAddonLoader().enableAddon(addon); } catch (Throwable ex) { client.getLogger().log(Level.SEVERE, "Error occurred (in the addon loader) while enabling " + addon.getDescription().getFullName() + " (Is it up to date?): " + ex.getMessage(), ex); } } } public void disableAddons() { for (Addon addon : getAddons()) { disableAddon(addon); } } public void disableAddon(final Addon addon) { if (addon.isEnabled()) { try { addon.getAddonLoader().disableAddon(addon); } catch (Throwable ex) { client.getLogger().log(Level.SEVERE, "Error occurred (in the addon loader) while disabling " + addon.getDescription().getFullName() + " (Is it up to date?): " + ex.getMessage(), ex); } } } public void clearAddons() { synchronized (this) { disableAddons(); addons.clear(); lookupNames.clear(); HandlerList.clearAll(); } } /** * Calls a player related event with the given details * * @param type Type of player related event to call * @param event Event details */ /** * Call an event. * * @param <TEvent> Event subclass * @param event Event to handle * @author lahwran */ public <TEvent extends Event<TEvent>> void callEvent(TEvent event) { HandlerList<TEvent> handlerlist = event.getHandlers(); handlerlist.bake(); Listener<TEvent>[][] handlers = handlerlist.handlers; int[] handlerids = handlerlist.handlerids; for (int arrayidx = 0; arrayidx < handlers.length; arrayidx++) { // if the order slot is even and the event has stopped propogating if (event.isCancelled() && (handlerids[arrayidx] & 1) == 0) continue; // then don't call this order slot for (int handler = 0; handler < handlers[arrayidx].length; handler++) { try { handlers[arrayidx][handler].onEvent(event); } catch (Throwable t) { System.err.println("Error while passing event " + event); t.printStackTrace(); } } } } }
true
true
public Addon[] loadAddons(File directory) { List<Addon> result = new ArrayList<Addon>(); File[] files = directory.listFiles(); boolean allFailed = false; boolean finalPass = false; LinkedList<File> filesList = new LinkedList(Arrays.asList(files)); if (!(client.getUpdateFolder().equals(""))) { updateDirectory = new File(directory, client.getUpdateFolder()); } while (!allFailed || finalPass) { allFailed = true; Iterator<File> itr = filesList.iterator(); while (itr.hasNext()) { File file = itr.next(); Addon addon = null; try { addon = loadAddon(file, finalPass); itr.remove(); } catch (UnknownDependencyException ex) { if (finalPass) { client.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': " + ex.getMessage(), ex); itr.remove(); } else { addon = null; } } catch (InvalidAddonException ex) { client.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': ", ex.getCause()); itr.remove(); } catch (InvalidDescriptionException ex) { client.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': " + ex.getMessage(), ex); itr.remove(); } if (addon != null) { result.add(addon); allFailed = false; finalPass = false; } } if (finalPass) { break; } else if (allFailed) { finalPass = true; } } return result.toArray(new Addon[result.size()]); }
public Addon[] loadAddons(File directory) { List<Addon> result = new ArrayList<Addon>(); File[] files = directory.listFiles(); boolean allFailed = false; boolean finalPass = false; LinkedList<File> filesList = new LinkedList(Arrays.asList(files)); if (!(client.getUpdateFolder().equals(""))) { updateDirectory = client.getUpdateFolder(); } while (!allFailed || finalPass) { allFailed = true; Iterator<File> itr = filesList.iterator(); while (itr.hasNext()) { File file = itr.next(); Addon addon = null; try { addon = loadAddon(file, finalPass); itr.remove(); } catch (UnknownDependencyException ex) { if (finalPass) { client.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': " + ex.getMessage(), ex); itr.remove(); } else { addon = null; } } catch (InvalidAddonException ex) { client.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': ", ex.getCause()); itr.remove(); } catch (InvalidDescriptionException ex) { client.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': " + ex.getMessage(), ex); itr.remove(); } if (addon != null) { result.add(addon); allFailed = false; finalPass = false; } } if (finalPass) { break; } else if (allFailed) { finalPass = true; } } return result.toArray(new Addon[result.size()]); }
diff --git a/src/org/odk/collect/android/logic/PropertyManager.java b/src/org/odk/collect/android/logic/PropertyManager.java index d6c3263..2497c68 100644 --- a/src/org/odk/collect/android/logic/PropertyManager.java +++ b/src/org/odk/collect/android/logic/PropertyManager.java @@ -1,109 +1,109 @@ /* * Copyright (C) 2009 University of Washington * * 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.odk.collect.android.logic; import org.javarosa.core.services.IPropertyManager; import org.javarosa.core.services.properties.IPropertyRules; import android.content.Context; import android.provider.Settings; import android.telephony.TelephonyManager; import android.util.Log; import java.util.HashMap; import java.util.Vector; /** * Used to return device properties to JavaRosa * * @author Yaw Anokwa ([email protected]) */ public class PropertyManager implements IPropertyManager { private String t = "PropertyManager"; private Context mContext; private TelephonyManager mTelephonyManager; private HashMap<String, String> mProperties; private final static String DEVICE_ID_PROPERTY = "deviceid"; // imei private final static String SUBSCRIBER_ID_PROPERTY = "subscriberid"; // imsi private final static String SIM_SERIAL_PROPERTY = "simserial"; private final static String PHONE_NUMBER_PROPERTY = "phonenumber"; public String getName() { return "Property Manager"; } public PropertyManager(Context context) { Log.i(t, "calling constructor"); mContext = context; mProperties = new HashMap<String, String>(); mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String deviceId = mTelephonyManager.getDeviceId(); - if (deviceId != null && (deviceId.contains("*") || Double.valueOf(deviceId) == 0.0)) { + if (deviceId != null && (deviceId.contains("*") || deviceId.contains("000000000000000"))) { deviceId = Settings.Secure .getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID); } mProperties.put(DEVICE_ID_PROPERTY, deviceId); mProperties.put(SUBSCRIBER_ID_PROPERTY, mTelephonyManager.getSubscriberId()); mProperties.put(SIM_SERIAL_PROPERTY, mTelephonyManager.getSimSerialNumber()); mProperties.put(PHONE_NUMBER_PROPERTY, mTelephonyManager.getLine1Number()); } @Override public Vector<String> getProperty(String propertyName) { return null; } @Override public String getSingularProperty(String propertyName) { return mProperties.get(propertyName.toLowerCase()); } @Override public void setProperty(String propertyName, String propertyValue) { } @Override public void setProperty(String propertyName, @SuppressWarnings("rawtypes") Vector propertyValue) { } @Override public void addRules(IPropertyRules rules) { } @Override public Vector<IPropertyRules> getRules() { return null; } }
true
true
public PropertyManager(Context context) { Log.i(t, "calling constructor"); mContext = context; mProperties = new HashMap<String, String>(); mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String deviceId = mTelephonyManager.getDeviceId(); if (deviceId != null && (deviceId.contains("*") || Double.valueOf(deviceId) == 0.0)) { deviceId = Settings.Secure .getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID); } mProperties.put(DEVICE_ID_PROPERTY, deviceId); mProperties.put(SUBSCRIBER_ID_PROPERTY, mTelephonyManager.getSubscriberId()); mProperties.put(SIM_SERIAL_PROPERTY, mTelephonyManager.getSimSerialNumber()); mProperties.put(PHONE_NUMBER_PROPERTY, mTelephonyManager.getLine1Number()); }
public PropertyManager(Context context) { Log.i(t, "calling constructor"); mContext = context; mProperties = new HashMap<String, String>(); mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String deviceId = mTelephonyManager.getDeviceId(); if (deviceId != null && (deviceId.contains("*") || deviceId.contains("000000000000000"))) { deviceId = Settings.Secure .getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID); } mProperties.put(DEVICE_ID_PROPERTY, deviceId); mProperties.put(SUBSCRIBER_ID_PROPERTY, mTelephonyManager.getSubscriberId()); mProperties.put(SIM_SERIAL_PROPERTY, mTelephonyManager.getSimSerialNumber()); mProperties.put(PHONE_NUMBER_PROPERTY, mTelephonyManager.getLine1Number()); }
diff --git a/mod/jodd-wot/test/jodd/db/DbMiscTest.java b/mod/jodd-wot/test/jodd/db/DbMiscTest.java index 631a359e2..9b752b47b 100644 --- a/mod/jodd-wot/test/jodd/db/DbMiscTest.java +++ b/mod/jodd-wot/test/jodd/db/DbMiscTest.java @@ -1,131 +1,131 @@ // Copyright (c) 2003-2012, Jodd Team (jodd.org). All Rights Reserved. package jodd.db; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import java.util.HashMap; public class DbMiscTest extends DbHsqldbTestCase { public void testBig() throws Exception { DbSession session = new DbSession(cp); DbQuery query = new DbQuery(session, "select count(*) from GIRL"); assertEquals(0, query.executeCount()); assertEquals(1, executeUpdate(session, "insert into GIRL values(1, 'Anna', 'seduction')")); assertEquals(1, query.executeCount()); assertEquals(1, executeUpdate(session, "insert into GIRL values(2, 'Sandra', 'spying')")); assertEquals(2, query.executeCount()); assertEquals(1, executeUpdate(session, "insert into GIRL values(3, 'Monica', 'hacking')")); assertEquals(3, query.executeCount()); assertEquals(0, query.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); query.close(); // play with the query String sql = "select * from GIRL where ID = :id"; query = new DbQuery(session, sql); query.setDebugMode(); query.setInteger("id", 2); ResultSet rs = query.execute(); assertEquals(1, query.getOpenResultSetCount()); // assertEquals(1, DbQuery.totalOpenResultSetCount); - assertEquals("select * from GIRL where ID = 2\nExecution time: ", query.getQueryString().substring(0, 48)); + assertEquals("select * from GIRL where ID = 2", query.getQueryString()); while (rs.next()) { assertEquals(2, rs.getInt(1)); assertEquals("Sandra", rs.getString(2)); assertEquals("spying", rs.getString(3)); } assertFalse(query.isClosed()); session.closeSession(); assertTrue(query.isClosed()); assertEquals(0, query.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); // thread dbsession DbSession dbts = new DbThreadSession(cp); DbQuery q = new DbQuery("select count(*) from GIRL"); assertEquals(3, q.executeCount()); dbts.closeSession(); assertNull(DbThreadSession.getCurrentSession()); // transaction example DbSession session1 = new DbSession(cp); DbSession session2 = new DbSession(cp); session1.beginTransaction(new DbTransactionMode().setReadOnly(false)); query = new DbQuery(session1, "insert into GIRL values(4, 'Jeniffer', 'fighting')"); assertEquals(1, query.executeUpdate()); query.close(); DbQuery query2 = new DbQuery(session2, "select count(*) from GIRL"); assertEquals(0, query2.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); rs = query2.execute(); if (rs.next()) { // count before rollback (READ_UNCOMMITTED isolation level) assertEquals(4, rs.getInt(1)); } assertEquals(1, query2.getOpenResultSetCount()); // assertEquals(1, DbQuery.totalOpenResultSetCount); // // HSQLDB supports transactions at the READ_UNCOMMITTED level, also known // // as level 0 transaction isolation. This means that during the lifetime of // // a transaction, other connections to the database can see the changes made // // to the data // session1.rollbackTransaction(); rs = query2.execute(); assertEquals(2, query2.getOpenResultSetCount()); // assertEquals(2, DbQuery.totalOpenResultSetCount); if (rs.next()) { assertEquals(3, rs.getInt(1)); } session2.closeSession(); assertEquals(0, query2.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); session1.closeSession(); } public void testSetMap() throws SQLException { DbSession session = new DbSession(cp); DbQuery dbQuery = new DbQuery(session, "select * from GIRL where ID = :id"); Map<String, Object> map = new HashMap<String, Object>(); map.put("id", Integer.valueOf(1)); dbQuery.setMap(map); ResultSet rs = dbQuery.execute(); if (rs.next()) { assertEquals(1, rs.getInt(1)); } } public void testSetObjects() throws SQLException { DbSession session = new DbSession(cp); DbQuery dbQuery = new DbQuery(session, "select * from GIRL where ID = ?"); Object[] o = {Integer.valueOf(1)}; dbQuery.setObjects(o); ResultSet rs = dbQuery.execute(); if (rs.next()) { assertEquals(1, rs.getInt(1)); } } }
true
true
public void testBig() throws Exception { DbSession session = new DbSession(cp); DbQuery query = new DbQuery(session, "select count(*) from GIRL"); assertEquals(0, query.executeCount()); assertEquals(1, executeUpdate(session, "insert into GIRL values(1, 'Anna', 'seduction')")); assertEquals(1, query.executeCount()); assertEquals(1, executeUpdate(session, "insert into GIRL values(2, 'Sandra', 'spying')")); assertEquals(2, query.executeCount()); assertEquals(1, executeUpdate(session, "insert into GIRL values(3, 'Monica', 'hacking')")); assertEquals(3, query.executeCount()); assertEquals(0, query.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); query.close(); // play with the query String sql = "select * from GIRL where ID = :id"; query = new DbQuery(session, sql); query.setDebugMode(); query.setInteger("id", 2); ResultSet rs = query.execute(); assertEquals(1, query.getOpenResultSetCount()); // assertEquals(1, DbQuery.totalOpenResultSetCount); assertEquals("select * from GIRL where ID = 2\nExecution time: ", query.getQueryString().substring(0, 48)); while (rs.next()) { assertEquals(2, rs.getInt(1)); assertEquals("Sandra", rs.getString(2)); assertEquals("spying", rs.getString(3)); } assertFalse(query.isClosed()); session.closeSession(); assertTrue(query.isClosed()); assertEquals(0, query.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); // thread dbsession DbSession dbts = new DbThreadSession(cp); DbQuery q = new DbQuery("select count(*) from GIRL"); assertEquals(3, q.executeCount()); dbts.closeSession(); assertNull(DbThreadSession.getCurrentSession()); // transaction example DbSession session1 = new DbSession(cp); DbSession session2 = new DbSession(cp); session1.beginTransaction(new DbTransactionMode().setReadOnly(false)); query = new DbQuery(session1, "insert into GIRL values(4, 'Jeniffer', 'fighting')"); assertEquals(1, query.executeUpdate()); query.close(); DbQuery query2 = new DbQuery(session2, "select count(*) from GIRL"); assertEquals(0, query2.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); rs = query2.execute(); if (rs.next()) { // count before rollback (READ_UNCOMMITTED isolation level) assertEquals(4, rs.getInt(1)); } assertEquals(1, query2.getOpenResultSetCount()); // assertEquals(1, DbQuery.totalOpenResultSetCount); // // HSQLDB supports transactions at the READ_UNCOMMITTED level, also known // // as level 0 transaction isolation. This means that during the lifetime of // // a transaction, other connections to the database can see the changes made // // to the data // session1.rollbackTransaction(); rs = query2.execute(); assertEquals(2, query2.getOpenResultSetCount()); // assertEquals(2, DbQuery.totalOpenResultSetCount); if (rs.next()) { assertEquals(3, rs.getInt(1)); } session2.closeSession(); assertEquals(0, query2.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); session1.closeSession(); }
public void testBig() throws Exception { DbSession session = new DbSession(cp); DbQuery query = new DbQuery(session, "select count(*) from GIRL"); assertEquals(0, query.executeCount()); assertEquals(1, executeUpdate(session, "insert into GIRL values(1, 'Anna', 'seduction')")); assertEquals(1, query.executeCount()); assertEquals(1, executeUpdate(session, "insert into GIRL values(2, 'Sandra', 'spying')")); assertEquals(2, query.executeCount()); assertEquals(1, executeUpdate(session, "insert into GIRL values(3, 'Monica', 'hacking')")); assertEquals(3, query.executeCount()); assertEquals(0, query.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); query.close(); // play with the query String sql = "select * from GIRL where ID = :id"; query = new DbQuery(session, sql); query.setDebugMode(); query.setInteger("id", 2); ResultSet rs = query.execute(); assertEquals(1, query.getOpenResultSetCount()); // assertEquals(1, DbQuery.totalOpenResultSetCount); assertEquals("select * from GIRL where ID = 2", query.getQueryString()); while (rs.next()) { assertEquals(2, rs.getInt(1)); assertEquals("Sandra", rs.getString(2)); assertEquals("spying", rs.getString(3)); } assertFalse(query.isClosed()); session.closeSession(); assertTrue(query.isClosed()); assertEquals(0, query.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); // thread dbsession DbSession dbts = new DbThreadSession(cp); DbQuery q = new DbQuery("select count(*) from GIRL"); assertEquals(3, q.executeCount()); dbts.closeSession(); assertNull(DbThreadSession.getCurrentSession()); // transaction example DbSession session1 = new DbSession(cp); DbSession session2 = new DbSession(cp); session1.beginTransaction(new DbTransactionMode().setReadOnly(false)); query = new DbQuery(session1, "insert into GIRL values(4, 'Jeniffer', 'fighting')"); assertEquals(1, query.executeUpdate()); query.close(); DbQuery query2 = new DbQuery(session2, "select count(*) from GIRL"); assertEquals(0, query2.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); rs = query2.execute(); if (rs.next()) { // count before rollback (READ_UNCOMMITTED isolation level) assertEquals(4, rs.getInt(1)); } assertEquals(1, query2.getOpenResultSetCount()); // assertEquals(1, DbQuery.totalOpenResultSetCount); // // HSQLDB supports transactions at the READ_UNCOMMITTED level, also known // // as level 0 transaction isolation. This means that during the lifetime of // // a transaction, other connections to the database can see the changes made // // to the data // session1.rollbackTransaction(); rs = query2.execute(); assertEquals(2, query2.getOpenResultSetCount()); // assertEquals(2, DbQuery.totalOpenResultSetCount); if (rs.next()) { assertEquals(3, rs.getInt(1)); } session2.closeSession(); assertEquals(0, query2.getOpenResultSetCount()); // assertEquals(0, DbQuery.totalOpenResultSetCount); session1.closeSession(); }
diff --git a/org.eclipse.jdt.launching.macosx/macosx/org/eclipse/jdt/internal/launching/macosx/MacOSXLaunchingPlugin.java b/org.eclipse.jdt.launching.macosx/macosx/org/eclipse/jdt/internal/launching/macosx/MacOSXLaunchingPlugin.java index f895d30fc..80a4fad2a 100644 --- a/org.eclipse.jdt.launching.macosx/macosx/org/eclipse/jdt/internal/launching/macosx/MacOSXLaunchingPlugin.java +++ b/org.eclipse.jdt.launching.macosx/macosx/org/eclipse/jdt/internal/launching/macosx/MacOSXLaunchingPlugin.java @@ -1,143 +1,156 @@ /******************************************************************************* * 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.jdt.internal.launching.macosx; import java.io.*; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.eclipse.core.runtime.IPluginDescriptor; import org.eclipse.core.runtime.Plugin; public class MacOSXLaunchingPlugin extends Plugin { private static MacOSXLaunchingPlugin fgPlugin; private static final String RESOURCE_BUNDLE= "org.eclipse.jdt.internal.launching.macosx.MacOSXLauncherMessages";//$NON-NLS-1$ private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); public MacOSXLaunchingPlugin(IPluginDescriptor descriptor) { super(descriptor); fgPlugin= this; } public static MacOSXLaunchingPlugin getDefault() { return fgPlugin; } static String getString(String key) { try { return fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } } /** * Convenience method which returns the unique identifier of this plugin. */ static String getUniqueIdentifier() { if (getDefault() == null) { // If the default instance is not yet initialized, // return a static identifier. This identifier must // match the plugin id defined in plugin.xml return "org.eclipse.jdt.launching.macosx"; //$NON-NLS-1$ } return getDefault().getDescriptor().getUniqueIdentifier(); } static String[] wrap(Class clazz, String[] cmdLine) { // System.err.println("wrap:"); // for (int ii= 0; ii < cmdLine.length; ii++) { // System.err.println(" " + cmdLine[ii]); // } // System.err.println(); for (int i= 0; i < cmdLine.length; i++) { String arg= cmdLine[i]; if (arg.indexOf("swt.jar") >= 0 || arg.indexOf("org.eclipse.swt") >= 0 || "-ws".equals(arg)) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String[] cmdLine2= new String[cmdLine.length + 2]; String wrapper= createWrapper(clazz, "start_carbon.sh"); //$NON-NLS-1$ int j= 0; cmdLine2[j++]= "/bin/sh"; //$NON-NLS-1$ cmdLine2[j++]= wrapper; for (i= 0; i < cmdLine.length; i++) cmdLine2[j++]= cmdLine[i]; return cmdLine2; } } return cmdLine; } static String createWrapper(Class where, String filename) { /* * In order to build an application bundle under MacOS X we need a small stub * that reads the various artefacts of a bundle and starts the Java VM. We copy * the stub either from the running Eclipse or from the JavaVM * framework. Here we create the appropriate pathname. */ + int pos= 0; String javaApplStub= System.getProperty("sun.boot.library.path"); //$NON-NLS-1$ - int pos= javaApplStub.indexOf(':'); + if (javaApplStub != null) + pos= javaApplStub.indexOf(':'); if (pos > 0) javaApplStub= javaApplStub.substring(0, pos); String expected= "/Contents/Resources/Java"; //$NON-NLS-1$ if (javaApplStub.endsWith(expected)) { javaApplStub= javaApplStub.substring(0, javaApplStub.length()-expected.length()); javaApplStub+= "/Contents/MacOS/"; //$NON-NLS-1$ } else { - javaApplStub= "/System/Library/Frameworks/JavaVM.framework/Versions/A/Resources/MacOS/"; //$NON-NLS-1$ + javaApplStub= System.getProperty("java.class.path"); //$NON-NLS-1$ + if (javaApplStub != null) + pos= javaApplStub.indexOf(expected); + else + pos= 0; + if (pos > 0) { + javaApplStub= javaApplStub.substring(0, pos); + javaApplStub+= "/Contents/MacOS/"; //$NON-NLS-1$ + } else { + // fall back + javaApplStub= "/System/Library/Frameworks/JavaVM.framework/Versions/A/Resources/MacOS/"; //$NON-NLS-1$ + } } javaApplStub= "JAVASTUB=\""+ javaApplStub + "\"\n"; //$NON-NLS-1$ //$NON-NLS-2$ String output= "/tmp/start_carbon.sh"; //$NON-NLS-1$ FileOutputStream os= null; try { os= new FileOutputStream(output); } catch (FileNotFoundException ex) { return null; } InputStream is= null; try { os.write("#!/bin/sh\n".getBytes()); //$NON-NLS-1$ os.write(javaApplStub.getBytes()); is= where.getResourceAsStream(filename); if (is != null) { while (true) { int c= is.read(); if (c == -1) break; os.write(c); } } os.flush(); } catch (IOException io) { return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } try { os.close(); } catch(IOException e) { } } return output; } }
false
true
static String createWrapper(Class where, String filename) { /* * In order to build an application bundle under MacOS X we need a small stub * that reads the various artefacts of a bundle and starts the Java VM. We copy * the stub either from the running Eclipse or from the JavaVM * framework. Here we create the appropriate pathname. */ String javaApplStub= System.getProperty("sun.boot.library.path"); //$NON-NLS-1$ int pos= javaApplStub.indexOf(':'); if (pos > 0) javaApplStub= javaApplStub.substring(0, pos); String expected= "/Contents/Resources/Java"; //$NON-NLS-1$ if (javaApplStub.endsWith(expected)) { javaApplStub= javaApplStub.substring(0, javaApplStub.length()-expected.length()); javaApplStub+= "/Contents/MacOS/"; //$NON-NLS-1$ } else { javaApplStub= "/System/Library/Frameworks/JavaVM.framework/Versions/A/Resources/MacOS/"; //$NON-NLS-1$ } javaApplStub= "JAVASTUB=\""+ javaApplStub + "\"\n"; //$NON-NLS-1$ //$NON-NLS-2$ String output= "/tmp/start_carbon.sh"; //$NON-NLS-1$ FileOutputStream os= null; try { os= new FileOutputStream(output); } catch (FileNotFoundException ex) { return null; } InputStream is= null; try { os.write("#!/bin/sh\n".getBytes()); //$NON-NLS-1$ os.write(javaApplStub.getBytes()); is= where.getResourceAsStream(filename); if (is != null) { while (true) { int c= is.read(); if (c == -1) break; os.write(c); } } os.flush(); } catch (IOException io) { return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } try { os.close(); } catch(IOException e) { } } return output; }
static String createWrapper(Class where, String filename) { /* * In order to build an application bundle under MacOS X we need a small stub * that reads the various artefacts of a bundle and starts the Java VM. We copy * the stub either from the running Eclipse or from the JavaVM * framework. Here we create the appropriate pathname. */ int pos= 0; String javaApplStub= System.getProperty("sun.boot.library.path"); //$NON-NLS-1$ if (javaApplStub != null) pos= javaApplStub.indexOf(':'); if (pos > 0) javaApplStub= javaApplStub.substring(0, pos); String expected= "/Contents/Resources/Java"; //$NON-NLS-1$ if (javaApplStub.endsWith(expected)) { javaApplStub= javaApplStub.substring(0, javaApplStub.length()-expected.length()); javaApplStub+= "/Contents/MacOS/"; //$NON-NLS-1$ } else { javaApplStub= System.getProperty("java.class.path"); //$NON-NLS-1$ if (javaApplStub != null) pos= javaApplStub.indexOf(expected); else pos= 0; if (pos > 0) { javaApplStub= javaApplStub.substring(0, pos); javaApplStub+= "/Contents/MacOS/"; //$NON-NLS-1$ } else { // fall back javaApplStub= "/System/Library/Frameworks/JavaVM.framework/Versions/A/Resources/MacOS/"; //$NON-NLS-1$ } } javaApplStub= "JAVASTUB=\""+ javaApplStub + "\"\n"; //$NON-NLS-1$ //$NON-NLS-2$ String output= "/tmp/start_carbon.sh"; //$NON-NLS-1$ FileOutputStream os= null; try { os= new FileOutputStream(output); } catch (FileNotFoundException ex) { return null; } InputStream is= null; try { os.write("#!/bin/sh\n".getBytes()); //$NON-NLS-1$ os.write(javaApplStub.getBytes()); is= where.getResourceAsStream(filename); if (is != null) { while (true) { int c= is.read(); if (c == -1) break; os.write(c); } } os.flush(); } catch (IOException io) { return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } try { os.close(); } catch(IOException e) { } } return output; }
diff --git a/androidsource/src/ca/ilanguage/bilingualaphasiatest/activity/BilingualAphasiaTestHome.java b/androidsource/src/ca/ilanguage/bilingualaphasiatest/activity/BilingualAphasiaTestHome.java index d7ce035..f0338c1 100644 --- a/androidsource/src/ca/ilanguage/bilingualaphasiatest/activity/BilingualAphasiaTestHome.java +++ b/androidsource/src/ca/ilanguage/bilingualaphasiatest/activity/BilingualAphasiaTestHome.java @@ -1,268 +1,268 @@ package ca.ilanguage.bilingualaphasiatest.activity; import java.util.Locale; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import ca.ilanguage.oprime.R; import ca.ilanguage.oprime.content.ExperimentJavaScriptInterface; import ca.ilanguage.oprime.content.OPrime; import ca.ilanguage.oprime.content.OPrimeApp; import ca.ilanguage.bilingualaphasiatest.content.BilingualAphasiaTest; import ca.ilanguage.oprime.activity.HTML5GameActivity; import ca.ilanguage.oprime.content.SubExperimentBlock; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.widget.Toast; public class BilingualAphasiaTestHome extends HTML5GameActivity { protected BilingualAphasiaTest BATapp; protected String mOutputDir = BilingualAphasiaTest.DEFAULT_OUTPUT_DIRECTORY; GoogleAnalyticsTracker tracker; @Override public void onCreate(Bundle savedInstanceState) { this.app = (BilingualAphasiaTest) getApplication(); this.BATapp = (BilingualAphasiaTest) getApplication(); ((BilingualAphasiaTest) getApplication()).setOutputDir(mOutputDir); ((OPrimeApp) getApplication()).setOutputDir(mOutputDir); super.onCreate(savedInstanceState); } @Override protected void setUpVariables() { TAG = BilingualAphasiaTest.getTag(); D = BilingualAphasiaTest.isD(); mOutputDir = BilingualAphasiaTest.DEFAULT_OUTPUT_DIRECTORY; mInitialAppServerUrl = "file:///android_asset/bilingual_aphasia_test_home.html"; mJavaScriptInterface = new ExperimentJavaScriptInterface(D, TAG, mOutputDir, getApplicationContext(), this, ""); mJavaScriptInterface.setContext(this); this.BATapp = (BilingualAphasiaTest) getApplication(); tracker = GoogleAnalyticsTracker.getInstance(); // Start the tracker in 20 sec interval dispatch mode... tracker.start("UA-30895446-1", 20, this); } @Override protected void checkIfNeedToPrepareExperiment( boolean activtySaysToPrepareExperiment) { boolean prepareExperiment = getIntent().getExtras().getBoolean( OPrime.EXTRA_PLEASE_PREPARE_EXPERIMENT, false); if (prepareExperiment || activtySaysToPrepareExperiment) { if (D) { Log.d(TAG, "BilingualAphasiaTestHome was asked to prepare the experiment."); } SharedPreferences prefs = getSharedPreferences(OPrimeApp.PREFERENCE_NAME, MODE_PRIVATE); String lang = prefs.getString(OPrimeApp.PREFERENCE_EXPERIMENT_LANGUAGE, ""); boolean autoAdvanceStimuliOnTouch = prefs.getBoolean( OPrimeApp.PREFERENCE_EXPERIMENT_AUTO_ADVANCE_ON_TOUCH, false); // ((OPrimeApp) this.getApplication()) // .setAutoAdvanceStimuliOnTouch(autoAdvanceStimuliOnTouch); if (BATapp.getLanguage().getLanguage().equals(lang) && BATapp.getExperiment() != null) { // do nothing if they didn't change the language if (D) { Log.d(TAG, "The Language has not changed, not preparing the experiment for " + lang); } } else { if (lang == null) { lang = BATapp.getLanguage().getLanguage(); if (D) { Log.d(TAG, "The Language was null, setting it to the tablets default language " + lang); } } if (D) { Log.d(TAG, "Preparing the experiment for " + lang); } /* * Let the user know if the language is not there. */ - String availibleLanguages = "en,el,es,es-rES,fr,iu,iw,kn,ru"; + String availibleLanguages = "en,el,es,es-ES,fr,iu,iw,kn,ru"; if (availibleLanguages.contains(lang)) { // do nothing, this language is supported } else { Locale templocale = new Locale(lang); new AlertDialog.Builder(this) .setTitle( templocale.getDisplayLanguage(new Locale(lang)) + " stimuli are not currently in this App") .setMessage( " We have only put ~8 BAT languages in the app (English, French, Spanish, Inuktitut, Hebrew, Russian, Kannada, Greek). Please contact us to request " + templocale.getDisplayLanguage(new Locale(lang)) + " if you need it. Click OK to contact us. \n\nClick Cancel to choose another language.") .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { /* * Open a browser to the contact us page. */ Intent browserIntent = new Intent( Intent.ACTION_VIEW, Uri.parse("https://docs.google.com/spreadsheet/viewform?formkey=dGpiRDhreGpmTFBmQ2FUTVVjVlhESHc6MQ")); startActivity(browserIntent); return; } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent i = new Intent(getBaseContext(), BATParticipantActivity.class); i.putExtra(OPrime.EXTRA_PLEASE_PREPARE_EXPERIMENT, true); startActivity(i); dialog.cancel(); } }).setCancelable(true).create().show(); // dont create experiment until user decides what to do return; } Locale templocale = new Locale(lang); final String finallang = lang; final boolean finalautoAdvanceStimuliOnTouch = autoAdvanceStimuliOnTouch; new AlertDialog.Builder(this) .setTitle( "Load " + templocale.getDisplayLanguage(new Locale(finallang)) + "?") .setMessage( "Do you want to load the " + templocale.getDisplayLanguage(new Locale(finallang)) + " stimuli - auto-advance: " + finalautoAdvanceStimuliOnTouch + " \n\n(Your previous sub experiments have all been saved to the SDCard, you may switch between languages at any time.)") .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { BATapp.createNewExperiment(finallang, finalautoAdvanceStimuliOnTouch); initExperiment(); return; } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).setCancelable(true).create().show(); } } } @Override protected void getParticipantDetails(OPrimeApp app) { super.getParticipantDetails(this.BATapp); } @Override protected void initExperiment() { getParticipantDetails(this.BATapp); mWebView.loadUrl("file:///android_asset/bilingual_aphasia_test_home.html"); } @Override protected void onDestroy() { try { tracker.trackEvent(BATapp.getExperiment().getParticipant().getCode(), // Category "Exit", // Action "Exit : " + System.currentTimeMillis() + " : ", // Label (int) System.currentTimeMillis()); // Value tracker.stop();// Stop the tracker when it is no longer needed. } catch (Exception e) { Log.e( TAG, "There was an error trying to get participant codes from the experiment. " + "Perhaps the experiemnt never began. this error was first seen on " + "Android market June 23 2012 8:27 am."); } super.onDestroy(); } @Override protected void trackCompletedExperiment(SubExperimentBlock completedExp) { tracker.trackEvent( BATapp.getExperiment().getParticipant().getCode(), // Category "SubExperiment", // Action completedExp.getTitle() + " in " + (new Locale(completedExp.getLanguage())).getDisplayLanguage() + " --- " + completedExp.getDisplayedStimuli() + "/" + completedExp.getStimuli().size() + " Completed " + System.currentTimeMillis() + " : ", // Label (int) System.currentTimeMillis()); // Value } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.open_settings) { Intent i = new Intent(getBaseContext(), BATParticipantActivity.class); i.putExtra(OPrime.EXTRA_PLEASE_PREPARE_EXPERIMENT, true); startActivityForResult(i, OPrime.SWITCH_LANGUAGE); return true; } else if (item.getItemId() == R.id.language_settings) { Intent inte = new Intent(getBaseContext(), BATParticipantActivity.class); inte.putExtra(OPrime.EXTRA_PLEASE_PREPARE_EXPERIMENT, true); startActivityForResult(inte, OPrime.SWITCH_LANGUAGE); return true; } else if (item.getItemId() == R.id.result_folder) { final boolean fileManagerAvailable = isIntentAvailable(this, "org.openintents.action.PICK_FILE"); if (!fileManagerAvailable) { Toast .makeText( getApplicationContext(), "To open and export recorded files or " + "draft data you can install the OI File Manager, " + "it allows you to browse your SDCARD directly on your mobile device." + " There are other apps which allow you to view the files, but OI is the one this app uses when you click on this button", Toast.LENGTH_LONG).show(); Intent goToMarket = new Intent(Intent.ACTION_VIEW).setData(Uri .parse("market://details?id=org.openintents.filemanager")); startActivity(goToMarket); } else { Intent openResults = new Intent("org.openintents.action.PICK_FILE"); openResults.setData(Uri.parse("file://" + mOutputDir)); startActivity(openResults); } // Intent intentReplay = new Intent(getBaseContext(), // ParticipantDetails.class); // startActivityForResult(intentReplay, OPrime.REPLAY_RESULTS); return true; } else if (item.getItemId() == R.id.issue_tracker) { Intent browserIntent = new Intent( Intent.ACTION_VIEW, Uri.parse("https://docs.google.com/spreadsheet/viewform?formkey=dGpiRDhreGpmTFBmQ2FUTVVjVlhESHc6MQ")); startActivity(browserIntent); return true; } return super.onOptionsItemSelected(item); } @Override public BilingualAphasiaTest getApp() { return BATapp; } public void setApp(BilingualAphasiaTest BATapp) { this.BATapp = BATapp; } }
true
true
protected void checkIfNeedToPrepareExperiment( boolean activtySaysToPrepareExperiment) { boolean prepareExperiment = getIntent().getExtras().getBoolean( OPrime.EXTRA_PLEASE_PREPARE_EXPERIMENT, false); if (prepareExperiment || activtySaysToPrepareExperiment) { if (D) { Log.d(TAG, "BilingualAphasiaTestHome was asked to prepare the experiment."); } SharedPreferences prefs = getSharedPreferences(OPrimeApp.PREFERENCE_NAME, MODE_PRIVATE); String lang = prefs.getString(OPrimeApp.PREFERENCE_EXPERIMENT_LANGUAGE, ""); boolean autoAdvanceStimuliOnTouch = prefs.getBoolean( OPrimeApp.PREFERENCE_EXPERIMENT_AUTO_ADVANCE_ON_TOUCH, false); // ((OPrimeApp) this.getApplication()) // .setAutoAdvanceStimuliOnTouch(autoAdvanceStimuliOnTouch); if (BATapp.getLanguage().getLanguage().equals(lang) && BATapp.getExperiment() != null) { // do nothing if they didn't change the language if (D) { Log.d(TAG, "The Language has not changed, not preparing the experiment for " + lang); } } else { if (lang == null) { lang = BATapp.getLanguage().getLanguage(); if (D) { Log.d(TAG, "The Language was null, setting it to the tablets default language " + lang); } } if (D) { Log.d(TAG, "Preparing the experiment for " + lang); } /* * Let the user know if the language is not there. */ String availibleLanguages = "en,el,es,es-rES,fr,iu,iw,kn,ru"; if (availibleLanguages.contains(lang)) { // do nothing, this language is supported } else { Locale templocale = new Locale(lang); new AlertDialog.Builder(this) .setTitle( templocale.getDisplayLanguage(new Locale(lang)) + " stimuli are not currently in this App") .setMessage( " We have only put ~8 BAT languages in the app (English, French, Spanish, Inuktitut, Hebrew, Russian, Kannada, Greek). Please contact us to request " + templocale.getDisplayLanguage(new Locale(lang)) + " if you need it. Click OK to contact us. \n\nClick Cancel to choose another language.") .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { /* * Open a browser to the contact us page. */ Intent browserIntent = new Intent( Intent.ACTION_VIEW, Uri.parse("https://docs.google.com/spreadsheet/viewform?formkey=dGpiRDhreGpmTFBmQ2FUTVVjVlhESHc6MQ")); startActivity(browserIntent); return; } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent i = new Intent(getBaseContext(), BATParticipantActivity.class); i.putExtra(OPrime.EXTRA_PLEASE_PREPARE_EXPERIMENT, true); startActivity(i); dialog.cancel(); } }).setCancelable(true).create().show(); // dont create experiment until user decides what to do return; } Locale templocale = new Locale(lang); final String finallang = lang; final boolean finalautoAdvanceStimuliOnTouch = autoAdvanceStimuliOnTouch; new AlertDialog.Builder(this) .setTitle( "Load " + templocale.getDisplayLanguage(new Locale(finallang)) + "?") .setMessage( "Do you want to load the " + templocale.getDisplayLanguage(new Locale(finallang)) + " stimuli - auto-advance: " + finalautoAdvanceStimuliOnTouch + " \n\n(Your previous sub experiments have all been saved to the SDCard, you may switch between languages at any time.)") .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { BATapp.createNewExperiment(finallang, finalautoAdvanceStimuliOnTouch); initExperiment(); return; } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).setCancelable(true).create().show(); } } }
protected void checkIfNeedToPrepareExperiment( boolean activtySaysToPrepareExperiment) { boolean prepareExperiment = getIntent().getExtras().getBoolean( OPrime.EXTRA_PLEASE_PREPARE_EXPERIMENT, false); if (prepareExperiment || activtySaysToPrepareExperiment) { if (D) { Log.d(TAG, "BilingualAphasiaTestHome was asked to prepare the experiment."); } SharedPreferences prefs = getSharedPreferences(OPrimeApp.PREFERENCE_NAME, MODE_PRIVATE); String lang = prefs.getString(OPrimeApp.PREFERENCE_EXPERIMENT_LANGUAGE, ""); boolean autoAdvanceStimuliOnTouch = prefs.getBoolean( OPrimeApp.PREFERENCE_EXPERIMENT_AUTO_ADVANCE_ON_TOUCH, false); // ((OPrimeApp) this.getApplication()) // .setAutoAdvanceStimuliOnTouch(autoAdvanceStimuliOnTouch); if (BATapp.getLanguage().getLanguage().equals(lang) && BATapp.getExperiment() != null) { // do nothing if they didn't change the language if (D) { Log.d(TAG, "The Language has not changed, not preparing the experiment for " + lang); } } else { if (lang == null) { lang = BATapp.getLanguage().getLanguage(); if (D) { Log.d(TAG, "The Language was null, setting it to the tablets default language " + lang); } } if (D) { Log.d(TAG, "Preparing the experiment for " + lang); } /* * Let the user know if the language is not there. */ String availibleLanguages = "en,el,es,es-ES,fr,iu,iw,kn,ru"; if (availibleLanguages.contains(lang)) { // do nothing, this language is supported } else { Locale templocale = new Locale(lang); new AlertDialog.Builder(this) .setTitle( templocale.getDisplayLanguage(new Locale(lang)) + " stimuli are not currently in this App") .setMessage( " We have only put ~8 BAT languages in the app (English, French, Spanish, Inuktitut, Hebrew, Russian, Kannada, Greek). Please contact us to request " + templocale.getDisplayLanguage(new Locale(lang)) + " if you need it. Click OK to contact us. \n\nClick Cancel to choose another language.") .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { /* * Open a browser to the contact us page. */ Intent browserIntent = new Intent( Intent.ACTION_VIEW, Uri.parse("https://docs.google.com/spreadsheet/viewform?formkey=dGpiRDhreGpmTFBmQ2FUTVVjVlhESHc6MQ")); startActivity(browserIntent); return; } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent i = new Intent(getBaseContext(), BATParticipantActivity.class); i.putExtra(OPrime.EXTRA_PLEASE_PREPARE_EXPERIMENT, true); startActivity(i); dialog.cancel(); } }).setCancelable(true).create().show(); // dont create experiment until user decides what to do return; } Locale templocale = new Locale(lang); final String finallang = lang; final boolean finalautoAdvanceStimuliOnTouch = autoAdvanceStimuliOnTouch; new AlertDialog.Builder(this) .setTitle( "Load " + templocale.getDisplayLanguage(new Locale(finallang)) + "?") .setMessage( "Do you want to load the " + templocale.getDisplayLanguage(new Locale(finallang)) + " stimuli - auto-advance: " + finalautoAdvanceStimuliOnTouch + " \n\n(Your previous sub experiments have all been saved to the SDCard, you may switch between languages at any time.)") .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { BATapp.createNewExperiment(finallang, finalautoAdvanceStimuliOnTouch); initExperiment(); return; } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).setCancelable(true).create().show(); } } }
diff --git a/core/taskbox/src/test/java/org/openengsb/core/taskbox/TaskboxServiceTest.java b/core/taskbox/src/test/java/org/openengsb/core/taskbox/TaskboxServiceTest.java index 5341113f3..194e3ec8e 100755 --- a/core/taskbox/src/test/java/org/openengsb/core/taskbox/TaskboxServiceTest.java +++ b/core/taskbox/src/test/java/org/openengsb/core/taskbox/TaskboxServiceTest.java @@ -1,93 +1,93 @@ /** * Copyright 2010 OpenEngSB Division, Vienna University of Technology * * 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.openengsb.core.taskbox; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.openengsb.core.common.persistence.PersistenceManager; import org.openengsb.core.common.persistence.PersistenceService; import org.openengsb.core.common.taskbox.TaskboxException; import org.openengsb.core.common.taskbox.model.Task; import org.openengsb.core.common.workflow.WorkflowException; import org.openengsb.core.common.workflow.WorkflowService; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; public class TaskboxServiceTest { private TaskboxServiceImpl service; private PersistenceService persistenceService; private WorkflowService workflowService; @Before public void init() throws Exception { workflowService = mock(WorkflowService.class); persistenceService = mock(PersistenceService.class); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getPersistenceForBundle(any(Bundle.class))).thenReturn(persistenceService); service = new TaskboxServiceImpl(); service.setBundleContext(mock(BundleContext.class)); service.setWorkflowService(workflowService); service.setPersistenceManager(persistenceManager); service.init(); } @SuppressWarnings("unchecked") @Test public void testStartWorkflow_ShouldStartOneWorkflow() throws TaskboxException, WorkflowException { service.startWorkflow("tasktest", "ticket", null); verify(workflowService).startFlow(Mockito.anyString(), Mockito.anyMap()); } @Test(expected = TaskboxException.class) public void testGetEmptyWorkflowMessage_ShouldThrowTaskboxException() throws TaskboxException { service.getWorkflowMessage(); } @Test public void testWorkflowMessage_ShouldSetString() throws TaskboxException { service.setWorkflowMessage("testmessage"); assertEquals("testmessage", service.getWorkflowMessage()); } @Test public void testGetOpenTasks_ShouldReturnOpenTasks() { /* result object for querys to persistence mock */ List<Task> result = new ArrayList<Task>(); result.add(new Task()); when(persistenceService.query(any(Task.class))).thenReturn(result); /* actual test */ List<Task> ret = service.getOpenTasks(); assertEquals(1, ret.size()); for (Task task : result) { - assertFalse(task.isTaskFinished()); + assertFalse(task.isFinished()); } } }
true
true
public void testGetOpenTasks_ShouldReturnOpenTasks() { /* result object for querys to persistence mock */ List<Task> result = new ArrayList<Task>(); result.add(new Task()); when(persistenceService.query(any(Task.class))).thenReturn(result); /* actual test */ List<Task> ret = service.getOpenTasks(); assertEquals(1, ret.size()); for (Task task : result) { assertFalse(task.isTaskFinished()); } }
public void testGetOpenTasks_ShouldReturnOpenTasks() { /* result object for querys to persistence mock */ List<Task> result = new ArrayList<Task>(); result.add(new Task()); when(persistenceService.query(any(Task.class))).thenReturn(result); /* actual test */ List<Task> ret = service.getOpenTasks(); assertEquals(1, ret.size()); for (Task task : result) { assertFalse(task.isFinished()); } }
diff --git a/wicket-security-swarm/src/test/java/org/apache/wicket/security/GeneralTest.java b/wicket-security-swarm/src/test/java/org/apache/wicket/security/GeneralTest.java index 8dd8fd64c..617edf71b 100644 --- a/wicket-security-swarm/src/test/java/org/apache/wicket/security/GeneralTest.java +++ b/wicket-security-swarm/src/test/java/org/apache/wicket/security/GeneralTest.java @@ -1,209 +1,211 @@ /* * 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.wicket.security; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.MalformedURLException; import junit.framework.TestCase; import org.apache.wicket.Page; import org.apache.wicket.Session; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.security.hive.HiveMind; import org.apache.wicket.security.hive.authentication.SecondaryLoginContext; import org.apache.wicket.security.hive.config.PolicyFileHiveFactory; import org.apache.wicket.security.pages.MockHomePage; import org.apache.wicket.security.pages.MockLoginPage; import org.apache.wicket.security.pages.PageA; import org.apache.wicket.security.pages.SecondaryLoginPage; import org.apache.wicket.security.pages.VerySecurePage; import org.apache.wicket.security.swarm.SwarmWebApplication; import org.apache.wicket.util.tester.FormTester; import org.apache.wicket.util.tester.WicketTester; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author marrink */ public class GeneralTest extends TestCase { private static final Logger log = LoggerFactory.getLogger(GeneralTest.class); protected WebApplication application; protected WicketTester mock; /** * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { mock = new WicketTester(application = new SwarmWebApplication() { protected Object getHiveKey() { // if we were using servlet-api 2.5 we could get the contextpath from the // servletcontext return "test"; } protected void setUpHive() { PolicyFileHiveFactory factory = new PolicyFileHiveFactory(); try { factory.addPolicyFile(getServletContext().getResource("WEB-INF/policy.hive")); factory.setAlias("TestPrincipal", "org.apache.wicket.security.hive.authorization.TestPrincipal"); factory.setAlias("myPackage","org.apache.wicket.security.pages"); } catch (MalformedURLException e) { log.error(e.getMessage(), e); } HiveMind.registerHive(getHiveKey(), factory); } public Class getHomePage() { return MockHomePage.class; } public Class getLoginPage() { return MockLoginPage.class; } }, "src/test/java/" + getClass().getPackage().getName().replace('.', '/')); } /** * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { mock.setupRequestAndResponse(); mock.getWicketSession().invalidate(); mock.processRequestCycle(); mock.destroy(); mock = null; application = null; HiveMind.unregisterHive("test"); } /** * Test multiple logins with auto redirect to the correct login page. */ public void testMultiLogin() { mock.startPage(MockHomePage.class); mock.assertRenderedPage(MockLoginPage.class); FormTester form = mock.newFormTester("form"); form.setValue("username", "test"); form.submit(); mock.assertRenderedPage(MockHomePage.class); mock.clickLink("secret", false); mock.assertRenderedPage(SecondaryLoginPage.class); form = mock.newFormTester("form"); form.setValue("username", "test"); form.submit(); mock.assertRenderedPage(VerySecurePage.class); assertTrue(((WaspSession)mock.getWicketSession()).logoff(new SecondaryLoginContext())); mock.startPage(mock.getLastRenderedPage()); mock.assertRenderedPage(application.getApplicationSettings().getAccessDeniedPage()); //accessdenied because the page is already constructed } public void testInheritance() { mock.startPage(MockHomePage.class); mock.assertRenderedPage(MockLoginPage.class); FormTester form = mock.newFormTester("form"); form.setValue("username", "test"); form.submit(); mock.assertRenderedPage(MockHomePage.class); mock.clickLink("link"); mock.assertRenderedPage(PageA.class); mock.assertInvisible("invisible"); mock.assertVisible("readonly"); assertTrue(mock.getTagByWicketId("readonly").hasAttribute("disabled")); mock.assertVisible("readonly"); } /** * Tests the serialization of the wicket session. * */ public void testSerialization() { //setup session mock.startPage(MockHomePage.class); mock.assertRenderedPage(MockLoginPage.class); FormTester form = mock.newFormTester("form"); form.setValue("username", "test"); form.submit(); mock.assertRenderedPage(MockHomePage.class); mock.clickLink("secret", false); mock.assertRenderedPage(SecondaryLoginPage.class); form = mock.newFormTester("form"); form.setValue("username", "test"); form.submit(); mock.assertRenderedPage(VerySecurePage.class); Page lastRendered=mock.getLastRenderedPage(); //prepare serialization WaspSession session=(WaspSession)mock.getWicketSession(); assertNotNull(session); assertFalse(session.isTemporary()); assertFalse(session.isSessionInvalidated()); try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(512*1024); ObjectOutputStream stream=new ObjectOutputStream(bytes); stream.writeObject(session); WaspSession session2 = (WaspSession)new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).readObject(); assertNotNull(session2); assertNotSame(session, session2); //fake restore session from disk mock.setupRequestAndResponse(); Session.set(session2); application.getSessionStore().bind(mock.getWicketRequest(), session2); mock.processRequestCycle(); } catch (IOException e) { log.error(e.getMessage(), e); fail(e.getMessage()); } catch (ClassNotFoundException e) { log.error(e.getMessage(), e); fail(e.getMessage()); } //attempt logoff WaspSession waspSession = ((WaspSession)mock.getWicketSession()); assertNotSame(session, waspSession); - //TODO simulate logincontext from different jvm by using a different classloader - assertTrue(waspSession.logoff(new SecondaryLoginContext())); + //instead of simulating a different jvm we can make sure the hashcode always stays the same + SecondaryLoginContext logoff = new SecondaryLoginContext(); + assertEquals(22889663, logoff.hashCode()); + assertTrue(waspSession.logoff(logoff)); mock.startPage(lastRendered); mock.assertRenderedPage(application.getApplicationSettings().getAccessDeniedPage()); } }
true
true
public void testSerialization() { //setup session mock.startPage(MockHomePage.class); mock.assertRenderedPage(MockLoginPage.class); FormTester form = mock.newFormTester("form"); form.setValue("username", "test"); form.submit(); mock.assertRenderedPage(MockHomePage.class); mock.clickLink("secret", false); mock.assertRenderedPage(SecondaryLoginPage.class); form = mock.newFormTester("form"); form.setValue("username", "test"); form.submit(); mock.assertRenderedPage(VerySecurePage.class); Page lastRendered=mock.getLastRenderedPage(); //prepare serialization WaspSession session=(WaspSession)mock.getWicketSession(); assertNotNull(session); assertFalse(session.isTemporary()); assertFalse(session.isSessionInvalidated()); try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(512*1024); ObjectOutputStream stream=new ObjectOutputStream(bytes); stream.writeObject(session); WaspSession session2 = (WaspSession)new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).readObject(); assertNotNull(session2); assertNotSame(session, session2); //fake restore session from disk mock.setupRequestAndResponse(); Session.set(session2); application.getSessionStore().bind(mock.getWicketRequest(), session2); mock.processRequestCycle(); } catch (IOException e) { log.error(e.getMessage(), e); fail(e.getMessage()); } catch (ClassNotFoundException e) { log.error(e.getMessage(), e); fail(e.getMessage()); } //attempt logoff WaspSession waspSession = ((WaspSession)mock.getWicketSession()); assertNotSame(session, waspSession); //TODO simulate logincontext from different jvm by using a different classloader assertTrue(waspSession.logoff(new SecondaryLoginContext())); mock.startPage(lastRendered); mock.assertRenderedPage(application.getApplicationSettings().getAccessDeniedPage()); }
public void testSerialization() { //setup session mock.startPage(MockHomePage.class); mock.assertRenderedPage(MockLoginPage.class); FormTester form = mock.newFormTester("form"); form.setValue("username", "test"); form.submit(); mock.assertRenderedPage(MockHomePage.class); mock.clickLink("secret", false); mock.assertRenderedPage(SecondaryLoginPage.class); form = mock.newFormTester("form"); form.setValue("username", "test"); form.submit(); mock.assertRenderedPage(VerySecurePage.class); Page lastRendered=mock.getLastRenderedPage(); //prepare serialization WaspSession session=(WaspSession)mock.getWicketSession(); assertNotNull(session); assertFalse(session.isTemporary()); assertFalse(session.isSessionInvalidated()); try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(512*1024); ObjectOutputStream stream=new ObjectOutputStream(bytes); stream.writeObject(session); WaspSession session2 = (WaspSession)new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).readObject(); assertNotNull(session2); assertNotSame(session, session2); //fake restore session from disk mock.setupRequestAndResponse(); Session.set(session2); application.getSessionStore().bind(mock.getWicketRequest(), session2); mock.processRequestCycle(); } catch (IOException e) { log.error(e.getMessage(), e); fail(e.getMessage()); } catch (ClassNotFoundException e) { log.error(e.getMessage(), e); fail(e.getMessage()); } //attempt logoff WaspSession waspSession = ((WaspSession)mock.getWicketSession()); assertNotSame(session, waspSession); //instead of simulating a different jvm we can make sure the hashcode always stays the same SecondaryLoginContext logoff = new SecondaryLoginContext(); assertEquals(22889663, logoff.hashCode()); assertTrue(waspSession.logoff(logoff)); mock.startPage(lastRendered); mock.assertRenderedPage(application.getApplicationSettings().getAccessDeniedPage()); }
diff --git a/managGui/src/managgui/Print.java b/managGui/src/managgui/Print.java index 49e4f6f..ea2a8da 100644 --- a/managGui/src/managgui/Print.java +++ b/managGui/src/managgui/Print.java @@ -1,172 +1,170 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package managgui; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.font.FontRenderContext; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; /** * * @author Claudio */ public class Print implements Printable { private SharedClasses.Customer c; private SharedClasses.Repair r; private SharedClasses.Device d; private SharedClasses.Details de; public Print (SharedClasses.Customer c, SharedClasses.Repair r, SharedClasses.Device d, SharedClasses.Details de) { this.c = c; this.r = r; this.d = d; this.de = de; } public static void repairPrint (int i, SharedClasses.Customer c, SharedClasses.Repair r, SharedClasses.Device d, SharedClasses.Details de) throws PrinterException { String name = "Scheda "; PrinterJob pj = PrinterJob.getPrinterJob(); pj.setJobName(name.concat(Integer.toString(i))); pj.setCopies(2); pj.printDialog(); pj.setPrintable(new Print(c, r, d, de)); pj.print(); } public int print(Graphics grap, PageFormat pageFormat, int pageIndex) throws PrinterException { if(pageIndex > 0) return NO_SUCH_PAGE; int x = (int)pageFormat.getImageableX(); int y = (int)pageFormat.getImageableY(); int width = (int)pageFormat.getImageableWidth(); int height = (int)pageFormat.getImageableHeight(); int firstX = x + (width/20); int firstY = y + (height/20); String optional = this.r.getOptional(); if(optional == null) optional = "NESSUNO"; Graphics2D grapdd = (Graphics2D) grap; Font f = new Font("Sans Serif", Font.PLAIN, 10); Font b = new Font("Sans Serif", Font.BOLD, 10); - Font p = new Font("Serif", Font.PLAIN, 10); + Font p = new Font("Serif", Font.PLAIN, 8); Font footer = new Font("Sans Serif", Font.PLAIN, 8); FontRenderContext frc = grapdd.getFontRenderContext(); Image logo = ManagGuiView.createImageIcon("images/logo100.png", "logo MR. Cooper").getImage(); - grapdd.drawImage(logo, firstX, firstY, null); + grapdd.drawImage(logo, firstX, firstY - 40, null); grapdd.drawGlyphVector(footer.createGlyphVector(frc, "MR. Cooper di Pette Davide - via Michele di Lando 22/24 Roma, 00162 - P.IVA 11549761002 - CF PTTDVD85E20H501E"), firstX, height - 20); grapdd.drawGlyphVector(footer.createGlyphVector(frc, "Tel.: 06/98933294 - Mail: [email protected]"), firstX, height - 5); // Customer info - firstY = firstY + heightLines(6); + firstY = firstY + heightLines(4); grapdd.drawGlyphVector(b.createGlyphVector(frc, "SCHEDA RIPARAZIONE #".concat(Integer.toString(this.r.getID()))), firstX, firstY); grapdd.drawGlyphVector(b.createGlyphVector(frc, "INFORMAZIONI CLIENTE"), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Cognome: ".concat(this.c.getSurname())), firstX + 20, firstY + heightLines(2)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Nome: ".concat(this.c.getName())), firstX + 20, firstY + heightLines(3)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Recapito telefonico: ".concat(this.c.getTelephone())), firstX + 20, firstY + heightLines(4)); // Device info firstY = firstY + heightLines(5); grap.drawLine(x + 100, firstY, width - 100 , firstY); grapdd.drawGlyphVector(b.createGlyphVector(frc, "INFORMAZIONI DISPOSITIVO"), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Modello: ".concat(this.d.getModel())), firstX + 20, firstY + heightLines(2)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Categoria: ".concat(deviceType(this.d.getType()))), firstX + 20, firstY + heightLines(3)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "IMEI/Serial Number: ".concat(this.d.getIdentification())), firstX + 20, firstY + heightLines(4)); // Repair details firstY = firstY + heightLines(5); grap.drawLine(x + 100, firstY, width - 100 , firstY); grapdd.drawGlyphVector(b.createGlyphVector(frc, "DETTAGLI SCHEDA"), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Data e ora ingresso: ".concat(this.r.getDateIn())), firstX + 20, firstY + heightLines(2)); printDeclared(firstX, firstY + heightLines(3), grapdd, f, frc); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Accessori consegnati: ".concat(optional)), firstX + 20, firstY + heightLines(6)); // responsability firstY = firstY + heightLines(7); grap.drawLine(x + 100, firstY, width - 100 , firstY); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "Il centro non è responsabile per eventuali accessori consegnati e non dichiarati al momento dell’accettazione. Si avvisa il cliente "), firstX, firstY + heightLines(1)); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "di realizzare delle copie di sicurezza dei dati presenti nella memoria del telefono, prima di consegnare il telefono medesimo al "), firstX, firstY + heightLines(2)); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "centro di assistenza per la riparazione, onde evitare la perdita degli stessi. Ai sensi dell’articolo 13 del D.lgs n. 196 del "), firstX, firstY + heightLines(3)); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "30 giugno 2003, si rende noto che i dati personali rilasciati dal cliente saranno oggetto di trattamento, nel rispetto della normativa"), firstX, firstY + heightLines(4)); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "sopra richiamata e degli obblighi di riservatezza. Titolare del trattamento dei dati è MR. COOPER di Pette Davide con sede in "), firstX, firstY + heightLines(5)); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "via Michele di Lando 22/24 00162 Roma (RM)."), firstX, firstY + heightLines(6)); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "FIRMA"), width - 150, firstY + heightLines(7)); + grapdd.drawGlyphVector(p.createGlyphVector(frc, "Il centro non è responsabile per eventuali accessori consegnati e non dichiarati al momento dell’accettazione. Si avvisa il cliente di realizzare delle copie "), firstX, firstY + heightLines(1)); + grapdd.drawGlyphVector(p.createGlyphVector(frc, "di sicurezza dei dati presenti nella memoria del telefono, prima di consegnare il telefono medesimo al centro di assistenza per la riparazione, onde evitare "), firstX, firstY + heightLines(2)); + grapdd.drawGlyphVector(p.createGlyphVector(frc, "la perdita degli stessi. Ai sensi dell’articolo 13 del D.lgs n. 196 del 30 giugno 2003, si rende noto che i dati personali rilasciati dal cliente saranno oggetto "), firstX, firstY + heightLines(3)); + grapdd.drawGlyphVector(p.createGlyphVector(frc, "di trattamento, nel rispetto della normativa sopra richiamata e degli obblighi di riservatezza. Titolare del trattamento dei dati è MR. COOPER di Pette Davide "), firstX, firstY + heightLines(4)); + grapdd.drawGlyphVector(p.createGlyphVector(frc, "con sede in via Michele di Lando 22/24 00162 Roma (RM)."), firstX, firstY + heightLines(5)); + grapdd.drawGlyphVector(p.createGlyphVector(frc, "FIRMA"), width - 150, firstY + heightLines(6)); grap.setColor(Color.LIGHT_GRAY); - grap.drawLine(width - 200, firstY + heightLines(8), width - 67, firstY + heightLines(8)); + grap.drawLine(width - 200, firstY + heightLines(7), width - 67, firstY + heightLines(7)); grap.setColor(Color.BLACK); // privacy - firstY = firstY + heightLines(9); + firstY = firstY + heightLines(8); grapdd.drawGlyphVector(p.createGlyphVector(frc, "ACQUISIZIONE DEL CONSENSO"), firstX, firstY); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "Dichiaro di aver acquisito le informazioni fornite dal titolare del trattamento ai sensi dell’art. 13 del D.lgs n 196/2003 e di prestare "), firstX, firstY + heightLines(1)); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "il mio consenso al trattamento dei dati personali. Presto inoltre il consenso alla comunicazione dei dati personali ai soggetti "), firstX, firstY + heightLines(2)); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "indicati nell’informativa. "), firstX, firstY + heightLines(3)); - grapdd.drawGlyphVector(p.createGlyphVector(frc, "FIRMA"), width - 150, firstY + heightLines(4)); + grapdd.drawGlyphVector(p.createGlyphVector(frc, "Dichiaro di aver acquisito le informazioni fornite dal titolare del trattamento ai sensi dell’art. 13 del D.lgs n 196/2003 e di prestare il mio consenso al "), firstX, firstY + heightLines(1)); + grapdd.drawGlyphVector(p.createGlyphVector(frc, "trattamento dei dati personali. Presto inoltre il consenso alla comunicazione dei dati personali ai soggetti indicati nell’informativa."), firstX, firstY + heightLines(2)); + grapdd.drawGlyphVector(p.createGlyphVector(frc, "FIRMA"), width - 150, firstY + heightLines(3)); grap.setColor(Color.LIGHT_GRAY); - grap.drawLine(width - 200, firstY + heightLines(5), width - 67, firstY + heightLines(5)); + grap.drawLine(width - 200, firstY + heightLines(4), width - 67, firstY + heightLines(4)); grap.setColor(Color.BLACK); return PAGE_EXISTS; } private static int heightLines (int i) { return i * 20; } private static int halfHeightLines (int i) { return i * 10; } private void printDeclared (int x, int y, Graphics2D g, Font f, FontRenderContext frc) { String s = this.de.getDeclared(); if(s.length() < 64) { g.drawGlyphVector(f.createGlyphVector(frc, "Difetto dichiarato: ".concat(s)), x + 20, y); } else if (s.length() < 140) { g.drawGlyphVector(f.createGlyphVector(frc, "Difetto dichiarato: ".concat(s.substring(0, 63))), x + 20, y); g.drawGlyphVector(f.createGlyphVector(frc, s.substring(64, s.length())), x + 20, y + heightLines(1)); } else if (s.length() < 218) { g.drawGlyphVector(f.createGlyphVector(frc, "Difetto dichiarato: ".concat(s.substring(0, 63))), x + 20, y); g.drawGlyphVector(f.createGlyphVector(frc, s.substring(64, 139)), x + 20, y + heightLines(1)); g.drawGlyphVector(f.createGlyphVector(frc, s.substring(140, s.length())), x + 20, y + heightLines(2)); } else { g.drawGlyphVector(f.createGlyphVector(frc, "Difetto dichiarato: ".concat(s.substring(0, 63))), x + 20, y); g.drawGlyphVector(f.createGlyphVector(frc, s.substring(64, 139)), x + 20, y + heightLines(1)); g.drawGlyphVector(f.createGlyphVector(frc, s.substring(140, 213).concat("...")), x + 20, y + heightLines(2)); } } private static String deviceType (int i) { switch(i) { case ComClasses.Constants.MOBILE: return "TELEFONIA"; case ComClasses.Constants.COM: return "INFORMATICA"; default: return "ALTRO"; } } }
false
true
public int print(Graphics grap, PageFormat pageFormat, int pageIndex) throws PrinterException { if(pageIndex > 0) return NO_SUCH_PAGE; int x = (int)pageFormat.getImageableX(); int y = (int)pageFormat.getImageableY(); int width = (int)pageFormat.getImageableWidth(); int height = (int)pageFormat.getImageableHeight(); int firstX = x + (width/20); int firstY = y + (height/20); String optional = this.r.getOptional(); if(optional == null) optional = "NESSUNO"; Graphics2D grapdd = (Graphics2D) grap; Font f = new Font("Sans Serif", Font.PLAIN, 10); Font b = new Font("Sans Serif", Font.BOLD, 10); Font p = new Font("Serif", Font.PLAIN, 10); Font footer = new Font("Sans Serif", Font.PLAIN, 8); FontRenderContext frc = grapdd.getFontRenderContext(); Image logo = ManagGuiView.createImageIcon("images/logo100.png", "logo MR. Cooper").getImage(); grapdd.drawImage(logo, firstX, firstY, null); grapdd.drawGlyphVector(footer.createGlyphVector(frc, "MR. Cooper di Pette Davide - via Michele di Lando 22/24 Roma, 00162 - P.IVA 11549761002 - CF PTTDVD85E20H501E"), firstX, height - 20); grapdd.drawGlyphVector(footer.createGlyphVector(frc, "Tel.: 06/98933294 - Mail: [email protected]"), firstX, height - 5); // Customer info firstY = firstY + heightLines(6); grapdd.drawGlyphVector(b.createGlyphVector(frc, "SCHEDA RIPARAZIONE #".concat(Integer.toString(this.r.getID()))), firstX, firstY); grapdd.drawGlyphVector(b.createGlyphVector(frc, "INFORMAZIONI CLIENTE"), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Cognome: ".concat(this.c.getSurname())), firstX + 20, firstY + heightLines(2)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Nome: ".concat(this.c.getName())), firstX + 20, firstY + heightLines(3)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Recapito telefonico: ".concat(this.c.getTelephone())), firstX + 20, firstY + heightLines(4)); // Device info firstY = firstY + heightLines(5); grap.drawLine(x + 100, firstY, width - 100 , firstY); grapdd.drawGlyphVector(b.createGlyphVector(frc, "INFORMAZIONI DISPOSITIVO"), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Modello: ".concat(this.d.getModel())), firstX + 20, firstY + heightLines(2)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Categoria: ".concat(deviceType(this.d.getType()))), firstX + 20, firstY + heightLines(3)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "IMEI/Serial Number: ".concat(this.d.getIdentification())), firstX + 20, firstY + heightLines(4)); // Repair details firstY = firstY + heightLines(5); grap.drawLine(x + 100, firstY, width - 100 , firstY); grapdd.drawGlyphVector(b.createGlyphVector(frc, "DETTAGLI SCHEDA"), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Data e ora ingresso: ".concat(this.r.getDateIn())), firstX + 20, firstY + heightLines(2)); printDeclared(firstX, firstY + heightLines(3), grapdd, f, frc); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Accessori consegnati: ".concat(optional)), firstX + 20, firstY + heightLines(6)); // responsability firstY = firstY + heightLines(7); grap.drawLine(x + 100, firstY, width - 100 , firstY); grapdd.drawGlyphVector(p.createGlyphVector(frc, "Il centro non è responsabile per eventuali accessori consegnati e non dichiarati al momento dell’accettazione. Si avvisa il cliente "), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "di realizzare delle copie di sicurezza dei dati presenti nella memoria del telefono, prima di consegnare il telefono medesimo al "), firstX, firstY + heightLines(2)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "centro di assistenza per la riparazione, onde evitare la perdita degli stessi. Ai sensi dell’articolo 13 del D.lgs n. 196 del "), firstX, firstY + heightLines(3)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "30 giugno 2003, si rende noto che i dati personali rilasciati dal cliente saranno oggetto di trattamento, nel rispetto della normativa"), firstX, firstY + heightLines(4)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "sopra richiamata e degli obblighi di riservatezza. Titolare del trattamento dei dati è MR. COOPER di Pette Davide con sede in "), firstX, firstY + heightLines(5)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "via Michele di Lando 22/24 00162 Roma (RM)."), firstX, firstY + heightLines(6)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "FIRMA"), width - 150, firstY + heightLines(7)); grap.setColor(Color.LIGHT_GRAY); grap.drawLine(width - 200, firstY + heightLines(8), width - 67, firstY + heightLines(8)); grap.setColor(Color.BLACK); // privacy firstY = firstY + heightLines(9); grapdd.drawGlyphVector(p.createGlyphVector(frc, "ACQUISIZIONE DEL CONSENSO"), firstX, firstY); grapdd.drawGlyphVector(p.createGlyphVector(frc, "Dichiaro di aver acquisito le informazioni fornite dal titolare del trattamento ai sensi dell’art. 13 del D.lgs n 196/2003 e di prestare "), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "il mio consenso al trattamento dei dati personali. Presto inoltre il consenso alla comunicazione dei dati personali ai soggetti "), firstX, firstY + heightLines(2)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "indicati nell’informativa. "), firstX, firstY + heightLines(3)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "FIRMA"), width - 150, firstY + heightLines(4)); grap.setColor(Color.LIGHT_GRAY); grap.drawLine(width - 200, firstY + heightLines(5), width - 67, firstY + heightLines(5)); grap.setColor(Color.BLACK); return PAGE_EXISTS; }
public int print(Graphics grap, PageFormat pageFormat, int pageIndex) throws PrinterException { if(pageIndex > 0) return NO_SUCH_PAGE; int x = (int)pageFormat.getImageableX(); int y = (int)pageFormat.getImageableY(); int width = (int)pageFormat.getImageableWidth(); int height = (int)pageFormat.getImageableHeight(); int firstX = x + (width/20); int firstY = y + (height/20); String optional = this.r.getOptional(); if(optional == null) optional = "NESSUNO"; Graphics2D grapdd = (Graphics2D) grap; Font f = new Font("Sans Serif", Font.PLAIN, 10); Font b = new Font("Sans Serif", Font.BOLD, 10); Font p = new Font("Serif", Font.PLAIN, 8); Font footer = new Font("Sans Serif", Font.PLAIN, 8); FontRenderContext frc = grapdd.getFontRenderContext(); Image logo = ManagGuiView.createImageIcon("images/logo100.png", "logo MR. Cooper").getImage(); grapdd.drawImage(logo, firstX, firstY - 40, null); grapdd.drawGlyphVector(footer.createGlyphVector(frc, "MR. Cooper di Pette Davide - via Michele di Lando 22/24 Roma, 00162 - P.IVA 11549761002 - CF PTTDVD85E20H501E"), firstX, height - 20); grapdd.drawGlyphVector(footer.createGlyphVector(frc, "Tel.: 06/98933294 - Mail: [email protected]"), firstX, height - 5); // Customer info firstY = firstY + heightLines(4); grapdd.drawGlyphVector(b.createGlyphVector(frc, "SCHEDA RIPARAZIONE #".concat(Integer.toString(this.r.getID()))), firstX, firstY); grapdd.drawGlyphVector(b.createGlyphVector(frc, "INFORMAZIONI CLIENTE"), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Cognome: ".concat(this.c.getSurname())), firstX + 20, firstY + heightLines(2)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Nome: ".concat(this.c.getName())), firstX + 20, firstY + heightLines(3)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Recapito telefonico: ".concat(this.c.getTelephone())), firstX + 20, firstY + heightLines(4)); // Device info firstY = firstY + heightLines(5); grap.drawLine(x + 100, firstY, width - 100 , firstY); grapdd.drawGlyphVector(b.createGlyphVector(frc, "INFORMAZIONI DISPOSITIVO"), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Modello: ".concat(this.d.getModel())), firstX + 20, firstY + heightLines(2)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Categoria: ".concat(deviceType(this.d.getType()))), firstX + 20, firstY + heightLines(3)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "IMEI/Serial Number: ".concat(this.d.getIdentification())), firstX + 20, firstY + heightLines(4)); // Repair details firstY = firstY + heightLines(5); grap.drawLine(x + 100, firstY, width - 100 , firstY); grapdd.drawGlyphVector(b.createGlyphVector(frc, "DETTAGLI SCHEDA"), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Data e ora ingresso: ".concat(this.r.getDateIn())), firstX + 20, firstY + heightLines(2)); printDeclared(firstX, firstY + heightLines(3), grapdd, f, frc); grapdd.drawGlyphVector(f.createGlyphVector(frc, "Accessori consegnati: ".concat(optional)), firstX + 20, firstY + heightLines(6)); // responsability firstY = firstY + heightLines(7); grap.drawLine(x + 100, firstY, width - 100 , firstY); grapdd.drawGlyphVector(p.createGlyphVector(frc, "Il centro non è responsabile per eventuali accessori consegnati e non dichiarati al momento dell’accettazione. Si avvisa il cliente di realizzare delle copie "), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "di sicurezza dei dati presenti nella memoria del telefono, prima di consegnare il telefono medesimo al centro di assistenza per la riparazione, onde evitare "), firstX, firstY + heightLines(2)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "la perdita degli stessi. Ai sensi dell’articolo 13 del D.lgs n. 196 del 30 giugno 2003, si rende noto che i dati personali rilasciati dal cliente saranno oggetto "), firstX, firstY + heightLines(3)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "di trattamento, nel rispetto della normativa sopra richiamata e degli obblighi di riservatezza. Titolare del trattamento dei dati è MR. COOPER di Pette Davide "), firstX, firstY + heightLines(4)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "con sede in via Michele di Lando 22/24 00162 Roma (RM)."), firstX, firstY + heightLines(5)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "FIRMA"), width - 150, firstY + heightLines(6)); grap.setColor(Color.LIGHT_GRAY); grap.drawLine(width - 200, firstY + heightLines(7), width - 67, firstY + heightLines(7)); grap.setColor(Color.BLACK); // privacy firstY = firstY + heightLines(8); grapdd.drawGlyphVector(p.createGlyphVector(frc, "ACQUISIZIONE DEL CONSENSO"), firstX, firstY); grapdd.drawGlyphVector(p.createGlyphVector(frc, "Dichiaro di aver acquisito le informazioni fornite dal titolare del trattamento ai sensi dell’art. 13 del D.lgs n 196/2003 e di prestare il mio consenso al "), firstX, firstY + heightLines(1)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "trattamento dei dati personali. Presto inoltre il consenso alla comunicazione dei dati personali ai soggetti indicati nell’informativa."), firstX, firstY + heightLines(2)); grapdd.drawGlyphVector(p.createGlyphVector(frc, "FIRMA"), width - 150, firstY + heightLines(3)); grap.setColor(Color.LIGHT_GRAY); grap.drawLine(width - 200, firstY + heightLines(4), width - 67, firstY + heightLines(4)); grap.setColor(Color.BLACK); return PAGE_EXISTS; }
diff --git a/edu/cmu/sphinx/frontend/DataProcessor.java b/edu/cmu/sphinx/frontend/DataProcessor.java index e390d99d..9f6decc6 100644 --- a/edu/cmu/sphinx/frontend/DataProcessor.java +++ b/edu/cmu/sphinx/frontend/DataProcessor.java @@ -1,228 +1,230 @@ /* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.frontend; import edu.cmu.sphinx.util.SphinxProperties; import edu.cmu.sphinx.util.Timer; import java.io.IOException; /** * DataProcessor contains the common elements of all frontend data * processors, namely the name, context, timers, SphinxProperties, * and dumping. It also contains the acoustic properties object from * which acoustic model properties can be queried. */ public abstract class DataProcessor { /** * The name of this DataProcessor. */ private String name; /** * The context of this DataProcessor. */ private String context; /** * A Timer for timing processing. */ private Timer timer; /** * Indicates whether to dump the processed Data */ private boolean dump = false; /** * The SphinxProperties used by this DataProcessor */ private SphinxProperties sphinxProperties; // true if processing Data objects within an Utterance private boolean inUtterance; /** * Constructs a default DataProcessor */ public DataProcessor() {} /** * Constructs a DataProcessor with the given name and context. * * @param name the name of this DataProcessor * @param context the context of this DataProcessor */ public DataProcessor(String name, String context) { initialize(name, context, null); } /** * Constructs a DataProcessor of the given name and at the given context. * * @param name the name of this DataProcessor * @param context the context of this DataProcessor * @param sphinxProperties the sphinx properties used */ public DataProcessor(String name, String context, SphinxProperties sphinxProperties) { initialize(name, context, sphinxProperties); } /** * Initializes this DataProcessor. * * @param name the name of this DataProcessor * @param context the context of this DataProcessor * @param sphinxProperties the SphinxProperties to use */ public void initialize(String name, String context, SphinxProperties sphinxProperties) { this.name = name; this.context = context; this.sphinxProperties = sphinxProperties; this.timer = Timer.getTimer(context, name); } /** * Returns the name of this DataProcessor. * * @return the name of this DataProcessor */ public final String getName() { return name; } /** * Returns the context of this DataProcessor. * * @return the context of this DataProcessor */ public final String getContext() { return context; } /** * Returns the SphinxProperties used by this DataProcessor. * * @return the SphinxProperties */ public final SphinxProperties getSphinxProperties() { if (sphinxProperties != null) { return sphinxProperties; } else { return SphinxProperties.getSphinxProperties(getContext()); } } /** * Sets the SphinxProperties to use. * * @param sphinxProperties the SphinxProperties to use */ public void setSphinxProperties(SphinxProperties sphinxProperties) { this.sphinxProperties = sphinxProperties; } /** * Returns the Timer for metrics collection purposes. * * @return the Timer */ public final Timer getTimer() { return timer; } /** * Determine whether to dump the output for debug purposes. * * @return true to dump, false to not dump */ public final boolean getDump() { return this.dump; } /** * Set whether we should dump the output for debug purposes. * * @param dump true to dump the output; false otherwise */ public void setDump(boolean dump) { this.dump = dump; } /** * Returns the name of this DataProcessor. * * @return the name of this DataProcessor */ public String toString() { return name; } /** * Does sanity check on whether the Signals UTTERANCE_START and * UTTERANCE_END are in sequence. Throws an Error if: * <ol> * <li> We have not received an UTTERANCE_START Signal before * receiving an Signal/Data. * <li> We received an UTTERANCE_START after an UTTERANCE_START * without an intervening UTTERANCE_END; * </ol> * * @throws Error if the UTTERANCE_START and UTTERANCE_END signals * are not in sequence */ protected void signalCheck(Data data) { if (!inUtterance) { if (data != null) { if (data.hasSignal(Signal.UTTERANCE_START)) { inUtterance = true; + } else if (data.hasSignal(Signal.UTTERANCE_END)) { + throw new Error(getName() + ": too many UTTERANCE_END."); } else { throw new Error(getName() + ": no UTTERANCE_START"); } } } else { if (data == null) { throw new Error (getName() + ": unexpected return of null Data"); } else if (data.hasSignal(Signal.UTTERANCE_END)) { inUtterance = false; } else if (data.hasSignal(Signal.UTTERANCE_START)) { throw new Error(getName() + ": too many UTTERANCE_START"); } } } }
true
true
protected void signalCheck(Data data) { if (!inUtterance) { if (data != null) { if (data.hasSignal(Signal.UTTERANCE_START)) { inUtterance = true; } else { throw new Error(getName() + ": no UTTERANCE_START"); } } } else { if (data == null) { throw new Error (getName() + ": unexpected return of null Data"); } else if (data.hasSignal(Signal.UTTERANCE_END)) { inUtterance = false; } else if (data.hasSignal(Signal.UTTERANCE_START)) { throw new Error(getName() + ": too many UTTERANCE_START"); } } }
protected void signalCheck(Data data) { if (!inUtterance) { if (data != null) { if (data.hasSignal(Signal.UTTERANCE_START)) { inUtterance = true; } else if (data.hasSignal(Signal.UTTERANCE_END)) { throw new Error(getName() + ": too many UTTERANCE_END."); } else { throw new Error(getName() + ": no UTTERANCE_START"); } } } else { if (data == null) { throw new Error (getName() + ": unexpected return of null Data"); } else if (data.hasSignal(Signal.UTTERANCE_END)) { inUtterance = false; } else if (data.hasSignal(Signal.UTTERANCE_START)) { throw new Error(getName() + ": too many UTTERANCE_START"); } } }
diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliDecoder.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliDecoder.java index 134fb88..98ed63e 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliDecoder.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliDecoder.java @@ -1,62 +1,62 @@ /** * Copyright 2011 Ryszard Wiśniewski <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.src; import brut.androlib.AndrolibException; import java.io.File; import java.io.IOException; import org.jf.baksmali.baksmali; import org.jf.baksmali.main; import org.jf.dexlib.Code.Analysis.ClassPath; import org.jf.dexlib.DexFile; /** * @author Ryszard Wiśniewski <[email protected]> */ public class SmaliDecoder { public static void decode(File apkFile, File outDir, boolean debug, boolean bakdeb) throws AndrolibException { new SmaliDecoder(apkFile, outDir, debug, bakdeb).decode(); } private SmaliDecoder(File apkFile, File outDir, boolean debug, boolean bakdeb) { mApkFile = apkFile; mOutDir = outDir; mDebug = debug; mBakDeb = bakdeb; } private void decode() throws AndrolibException { if (mDebug) { ClassPath.dontLoadClassPath = true; } try { baksmali.disassembleDexFile(mApkFile.getAbsolutePath(), new DexFile(mApkFile), false, mOutDir.getAbsolutePath(), null, null, null, false, true, true, mBakDeb, false, false, - mDebug ? main.DIFFPRE: 0, false, false, null); + mDebug ? main.DIFFPRE: 0, false, false, null, false); } catch (IOException ex) { throw new AndrolibException(ex); } } private final File mApkFile; private final File mOutDir; private final boolean mDebug; private final boolean mBakDeb; }
true
true
private void decode() throws AndrolibException { if (mDebug) { ClassPath.dontLoadClassPath = true; } try { baksmali.disassembleDexFile(mApkFile.getAbsolutePath(), new DexFile(mApkFile), false, mOutDir.getAbsolutePath(), null, null, null, false, true, true, mBakDeb, false, false, mDebug ? main.DIFFPRE: 0, false, false, null); } catch (IOException ex) { throw new AndrolibException(ex); } }
private void decode() throws AndrolibException { if (mDebug) { ClassPath.dontLoadClassPath = true; } try { baksmali.disassembleDexFile(mApkFile.getAbsolutePath(), new DexFile(mApkFile), false, mOutDir.getAbsolutePath(), null, null, null, false, true, true, mBakDeb, false, false, mDebug ? main.DIFFPRE: 0, false, false, null, false); } catch (IOException ex) { throw new AndrolibException(ex); } }
diff --git a/samples/jaxp/TypeInfoWriter.java b/samples/jaxp/TypeInfoWriter.java index 51507ebc..a49a147c 100644 --- a/samples/jaxp/TypeInfoWriter.java +++ b/samples/jaxp/TypeInfoWriter.java @@ -1,606 +1,607 @@ /* * Copyright 2005 The Apache Software Foundation. * * 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 jaxp; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Vector; import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.TypeInfoProvider; import javax.xml.validation.ValidatorHandler; import org.w3c.dom.TypeInfo; import org.xml.sax.Attributes; import org.xml.sax.DTDHandler; import org.xml.sax.Locator; import org.xml.sax.Parser; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.ParserAdapter; import org.xml.sax.helpers.ParserFactory; import org.xml.sax.helpers.XMLReaderFactory; /** * <p>Provides a trace of the schema type information for elements and * attributes in an XML document. This demonstrates usage of the * JAXP 1.3 Validation API, particuarly how to read type information * from a TypeInfoProvider.</p> * * @author Michael Glavassevich, IBM * * @version $Id$ */ public class TypeInfoWriter extends DefaultHandler { // // Constants // // feature ids /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */ protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking"; /** Honour all schema locations feature id (http://apache.org/xml/features/honour-all-schemaLocations). */ protected static final String HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations"; /** Validate schema annotations feature id (http://apache.org/xml/features/validate-annotations) */ protected static final String VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations"; /** Generate synthetic schema annotations feature id (http://apache.org/xml/features/generate-synthetic-annotations). */ protected static final String GENERATE_SYNTHETIC_ANNOTATIONS_ID = "http://apache.org/xml/features/generate-synthetic-annotations"; // default settings /** Default parser name. */ protected static final String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser"; /** Default schema full checking support (false). */ protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false; /** Default honour all schema locations (false). */ protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false; /** Default validate schema annotations (false). */ protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false; /** Default generate synthetic schema annotations (false). */ protected static final boolean DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS = false; // // Data // /** TypeInfo provider. */ protected TypeInfoProvider fTypeInfoProvider; /** Print writer. */ protected PrintWriter fOut; /** Indent level. */ protected int fIndent; // // Constructors // /** Default constructor. */ public TypeInfoWriter() {} // // ContentHandler and DocumentHandler methods // /** Set document locator. */ public void setDocumentLocator(Locator locator) { fIndent = 0; printIndent(); fOut.print("setDocumentLocator("); fOut.print("systemId="); printQuotedString(locator.getSystemId()); fOut.print(", publicId="); printQuotedString(locator.getPublicId()); fOut.println(')'); fOut.flush(); } // setDocumentLocator(Locator) /** Start document. */ public void startDocument() throws SAXException { fIndent = 0; printIndent(); fOut.println("startDocument()"); fOut.flush(); fIndent++; } // startDocument() /** Start element. */ public void startElement(String uri, String localName, String qname, Attributes attributes) throws SAXException { TypeInfo type; printIndent(); fOut.print("startElement("); fOut.print("name="); printQName(uri, localName); fOut.print(','); fOut.print("type="); if (fTypeInfoProvider != null && (type = fTypeInfoProvider.getElementTypeInfo()) != null) { printQName(type.getTypeNamespace(), type.getTypeName()); } else { fOut.print("null"); } fOut.print(','); fOut.print("attributes="); if (attributes == null) { fOut.println("null"); } else { fOut.print('{'); int length = attributes.getLength(); for (int i = 0; i < length; i++) { if (i > 0) { fOut.print(','); } String attrURI = attributes.getURI(i); String attrLocalName = attributes.getLocalName(i); fOut.print('{'); fOut.print("name="); printQName(attrURI, attrLocalName); fOut.print(','); fOut.print("type="); if (fTypeInfoProvider != null && (type = fTypeInfoProvider.getAttributeTypeInfo(i)) != null) { printQName(type.getTypeNamespace(), type.getTypeName()); } else { fOut.print("null"); } fOut.print(','); fOut.print("id="); fOut.print(fTypeInfoProvider != null && fTypeInfoProvider.isIdAttribute(i) ? "\"true\"" : "\"false\""); fOut.print(','); fOut.print("specified="); fOut.print(fTypeInfoProvider == null || fTypeInfoProvider.isSpecified(i) ? "\"true\"" : "\"false\""); fOut.print('}'); } fOut.print('}'); } fOut.println(')'); fOut.flush(); fIndent++; } // startElement(String,String,String,Attributes) /** End element. */ public void endElement(String uri, String localName, String qname) throws SAXException { fIndent--; printIndent(); fOut.print("endElement("); fOut.print("name="); printQName(uri, localName); fOut.println(')'); fOut.flush(); } // endElement(String,String,String) /** End document. */ public void endDocument() throws SAXException { fIndent--; printIndent(); fOut.println("endDocument()"); fOut.flush(); } // endDocument() // // ErrorHandler methods // /** Warning. */ public void warning(SAXParseException ex) throws SAXException { printError("Warning", ex); } // warning(SAXParseException) /** Error. */ public void error(SAXParseException ex) throws SAXException { printError("Error", ex); } // error(SAXParseException) /** Fatal error. */ public void fatalError(SAXParseException ex) throws SAXException { printError("Fatal Error", ex); throw ex; } // fatalError(SAXParseException) // // Public methods // /** Sets the output stream for printing. */ public void setOutput(OutputStream stream, String encoding) throws UnsupportedEncodingException { if (encoding == null) { encoding = "UTF8"; } java.io.Writer writer = new OutputStreamWriter(stream, encoding); fOut = new PrintWriter(writer); } // setOutput(OutputStream,String) // // Protected methods // /** Sets the TypeInfoProvider used by this writer. */ protected void setTypeInfoProvider(TypeInfoProvider provider) { fTypeInfoProvider = provider; } /** Prints the error message. */ protected void printError(String type, SAXParseException ex) { System.err.print("["); System.err.print(type); System.err.print("] "); String systemId = ex.getSystemId(); if (systemId != null) { int index = systemId.lastIndexOf('/'); if (index != -1) systemId = systemId.substring(index + 1); System.err.print(systemId); } System.err.print(':'); System.err.print(ex.getLineNumber()); System.err.print(':'); System.err.print(ex.getColumnNumber()); System.err.print(": "); System.err.print(ex.getMessage()); System.err.println(); System.err.flush(); } // printError(String,SAXParseException) /** Prints the indent. */ protected void printIndent() { for (int i = 0; i < fIndent; i++) { fOut.print(' '); } } // printIndent() protected void printQName(String uri, String localName) { if (uri != null && uri.length() > 0) { printQuotedString('{' + uri + "}" + localName); return; } printQuotedString(localName); } /** Print quoted string. */ protected void printQuotedString(String s) { if (s == null) { fOut.print("null"); return; } fOut.print('"'); fOut.print(s); fOut.print('"'); } // printQuotedString(String) // // MAIN // /** Main program entry point. */ public static void main (String [] argv) { // is there anything to do? if (argv.length == 0) { printUsage(); System.exit(1); } // variables XMLReader parser = null; Vector schemas = null; Vector instances = null; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; // process arguments for (int i = 0; i < argv.length; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); + continue; } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser ("+parserName+")"); e.printStackTrace(System.err); System.exit(1); } } continue; } if (arg.equals("-a")) { // process -a: schema documents if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option ("+option+")."); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")"); e.printStackTrace(System.err); System.exit(1); } } try { // Create writer TypeInfoWriter writer = new TypeInfoWriter(); writer.setOutput(System.out, "UTF8"); // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setErrorHandler(writer); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Build Schema from sources Schema schema; if (schemas != null && schemas.size() > 0) { final int length = schemas.size(); StreamSource[] sources = new StreamSource[length]; for (int j = 0; j < length; ++j) { sources[j] = new StreamSource((String) schemas.elementAt(j)); } schema = factory.newSchema(sources); } else { schema = factory.newSchema(); } // Setup validator and parser ValidatorHandler validator = schema.newValidatorHandler(); parser.setContentHandler(validator); if (validator instanceof DTDHandler) { parser.setDTDHandler((DTDHandler) validator); } parser.setErrorHandler(writer); validator.setContentHandler(writer); validator.setErrorHandler(writer); writer.setTypeInfoProvider(validator.getTypeInfoProvider()); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Validate instance documents and print type information if (instances != null && instances.size() > 0) { final int length = instances.size(); for (int j = 0; j < length; ++j) { parser.parse((String) instances.elementAt(j)); } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - "+e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException)e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } // main(String[]) // // Private static methods // /** Prints the usage. */ private static void printUsage() { System.err.println("usage: java jaxp.TypeInfoWriter (options) ..."); System.err.println(); System.err.println("options:"); System.err.println(" -a uri ... Provide a list of schema documents"); System.err.println(" -i uri ... Provide a list of instance documents to validate"); System.err.println(" -p name Select parser by name."); System.err.println(" -f | -F Turn on/off Schema full checking."); System.err.println(" NOTE: Not supported by all schema factories and validators."); System.err.println(" -hs | -HS Turn on/off honouring of all schema locations."); System.err.println(" NOTE: Not supported by all schema factories and validators."); System.err.println(" -va | -VA Turn on/off validation of schema annotations."); System.err.println(" NOTE: Not supported by all schema factories and validators."); System.err.println(" -ga | -GA Turn on/off generation of synthetic schema annotations."); System.err.println(" NOTE: Not supported by all schema factories and validators."); System.err.println(" -h This help screen."); System.err.println(); System.err.println("defaults:"); System.err.println(" Parser: "+DEFAULT_PARSER_NAME); System.err.print(" Schema full checking: "); System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off"); System.err.print(" Honour all schema locations: "); System.err.println(DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off"); System.err.print(" Validate annotations: "); System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off"); System.err.print(" Generate synthetic annotations: "); System.err.println(DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS ? "on" : "off"); } // printUsage() } // class TypeInfoWriter
true
true
public static void main (String [] argv) { // is there anything to do? if (argv.length == 0) { printUsage(); System.exit(1); } // variables XMLReader parser = null; Vector schemas = null; Vector instances = null; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; // process arguments for (int i = 0; i < argv.length; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser ("+parserName+")"); e.printStackTrace(System.err); System.exit(1); } } continue; } if (arg.equals("-a")) { // process -a: schema documents if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option ("+option+")."); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")"); e.printStackTrace(System.err); System.exit(1); } } try { // Create writer TypeInfoWriter writer = new TypeInfoWriter(); writer.setOutput(System.out, "UTF8"); // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setErrorHandler(writer); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Build Schema from sources Schema schema; if (schemas != null && schemas.size() > 0) { final int length = schemas.size(); StreamSource[] sources = new StreamSource[length]; for (int j = 0; j < length; ++j) { sources[j] = new StreamSource((String) schemas.elementAt(j)); } schema = factory.newSchema(sources); } else { schema = factory.newSchema(); } // Setup validator and parser ValidatorHandler validator = schema.newValidatorHandler(); parser.setContentHandler(validator); if (validator instanceof DTDHandler) { parser.setDTDHandler((DTDHandler) validator); } parser.setErrorHandler(writer); validator.setContentHandler(writer); validator.setErrorHandler(writer); writer.setTypeInfoProvider(validator.getTypeInfoProvider()); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Validate instance documents and print type information if (instances != null && instances.size() > 0) { final int length = instances.size(); for (int j = 0; j < length; ++j) { parser.parse((String) instances.elementAt(j)); } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - "+e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException)e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } // main(String[])
public static void main (String [] argv) { // is there anything to do? if (argv.length == 0) { printUsage(); System.exit(1); } // variables XMLReader parser = null; Vector schemas = null; Vector instances = null; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; // process arguments for (int i = 0; i < argv.length; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); continue; } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser ("+parserName+")"); e.printStackTrace(System.err); System.exit(1); } } continue; } if (arg.equals("-a")) { // process -a: schema documents if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option ("+option+")."); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")"); e.printStackTrace(System.err); System.exit(1); } } try { // Create writer TypeInfoWriter writer = new TypeInfoWriter(); writer.setOutput(System.out, "UTF8"); // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setErrorHandler(writer); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Build Schema from sources Schema schema; if (schemas != null && schemas.size() > 0) { final int length = schemas.size(); StreamSource[] sources = new StreamSource[length]; for (int j = 0; j < length; ++j) { sources[j] = new StreamSource((String) schemas.elementAt(j)); } schema = factory.newSchema(sources); } else { schema = factory.newSchema(); } // Setup validator and parser ValidatorHandler validator = schema.newValidatorHandler(); parser.setContentHandler(validator); if (validator instanceof DTDHandler) { parser.setDTDHandler((DTDHandler) validator); } parser.setErrorHandler(writer); validator.setContentHandler(writer); validator.setErrorHandler(writer); writer.setTypeInfoProvider(validator.getTypeInfoProvider()); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Validate instance documents and print type information if (instances != null && instances.size() > 0) { final int length = instances.size(); for (int j = 0; j < length; ++j) { parser.parse((String) instances.elementAt(j)); } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - "+e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException)e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } // main(String[])
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/NewAbstractCloudTest.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/NewAbstractCloudTest.java index e9278969..f8f39fd8 100644 --- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/NewAbstractCloudTest.java +++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/NewAbstractCloudTest.java @@ -1,417 +1,417 @@ package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud; import java.io.File; import java.io.IOException; import org.cloudifysource.dsl.cloud.compute.ComputeTemplate; import org.cloudifysource.quality.iTests.framework.utils.ApplicationInstaller; import org.cloudifysource.quality.iTests.framework.utils.AssertUtils; import org.cloudifysource.quality.iTests.framework.utils.CloudBootstrapper; import org.cloudifysource.quality.iTests.framework.utils.DumpUtils; import org.cloudifysource.quality.iTests.framework.utils.LogUtils; import org.cloudifysource.quality.iTests.framework.utils.ScriptUtils; import org.cloudifysource.quality.iTests.framework.utils.ServiceInstaller; import org.cloudifysource.quality.iTests.framework.utils.StorageUtils; import org.cloudifysource.quality.iTests.test.AbstractTestSupport; import org.cloudifysource.quality.iTests.test.cli.cloudify.CommandTestUtils; import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.CloudService; import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.CloudServiceManager; import org.cloudifysource.quality.iTests.test.cli.cloudify.security.SecurityConstants; import org.openspaces.admin.Admin; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import com.gigaspaces.internal.utils.StringUtils; public abstract class NewAbstractCloudTest extends AbstractTestSupport { private static final int TEN_SECONDS_IN_MILLIS = 10000; public static final int SERVICE_INSTALLATION_TIMEOUT_IN_MINUTES = 10; private static final int MAX_SCAN_RETRY = 3; protected CloudService cloudService; protected void customizeCloud() throws Exception {} protected void beforeBootstrap() throws Exception {} protected void afterBootstrap() throws Exception {} protected void beforeTeardown() throws Exception {} protected void afterTeardown() throws Exception {} /****** * Returns the name of the cloud, as used in the bootstrap-cloud command. * * @return */ protected abstract String getCloudName(); /******** * Indicates if the cloud used in this test is reusable - which means it may have already been bootstrapped and can * be reused. Non reusable clouds are bootstrapped at the beginning of the class, and torn down at its end. Reusable * clouds are torn down when the suite ends. * * @return */ protected abstract boolean isReusableCloud(); @BeforeClass(alwaysRun = true) public void overrideCloudifyJars() throws Exception { if(System.getProperty("cloudify.override") != null) { buildAndCopyCloudifyJars(getCloudName()); } } private void buildAndCopyCloudifyJars(String cloudName) throws Exception{ String cloudifySourceDir = ScriptUtils.getCloudifySourceDir() + "cloudify"; String prefix = ""; String extension = ""; if(ScriptUtils.isWindows()) { prefix = getPrefix(System.getenv("M2_HOME")); extension = ".bat"; } ScriptUtils.startLocalProcess(cloudifySourceDir, (prefix + "mvn" + extension + " clean package -DskipTests").split(" ")); if(ScriptUtils.isWindows()) { prefix = getPrefix(System.getenv("ANT_HOME")); } ScriptUtils.startLocalProcess(cloudifySourceDir, (prefix + "ant" + extension + " -f copy_jars_local.xml \"Copy Cloudify jars to install dir\"").split(" ")); ScriptUtils.startLocalProcess(cloudifySourceDir, (prefix + "ant" + extension + " -f copy_jars_local.xml \"Copy Cloudify jars to " + getCloudName() + " upload dir\"").split(" ")); } private String getPrefix(String homeVar) { String s = File.separator; return "cmd /c call " + homeVar + s + "bin" + s; } @BeforeMethod public void beforeTest() { LogUtils.log("Creating test folder"); } public CloudService getService() { return cloudService; } protected void bootstrap() throws Exception { bootstrap(null, null); } protected void bootstrap(CloudBootstrapper bootstrapper) throws Exception { bootstrap(null, bootstrapper); } protected void bootstrap(CloudService service) throws Exception { bootstrap(service, null); } protected void bootstrap(CloudService service, CloudBootstrapper bootstrapper) throws Exception { if (this.isReusableCloud()) { throw new UnsupportedOperationException(this.getClass().getName() + "Requires reusable clouds, which are not supported yet"); } if (service == null) { // use the default cloud service if non is specified this.cloudService = CloudServiceManager.getInstance().getCloudService(this.getCloudName()); } else { this.cloudService = service; // use the custom service to execute bootstrap and teardown commands } if (bootstrapper != null) { // use the custom bootstrapper this.cloudService.setBootstrapper(bootstrapper); } this.cloudService.init(this.getClass().getSimpleName().toLowerCase()); LogUtils.log("Customizing cloud"); customizeCloud(); beforeBootstrap(); String branchName = System.getProperty("branch.name", ""); LogUtils.log("Branch name is : " + branchName); - final String prefix = System.getProperty("user.name") + "-" + property + this.getClass().getSimpleName().toLowerCase() + "-"; + final String prefix = System.getProperty("user.name") + "-" + branchName + this.getClass().getSimpleName().toLowerCase() + "-"; this.cloudService.setMachinePrefix(prefix); this.cloudService.setVolumePrefix(prefix); this.cloudService.bootstrapCloud(); if(!cloudService.getBootstrapper().isBootstrapExpectedToFail()) { afterBootstrap(); } } protected void teardown() throws Exception { beforeTeardown(); if (this.cloudService == null) { LogUtils.log("No teardown was executed as the cloud instance for this class was not created"); return; } this.cloudService.teardownCloud(); afterTeardown(); } protected void teardown(Admin admin) throws Exception { beforeTeardown(); if (this.cloudService == null) { LogUtils.log("No teardown was executed as the cloud instance for this class was not created"); } this.cloudService.teardownCloud(admin); afterTeardown(); } protected void doSanityTest(String applicationFolderName, String applicationName) throws IOException, InterruptedException { LogUtils.log("installing application " + applicationName + " on " + cloudService.getCloudName()); String applicationPath = ScriptUtils.getBuildPath() + "/recipes/apps/" + applicationFolderName; installApplicationAndWait(applicationPath, applicationName); uninstallApplicationAndWait(applicationName); scanForLeakedAgentNodes(); } protected void doSanityTest(String applicationFolderName, String applicationName, final int timeout) throws IOException, InterruptedException { LogUtils.log("installing application " + applicationName + " on " + cloudService.getCloudName()); String applicationPath = ScriptUtils.getBuildPath() + "/recipes/apps/" + applicationFolderName; installApplicationAndWait(applicationPath, applicationName, timeout); uninstallApplicationIfFound(applicationName); scanForLeakedAgentNodes(); } protected void scanForLeakedAgentNodes() { if (cloudService == null) { return; } // We will give a short timeout to give the ESM // time to recognize that he needs to shutdown the machine. try { Thread.sleep(TEN_SECONDS_IN_MILLIS); } catch (InterruptedException e) { } Throwable first = null; for (int i = 0 ; i < MAX_SCAN_RETRY ; i++) { try { boolean leakedAgentNodesScanResult = this.cloudService.scanLeakedAgentNodes(); if (leakedAgentNodesScanResult == true) { return; } else { Assert.fail("Leaked nodes were found!"); } break; } catch (final Exception t) { first = t; LogUtils.log("Failed scaning for leaked nodes. attempt number " + (i + 1) , t); } } if (first != null) { Assert.fail("Failed scanning for leaked nodes after " + MAX_SCAN_RETRY + " attempts. First exception was --> " + first.getMessage(), first); } } protected String installApplicationAndWait(String applicationName) throws IOException, InterruptedException { ApplicationInstaller applicationInstaller = new ApplicationInstaller(getRestUrl(), applicationName); applicationInstaller.waitForFinish(true); return applicationInstaller.install(); } protected String installApplicationAndWait(String applicationPath, String applicationName) throws IOException, InterruptedException { ApplicationInstaller applicationInstaller = new ApplicationInstaller(getRestUrl(), applicationName); applicationInstaller.recipePath(applicationPath); applicationInstaller.waitForFinish(true); return applicationInstaller.install(); } protected String uninstallApplicationAndWait(String applicationName) throws IOException, InterruptedException { return uninstallApplicationAndWait(applicationName, false); } protected String uninstallApplicationAndWait(String applicationName, boolean isExpectedFail) throws IOException, InterruptedException { ApplicationInstaller applicationInstaller = new ApplicationInstaller(getRestUrl(), applicationName); applicationInstaller.waitForFinish(true); applicationInstaller.expectToFail(isExpectedFail); return applicationInstaller.uninstall(); } protected void uninstallApplicationIfFound(String applicationName) throws IOException, InterruptedException { ApplicationInstaller applicationInstaller = new ApplicationInstaller(getRestUrl(), applicationName); applicationInstaller.waitForFinish(true); applicationInstaller.uninstallIfFound(); } protected String installApplicationAndWait(String applicationPath, String applicationName, int timeout) throws IOException, InterruptedException { ApplicationInstaller applicationInstaller = new ApplicationInstaller(getRestUrl(), applicationName); applicationInstaller.recipePath(applicationPath); applicationInstaller.waitForFinish(true); applicationInstaller.timeoutInMinutes(timeout); return applicationInstaller.install(); } protected String installApplicationAndWait(String applicationPath, String applicationName, int timeout , boolean expectToFail) throws IOException, InterruptedException { ApplicationInstaller applicationInstaller = new ApplicationInstaller(getRestUrl(), applicationName); applicationInstaller.recipePath(applicationPath); applicationInstaller.waitForFinish(true); applicationInstaller.expectToFail(expectToFail); applicationInstaller.timeoutInMinutes(timeout); return applicationInstaller.install(); } protected String uninstallServiceAndWait(String serviceName, boolean isExpectedFail) throws IOException, InterruptedException { ServiceInstaller serviceInstaller = new ServiceInstaller(getRestUrl(), serviceName); serviceInstaller.waitForFinish(true); serviceInstaller.expectToFail(isExpectedFail); String output = serviceInstaller.uninstall(); if(StorageUtils.isInitialized()){ StorageUtils.afterServiceUninstallation(serviceName); } return output; } protected String uninstallServiceAndWait(String serviceName) throws IOException, InterruptedException { return uninstallServiceAndWait(serviceName, false); } protected void uninstallServiceIfFound(String serviceName) throws IOException, InterruptedException { ServiceInstaller serviceInstaller = new ServiceInstaller(getRestUrl(), serviceName); serviceInstaller.waitForFinish(true); serviceInstaller.uninstallIfFound(); if(StorageUtils.isInitialized()){ StorageUtils.afterServiceUninstallation(serviceName); } } protected String invokeCommand(String serviceName, String commandName) throws IOException, InterruptedException { ServiceInstaller installer = new ServiceInstaller(getRestUrl(), serviceName); return installer.invoke(commandName); } protected String installServiceAndWait(String servicePath, String serviceName) throws IOException, InterruptedException { return installServiceAndWait(servicePath, serviceName, SERVICE_INSTALLATION_TIMEOUT_IN_MINUTES, false); } protected String installServiceAndWait(String servicePath, String serviceName, int timeout, int numOfInstances) throws IOException, InterruptedException { return installServiceAndWait(servicePath, serviceName, timeout, false, false, numOfInstances); } protected String installServiceAndWait(String servicePath, String serviceName, int timeout) throws IOException, InterruptedException { return installServiceAndWait(servicePath, serviceName, timeout, false); } protected String installServiceAndWait(String servicePath, String serviceName, int timeout , boolean expectToFail) throws IOException, InterruptedException { return installServiceAndWait(servicePath, serviceName, timeout, expectToFail, false, 0); } protected String installServiceAndWait(String servicePath, String serviceName, int timeout , boolean expectToFail, boolean disableSelfHealing, int numOfInstances) throws IOException, InterruptedException { ServiceInstaller serviceInstaller = new ServiceInstaller(getRestUrl(), serviceName); serviceInstaller.recipePath(servicePath); serviceInstaller.waitForFinish(true); serviceInstaller.expectToFail(expectToFail); serviceInstaller.timeoutInMinutes(timeout); serviceInstaller.setDisableSelfHealing(disableSelfHealing); if(StorageUtils.isInitialized()){ StorageUtils.beforeServiceInstallation(); } String output = serviceInstaller.install(); if(StorageUtils.isInitialized()){ StorageUtils.afterServiceInstallation(serviceName); } if(numOfInstances > 0){ serviceInstaller.setInstances(numOfInstances); } return output; } protected String installServiceAndWait(String servicePath, String serviceName, boolean expectToFail) throws IOException, InterruptedException { return installServiceAndWait(servicePath, serviceName, SERVICE_INSTALLATION_TIMEOUT_IN_MINUTES, expectToFail); } protected String getRestUrl() { String finalUrl = null; String[] restUrls = cloudService.getRestUrls(); AssertUtils.assertNotNull("No rest URL's found. there was probably a problem with bootstrap", restUrls); if (restUrls.length == 1) { finalUrl = restUrls[0]; } else { for (String url : restUrls) { String command = "connect " + url; try { LogUtils.log("trying to connect to rest with url " + url); CommandTestUtils.runCommandAndWait(command); finalUrl = url; break; } catch (Throwable e) { LogUtils.log("caught an exception while trying to connect to rest server with url " + url, e); } } } if (finalUrl == null) { Assert.fail("Failed to find a working rest URL. tried : " + StringUtils.arrayToCommaDelimitedString(restUrls)); } return finalUrl; } protected String getWebuiUrl() { return cloudService.getWebuiUrls()[0]; } protected void dumpMachines() { final String restUrl = getRestUrl(); String url = null; try { String cloudifyUser = null; String cloudifyPassword = null; url = restUrl + "/service/dump/machines/?fileSizeLimit=50000000"; if (cloudService.getBootstrapper().isSecured()) { cloudifyUser = SecurityConstants.USER_PWD_ALL_ROLES; cloudifyPassword = SecurityConstants.USER_PWD_ALL_ROLES; } DumpUtils.dumpMachines(restUrl, cloudifyUser, cloudifyPassword); } catch (final Exception e) { LogUtils.log("Failed to create dump for this url - " + url, e); } } protected File getPemFile() { String cloudFolderPath = getService().getPathToCloudFolder(); ComputeTemplate managementTemplate = getService().getCloud().getCloudCompute().getTemplates().get(getService().getCloud().getConfiguration().getManagementMachineTemplate()); String keyFileName = managementTemplate.getKeyFile(); String localDirectory = managementTemplate.getLocalDirectory(); String keyFilePath = cloudFolderPath + "/" + localDirectory + "/" + keyFileName; final File keyFile = new File(keyFilePath); if(!keyFile.exists()) { throw new IllegalStateException("Could not find key file at expected location: " + keyFilePath); } if(!keyFile.isFile()) { throw new IllegalStateException("Expected key file: " + keyFile + " is not a file"); } return keyFile; } }
true
true
protected void bootstrap(CloudService service, CloudBootstrapper bootstrapper) throws Exception { if (this.isReusableCloud()) { throw new UnsupportedOperationException(this.getClass().getName() + "Requires reusable clouds, which are not supported yet"); } if (service == null) { // use the default cloud service if non is specified this.cloudService = CloudServiceManager.getInstance().getCloudService(this.getCloudName()); } else { this.cloudService = service; // use the custom service to execute bootstrap and teardown commands } if (bootstrapper != null) { // use the custom bootstrapper this.cloudService.setBootstrapper(bootstrapper); } this.cloudService.init(this.getClass().getSimpleName().toLowerCase()); LogUtils.log("Customizing cloud"); customizeCloud(); beforeBootstrap(); String branchName = System.getProperty("branch.name", ""); LogUtils.log("Branch name is : " + branchName); final String prefix = System.getProperty("user.name") + "-" + property + this.getClass().getSimpleName().toLowerCase() + "-"; this.cloudService.setMachinePrefix(prefix); this.cloudService.setVolumePrefix(prefix); this.cloudService.bootstrapCloud(); if(!cloudService.getBootstrapper().isBootstrapExpectedToFail()) { afterBootstrap(); } }
protected void bootstrap(CloudService service, CloudBootstrapper bootstrapper) throws Exception { if (this.isReusableCloud()) { throw new UnsupportedOperationException(this.getClass().getName() + "Requires reusable clouds, which are not supported yet"); } if (service == null) { // use the default cloud service if non is specified this.cloudService = CloudServiceManager.getInstance().getCloudService(this.getCloudName()); } else { this.cloudService = service; // use the custom service to execute bootstrap and teardown commands } if (bootstrapper != null) { // use the custom bootstrapper this.cloudService.setBootstrapper(bootstrapper); } this.cloudService.init(this.getClass().getSimpleName().toLowerCase()); LogUtils.log("Customizing cloud"); customizeCloud(); beforeBootstrap(); String branchName = System.getProperty("branch.name", ""); LogUtils.log("Branch name is : " + branchName); final String prefix = System.getProperty("user.name") + "-" + branchName + this.getClass().getSimpleName().toLowerCase() + "-"; this.cloudService.setMachinePrefix(prefix); this.cloudService.setVolumePrefix(prefix); this.cloudService.bootstrapCloud(); if(!cloudService.getBootstrapper().isBootstrapExpectedToFail()) { afterBootstrap(); } }
diff --git a/JavaSource/org/unitime/timetable/dataexchange/StaffImport.java b/JavaSource/org/unitime/timetable/dataexchange/StaffImport.java index b5a60fbb..db1ec619 100644 --- a/JavaSource/org/unitime/timetable/dataexchange/StaffImport.java +++ b/JavaSource/org/unitime/timetable/dataexchange/StaffImport.java @@ -1,151 +1,156 @@ /* * UniTime 3.1 (University Timetabling Application) * Copyright (C) 2008, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * 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. */ package org.unitime.timetable.dataexchange; import java.io.FileInputStream; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.model.ChangeLog; import org.unitime.timetable.model.PositionCodeType; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.Staff; import org.unitime.timetable.model.dao.PositionCodeTypeDAO; /** * * @author Timothy Almon * */ public class StaffImport extends BaseImport { boolean trimLeadingZerosFromExternalId = false; public StaffImport() { super(); } public void loadFromXML(String filename) throws Exception { FileInputStream fis = null; try { fis = new FileInputStream(filename); loadFromStream(fis); } finally { if (fis != null) fis.close(); } return; } public void loadFromStream(FileInputStream fis) throws Exception { Document document = (new SAXReader()).read(fis); Element root = document.getRootElement(); loadXml(root); } public void loadXml(Element root) throws Exception { String trimLeadingZeros = ApplicationProperties.getProperty("tmtbl.data.exchange.trim.externalId","false"); if (trimLeadingZeros.equals("true")){ trimLeadingZerosFromExternalId = true; } if (!root.getName().equalsIgnoreCase("staff")) { throw new Exception("Given XML file is not a Staff load file."); } String campus = root.attributeValue("campus"); String year = root.attributeValue("year"); String term = root.attributeValue("term"); String created = root.attributeValue("created"); String elementName = "staffMember"; try { beginTransaction(); Session session = Session.getSessionUsingInitiativeYearTerm(campus, year, term); if (session != null && created != null) { ChangeLog.addChange(getHibSession(), getManager(), session, session, created, ChangeLog.Source.DATA_IMPORT_STAFF, ChangeLog.Operation.UPDATE, null, null); } for ( Iterator it = root.elementIterator(); it.hasNext(); ) { Element element = (Element) it.next(); String externalId = getRequiredStringAttribute(element, "externalId", elementName); Staff staff = null; if(externalId != null && externalId.length() > 0) { if (trimLeadingZerosFromExternalId){ - externalId = (new Integer(externalId)).toString(); - } + try { + Integer num = new Integer(externalId); + externalId = num.toString(); + } catch (Exception e) { + // do nothing + } + } staff = findByExternalId(externalId); } if(staff == null) { staff = new Staff(); } else { if("T".equalsIgnoreCase(element.attributeValue("delete"))) { getHibSession().delete(staff); continue; } } staff.setFirstName(getOptionalStringAttribute(element, "firstName")); staff.setMiddleName(getOptionalStringAttribute(element, "middleName")); staff.setLastName(getRequiredStringAttribute(element, "lastName", elementName)); PositionCodeType posCodeType = null; String positionCode = getOptionalStringAttribute(element, "positionCode"); if (positionCode != null){ posCodeType = new PositionCodeTypeDAO().get(positionCode); } staff.setPositionCode(posCodeType); staff.setExternalUniqueId(externalId); String dept = getOptionalStringAttribute(element, "department"); if (dept != null) staff.setDept(dept); String email = getOptionalStringAttribute(element, "email"); if (email != null) staff.setEmail(email); getHibSession().saveOrUpdate(staff); flushIfNeeded(true); } commitTransaction(); } catch (Exception e) { fatal("Exception: " + e.getMessage(), e); rollbackTransaction(); throw e; } return; } private Staff findByExternalId(String externalId) { return (Staff) this. getHibSession(). createQuery("select distinct a from Staff as a where a.externalUniqueId=:externalId"). setString("externalId", externalId). setCacheable(true). uniqueResult(); } }
true
true
public void loadXml(Element root) throws Exception { String trimLeadingZeros = ApplicationProperties.getProperty("tmtbl.data.exchange.trim.externalId","false"); if (trimLeadingZeros.equals("true")){ trimLeadingZerosFromExternalId = true; } if (!root.getName().equalsIgnoreCase("staff")) { throw new Exception("Given XML file is not a Staff load file."); } String campus = root.attributeValue("campus"); String year = root.attributeValue("year"); String term = root.attributeValue("term"); String created = root.attributeValue("created"); String elementName = "staffMember"; try { beginTransaction(); Session session = Session.getSessionUsingInitiativeYearTerm(campus, year, term); if (session != null && created != null) { ChangeLog.addChange(getHibSession(), getManager(), session, session, created, ChangeLog.Source.DATA_IMPORT_STAFF, ChangeLog.Operation.UPDATE, null, null); } for ( Iterator it = root.elementIterator(); it.hasNext(); ) { Element element = (Element) it.next(); String externalId = getRequiredStringAttribute(element, "externalId", elementName); Staff staff = null; if(externalId != null && externalId.length() > 0) { if (trimLeadingZerosFromExternalId){ externalId = (new Integer(externalId)).toString(); } staff = findByExternalId(externalId); } if(staff == null) { staff = new Staff(); } else { if("T".equalsIgnoreCase(element.attributeValue("delete"))) { getHibSession().delete(staff); continue; } } staff.setFirstName(getOptionalStringAttribute(element, "firstName")); staff.setMiddleName(getOptionalStringAttribute(element, "middleName")); staff.setLastName(getRequiredStringAttribute(element, "lastName", elementName)); PositionCodeType posCodeType = null; String positionCode = getOptionalStringAttribute(element, "positionCode"); if (positionCode != null){ posCodeType = new PositionCodeTypeDAO().get(positionCode); } staff.setPositionCode(posCodeType); staff.setExternalUniqueId(externalId); String dept = getOptionalStringAttribute(element, "department"); if (dept != null) staff.setDept(dept); String email = getOptionalStringAttribute(element, "email"); if (email != null) staff.setEmail(email); getHibSession().saveOrUpdate(staff); flushIfNeeded(true); } commitTransaction(); } catch (Exception e) { fatal("Exception: " + e.getMessage(), e); rollbackTransaction(); throw e; } return; }
public void loadXml(Element root) throws Exception { String trimLeadingZeros = ApplicationProperties.getProperty("tmtbl.data.exchange.trim.externalId","false"); if (trimLeadingZeros.equals("true")){ trimLeadingZerosFromExternalId = true; } if (!root.getName().equalsIgnoreCase("staff")) { throw new Exception("Given XML file is not a Staff load file."); } String campus = root.attributeValue("campus"); String year = root.attributeValue("year"); String term = root.attributeValue("term"); String created = root.attributeValue("created"); String elementName = "staffMember"; try { beginTransaction(); Session session = Session.getSessionUsingInitiativeYearTerm(campus, year, term); if (session != null && created != null) { ChangeLog.addChange(getHibSession(), getManager(), session, session, created, ChangeLog.Source.DATA_IMPORT_STAFF, ChangeLog.Operation.UPDATE, null, null); } for ( Iterator it = root.elementIterator(); it.hasNext(); ) { Element element = (Element) it.next(); String externalId = getRequiredStringAttribute(element, "externalId", elementName); Staff staff = null; if(externalId != null && externalId.length() > 0) { if (trimLeadingZerosFromExternalId){ try { Integer num = new Integer(externalId); externalId = num.toString(); } catch (Exception e) { // do nothing } } staff = findByExternalId(externalId); } if(staff == null) { staff = new Staff(); } else { if("T".equalsIgnoreCase(element.attributeValue("delete"))) { getHibSession().delete(staff); continue; } } staff.setFirstName(getOptionalStringAttribute(element, "firstName")); staff.setMiddleName(getOptionalStringAttribute(element, "middleName")); staff.setLastName(getRequiredStringAttribute(element, "lastName", elementName)); PositionCodeType posCodeType = null; String positionCode = getOptionalStringAttribute(element, "positionCode"); if (positionCode != null){ posCodeType = new PositionCodeTypeDAO().get(positionCode); } staff.setPositionCode(posCodeType); staff.setExternalUniqueId(externalId); String dept = getOptionalStringAttribute(element, "department"); if (dept != null) staff.setDept(dept); String email = getOptionalStringAttribute(element, "email"); if (email != null) staff.setEmail(email); getHibSession().saveOrUpdate(staff); flushIfNeeded(true); } commitTransaction(); } catch (Exception e) { fatal("Exception: " + e.getMessage(), e); rollbackTransaction(); throw e; } return; }
diff --git a/core/src/main/java/org/apache/mahout/ep/State.java b/core/src/main/java/org/apache/mahout/ep/State.java index fa0ecf5b..fd27be56 100644 --- a/core/src/main/java/org/apache/mahout/ep/State.java +++ b/core/src/main/java/org/apache/mahout/ep/State.java @@ -1,198 +1,198 @@ package org.apache.mahout.ep; import java.util.Arrays; import java.util.Random; /** * Records evolutionary state and provides a mutation operation for recorded-step meta-mutation. * * You provide the payload, this class provides the mutation operations. During mutation, * the payload is copied and after the state variables are changed, they are passed to the * payload. * * Parameters are internally mutated in a state space that spans all of R^n, but parameters * passed to the payload are transformed as specified by a call to setMap(). The default * mapping is the identity map, but uniform-ish or exponential-ish coverage of a range are * also supported. * * More information on the underlying algorithm can be found in the following paper * * http://arxiv.org/abs/0803.3838 * * @see Mapping * @see State */ public class State<T extends Payload<T>> implements Comparable<State<T>> { // object count is kept to break ties in comparison. static volatile int objectCount = 0; int id = objectCount++; private Random gen = new Random(); // current state private double[] params; // mappers to transform state private Mapping[] maps; // omni-directional mutation private double omni; // directional mutation private double[] step; // current fitness value private double value; private T payload; private State() { } /** * Invent a new state with no momentum (yet). */ public State(double[] x0, double omni) { params = Arrays.copyOf(x0, x0.length); this.omni = omni; step = new double[params.length]; maps = new Mapping[params.length]; } /** * Deep copies a state, useful in mutation. */ public State<T> copy() { State<T> r = new State<T>(); r.params = Arrays.copyOf(this.params, this.params.length); r.omni = this.omni; r.step = Arrays.copyOf(this.step, this.step.length); r.maps = Arrays.copyOf(this.maps, this.maps.length); if (this.payload != null) { r.payload = this.payload.copy(); } r.gen = this.gen; return r; } /** * Clones this state with a random change in position. Copies the payload and * lets it know about the change. * * @return A new state. */ public State<T> mutate() { double sum = 0; for (double v : step) { sum += v * v; } sum = Math.sqrt(sum); double lambda = 1 + gen.nextGaussian(); State<T> r = this.copy(); double magnitude = 0.9 * omni + sum / 10; r.omni = magnitude * -Math.log(1 - gen.nextDouble()); for (int i = 0; i < step.length; i++) { r.step[i] = lambda * step[i] + r.omni * gen.nextGaussian(); r.params[i] += r.step[i]; } - if (r.payload != null) { + if (this.payload != null) { r.payload.update(r.getMappedParams()); } return r; } /** * Defines the transformation for a parameter. * @param i Which parameter's mapping to define. * @param m The mapping to use. * @see org.apache.mahout.ep.Mapping */ public void setMap(int i, Mapping m) { maps[i] = m; } /** * Returns a transformed parameter. * @param i The parameter to return. * @return The value of the parameter. */ public double get(int i) { Mapping m = maps[i]; if (m == null) { return params[i]; } else { return m.apply(params[i]); } } /** * Returns all the parameters in mapped form. * @return An array of parameters. */ public double[] getMappedParams() { double[] r = Arrays.copyOf(params, params.length); for (int i = 0; i < params.length; i++) { r[i] = get(i); } return r; } public double getOmni() { return omni; } public double[] getStep() { return step; } public T getPayload() { return payload; } public double getValue() { return value; } public void setRand(Random rand) { this.gen = rand; } public void setOmni(double omni) { this.omni = omni; } public void setValue(double v) { value = v; } public void setPayload(T payload) { this.payload = payload; } /** * Natural order is to sort in descending order of score. Creation order is used as a * tie-breaker. * * @param other The state to compare with. * @return -1, 0, 1 if the other state is better, identical or worse than this one. */ @Override public int compareTo(State other) { int r = Double.compare(other.value, this.value); if (r != 0) { return r; } else { return this.id - other.id; } } public String toString() { double sum = 0; for (double v : step) { sum += v * v; } return String.format("<S/%s %.3f %.3f>", payload, omni + Math.sqrt(sum), value); } }
true
true
public State<T> mutate() { double sum = 0; for (double v : step) { sum += v * v; } sum = Math.sqrt(sum); double lambda = 1 + gen.nextGaussian(); State<T> r = this.copy(); double magnitude = 0.9 * omni + sum / 10; r.omni = magnitude * -Math.log(1 - gen.nextDouble()); for (int i = 0; i < step.length; i++) { r.step[i] = lambda * step[i] + r.omni * gen.nextGaussian(); r.params[i] += r.step[i]; } if (r.payload != null) { r.payload.update(r.getMappedParams()); } return r; }
public State<T> mutate() { double sum = 0; for (double v : step) { sum += v * v; } sum = Math.sqrt(sum); double lambda = 1 + gen.nextGaussian(); State<T> r = this.copy(); double magnitude = 0.9 * omni + sum / 10; r.omni = magnitude * -Math.log(1 - gen.nextDouble()); for (int i = 0; i < step.length; i++) { r.step[i] = lambda * step[i] + r.omni * gen.nextGaussian(); r.params[i] += r.step[i]; } if (this.payload != null) { r.payload.update(r.getMappedParams()); } return r; }
diff --git a/engine/src/main/java/org/camunda/bpm/engine/impl/interceptor/CommandContext.java b/engine/src/main/java/org/camunda/bpm/engine/impl/interceptor/CommandContext.java index a116c60649..4bba855c3b 100644 --- a/engine/src/main/java/org/camunda/bpm/engine/impl/interceptor/CommandContext.java +++ b/engine/src/main/java/org/camunda/bpm/engine/impl/interceptor/CommandContext.java @@ -1,405 +1,405 @@ /* 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.camunda.bpm.engine.impl.interceptor; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.ibatis.exceptions.PersistenceException; import org.camunda.bpm.application.ProcessApplicationReference; import org.camunda.bpm.engine.IdentityService; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.TaskAlreadyClaimedException; import org.camunda.bpm.engine.impl.application.ProcessApplicationManager; import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.camunda.bpm.engine.impl.cfg.TransactionContext; import org.camunda.bpm.engine.impl.cfg.TransactionContextFactory; import org.camunda.bpm.engine.impl.context.Context; import org.camunda.bpm.engine.impl.db.DbSqlSession; import org.camunda.bpm.engine.impl.identity.Authentication; import org.camunda.bpm.engine.impl.identity.ReadOnlyIdentityProvider; import org.camunda.bpm.engine.impl.identity.WritableIdentityProvider; import org.camunda.bpm.engine.impl.jobexecutor.FailedJobCommandFactory; import org.camunda.bpm.engine.impl.persistence.entity.AttachmentManager; import org.camunda.bpm.engine.impl.persistence.entity.AuthorizationManager; import org.camunda.bpm.engine.impl.persistence.entity.ByteArrayManager; import org.camunda.bpm.engine.impl.persistence.entity.CommentManager; import org.camunda.bpm.engine.impl.persistence.entity.DeploymentManager; import org.camunda.bpm.engine.impl.persistence.entity.EventSubscriptionManager; import org.camunda.bpm.engine.impl.persistence.entity.ExecutionManager; import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceManager; import org.camunda.bpm.engine.impl.persistence.entity.HistoricDetailManager; import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceManager; import org.camunda.bpm.engine.impl.persistence.entity.HistoricTaskInstanceManager; import org.camunda.bpm.engine.impl.persistence.entity.HistoricVariableInstanceManager; import org.camunda.bpm.engine.impl.persistence.entity.IdentityInfoManager; import org.camunda.bpm.engine.impl.persistence.entity.IdentityLinkManager; import org.camunda.bpm.engine.impl.persistence.entity.IncidentManager; import org.camunda.bpm.engine.impl.persistence.entity.JobManager; import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionManager; import org.camunda.bpm.engine.impl.persistence.entity.PropertyManager; import org.camunda.bpm.engine.impl.persistence.entity.ResourceManager; import org.camunda.bpm.engine.impl.persistence.entity.StatisticsManager; import org.camunda.bpm.engine.impl.persistence.entity.TableDataManager; import org.camunda.bpm.engine.impl.persistence.entity.TaskManager; import org.camunda.bpm.engine.impl.persistence.entity.VariableInstanceManager; import org.camunda.bpm.engine.impl.pvm.runtime.AtomicOperation; import org.camunda.bpm.engine.impl.pvm.runtime.InterpretableExecution; /** * @author Tom Baeyens * @author Agim Emruli * @author Daniel Meyer */ public class CommandContext { private static Logger log = Logger.getLogger(CommandContext.class.getName()); protected Command< ? > command; protected TransactionContext transactionContext; protected Map<Class< ? >, SessionFactory> sessionFactories; protected Map<Class< ? >, Session> sessions = new HashMap<Class< ? >, Session>(); protected Throwable exception = null; protected LinkedList<AtomicOperation> nextOperations = new LinkedList<AtomicOperation>(); protected ProcessEngineConfigurationImpl processEngineConfiguration; protected FailedJobCommandFactory failedJobCommandFactory; public CommandContext(Command<?> command, ProcessEngineConfigurationImpl processEngineConfiguration) { this(command, processEngineConfiguration, processEngineConfiguration.getTransactionContextFactory()); } public CommandContext(Command<?> cmd, ProcessEngineConfigurationImpl processEngineConfiguration, TransactionContextFactory transactionContextFactory) { this.command = cmd; this.processEngineConfiguration = processEngineConfiguration; this.failedJobCommandFactory = processEngineConfiguration.getFailedJobCommandFactory(); sessionFactories = processEngineConfiguration.getSessionFactories(); this.transactionContext = transactionContextFactory.openTransactionContext(this); } public void performOperation(final AtomicOperation executionOperation, final InterpretableExecution execution) { ProcessApplicationReference targetProcessApplication = getTargetProcessApplication(execution); if(requiresContextSwitch(executionOperation, targetProcessApplication)) { Context.executeWithinProcessApplication(new Callable<Void>() { public Void call() throws Exception { performOperation(executionOperation, execution); return null; } }, targetProcessApplication); } else { nextOperations.add(executionOperation); if (nextOperations.size()==1) { try { Context.setExecutionContext(execution); while (!nextOperations.isEmpty()) { AtomicOperation currentOperation = nextOperations.removeFirst(); if (log.isLoggable(Level.FINEST)) { log.finest("AtomicOperation: " + currentOperation + " on " + this); } currentOperation.execute(execution); } } finally { Context.removeExecutionContext(); } } } } protected ProcessApplicationReference getTargetProcessApplication(InterpretableExecution execution) { String deploymentId = execution.getProcessDefinition().getDeploymentId(); ProcessApplicationManager processApplicationManager = processEngineConfiguration.getProcessApplicationManager(); return processApplicationManager.getProcessApplicationForDeployment(deploymentId); } protected boolean requiresContextSwitch(final AtomicOperation executionOperation, ProcessApplicationReference processApplicationReference) { final ProcessApplicationReference currentProcessApplication = Context.getCurrentProcessApplication(); return processApplicationReference != null && ( currentProcessApplication == null || !processApplicationReference.getName().equals(currentProcessApplication.getName()) ); } public void close() { // the intention of this method is that all resources are closed properly, // even // if exceptions occur in close or flush methods of the sessions or the // transaction context. try { try { try { if (exception == null) { flushSessions(); } } catch (Throwable exception) { exception(exception); } finally { try { if (exception == null) { transactionContext.commit(); } } catch (Throwable exception) { exception(exception); } if (exception != null) { Level loggingLevel = Level.SEVERE; if (exception instanceof TaskAlreadyClaimedException) { loggingLevel = Level.INFO; // reduce log level, because this is not really a technical exception } log.log(loggingLevel, "Error while closing command context", exception); transactionContext.rollback(); } } } catch (Throwable exception) { exception(exception); } finally { closeSessions(); } } catch (Throwable exception) { exception(exception); } // rethrow the original exception if there was one if (exception != null) { if (exception instanceof Error) { throw (Error) exception; } else if (exception instanceof PersistenceException) { - throw new ProcessEngineException("Process engnine persistence exception", exception); + throw new ProcessEngineException("Process engine persistence exception", exception); } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new ProcessEngineException("exception while executing command " + command, exception); } } } protected void flushSessions() { for (Session session : sessions.values()) { session.flush(); } } protected void closeSessions() { for (Session session : sessions.values()) { try { session.close(); } catch (Throwable exception) { exception(exception); } } } public void exception(Throwable exception) { if (this.exception == null) { this.exception = exception; } else { log.log(Level.SEVERE, "masked exception in command context. for root cause, see below as it will be rethrown later.", exception); } } @SuppressWarnings({"unchecked"}) public <T> T getSession(Class<T> sessionClass) { Session session = sessions.get(sessionClass); if (session == null) { SessionFactory sessionFactory = sessionFactories.get(sessionClass); if (sessionFactory==null) { throw new ProcessEngineException("no session factory configured for "+sessionClass.getName()); } session = sessionFactory.openSession(); sessions.put(sessionClass, session); } return (T) session; } public DbSqlSession getDbSqlSession() { return getSession(DbSqlSession.class); } public DeploymentManager getDeploymentManager() { return getSession(DeploymentManager.class); } public ResourceManager getResourceManager() { return getSession(ResourceManager.class); } public ByteArrayManager getByteArrayManager() { return getSession(ByteArrayManager.class); } public ProcessDefinitionManager getProcessDefinitionManager() { return getSession(ProcessDefinitionManager.class); } public ExecutionManager getExecutionManager() { return getSession(ExecutionManager.class); } public TaskManager getTaskManager() { return getSession(TaskManager.class); } public IdentityLinkManager getIdentityLinkManager() { return getSession(IdentityLinkManager.class); } public VariableInstanceManager getVariableInstanceManager() { return getSession(VariableInstanceManager.class); } public HistoricProcessInstanceManager getHistoricProcessInstanceManager() { return getSession(HistoricProcessInstanceManager.class); } public HistoricDetailManager getHistoricDetailManager() { return getSession(HistoricDetailManager.class); } public HistoricVariableInstanceManager getHistoricVariableInstanceManager() { return getSession(HistoricVariableInstanceManager.class); } public HistoricActivityInstanceManager getHistoricActivityInstanceManager() { return getSession(HistoricActivityInstanceManager.class); } public HistoricTaskInstanceManager getHistoricTaskInstanceManager() { return getSession(HistoricTaskInstanceManager.class); } public JobManager getJobManager() { return getSession(JobManager.class); } public IncidentManager getIncidentManager() { return getSession(IncidentManager.class); } public IdentityInfoManager getIdentityInfoManager() { return getSession(IdentityInfoManager.class); } public AttachmentManager getAttachmentManager() { return getSession(AttachmentManager.class); } public TableDataManager getTableDataManager() { return getSession(TableDataManager.class); } public CommentManager getCommentManager() { return getSession(CommentManager.class); } public EventSubscriptionManager getEventSubscriptionManager() { return getSession(EventSubscriptionManager.class); } public Map<Class< ? >, SessionFactory> getSessionFactories() { return sessionFactories; } public PropertyManager getPropertyManager() { return getSession(PropertyManager.class); } public StatisticsManager getStatisticsManager() { return getSession(StatisticsManager.class); } public AuthorizationManager getAuthorizationManager() { return getSession(AuthorizationManager.class); } public ReadOnlyIdentityProvider getReadOnlyIdentityProvider() { return getSession(ReadOnlyIdentityProvider.class); } public WritableIdentityProvider getWritableIdentityProvider() { return getSession(WritableIdentityProvider.class); } // getters and setters ////////////////////////////////////////////////////// public TransactionContext getTransactionContext() { return transactionContext; } public Command< ? > getCommand() { return command; } public Map<Class< ? >, Session> getSessions() { return sessions; } public Throwable getException() { return exception; } public FailedJobCommandFactory getFailedJobCommandFactory() { return failedJobCommandFactory; } public Authentication getAuthentication() { IdentityService identityService = processEngineConfiguration.getIdentityService(); return identityService.getCurrentAuthentication(); } public void runWithoutAuthentication(Runnable runnable) { IdentityService identityService = processEngineConfiguration.getIdentityService(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); try { identityService.clearAuthentication(); runnable.run(); } finally { identityService.setAuthentication(currentAuthentication); } } public String getAuthenticatedUserId() { IdentityService identityService = processEngineConfiguration.getIdentityService(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); if(currentAuthentication == null) { return null; } else { return currentAuthentication.getUserId(); } } public List<String> getAuthenticatedGroupIds() { IdentityService identityService = processEngineConfiguration.getIdentityService(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); if(currentAuthentication == null) { return null; } else { return currentAuthentication.getGroupIds(); } } }
true
true
public void close() { // the intention of this method is that all resources are closed properly, // even // if exceptions occur in close or flush methods of the sessions or the // transaction context. try { try { try { if (exception == null) { flushSessions(); } } catch (Throwable exception) { exception(exception); } finally { try { if (exception == null) { transactionContext.commit(); } } catch (Throwable exception) { exception(exception); } if (exception != null) { Level loggingLevel = Level.SEVERE; if (exception instanceof TaskAlreadyClaimedException) { loggingLevel = Level.INFO; // reduce log level, because this is not really a technical exception } log.log(loggingLevel, "Error while closing command context", exception); transactionContext.rollback(); } } } catch (Throwable exception) { exception(exception); } finally { closeSessions(); } } catch (Throwable exception) { exception(exception); } // rethrow the original exception if there was one if (exception != null) { if (exception instanceof Error) { throw (Error) exception; } else if (exception instanceof PersistenceException) { throw new ProcessEngineException("Process engnine persistence exception", exception); } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new ProcessEngineException("exception while executing command " + command, exception); } } }
public void close() { // the intention of this method is that all resources are closed properly, // even // if exceptions occur in close or flush methods of the sessions or the // transaction context. try { try { try { if (exception == null) { flushSessions(); } } catch (Throwable exception) { exception(exception); } finally { try { if (exception == null) { transactionContext.commit(); } } catch (Throwable exception) { exception(exception); } if (exception != null) { Level loggingLevel = Level.SEVERE; if (exception instanceof TaskAlreadyClaimedException) { loggingLevel = Level.INFO; // reduce log level, because this is not really a technical exception } log.log(loggingLevel, "Error while closing command context", exception); transactionContext.rollback(); } } } catch (Throwable exception) { exception(exception); } finally { closeSessions(); } } catch (Throwable exception) { exception(exception); } // rethrow the original exception if there was one if (exception != null) { if (exception instanceof Error) { throw (Error) exception; } else if (exception instanceof PersistenceException) { throw new ProcessEngineException("Process engine persistence exception", exception); } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new ProcessEngineException("exception while executing command " + command, exception); } } }
diff --git a/src/bindings/org/freedesktop/cairo/Context.java b/src/bindings/org/freedesktop/cairo/Context.java index ecbc5101..5e750f8b 100644 --- a/src/bindings/org/freedesktop/cairo/Context.java +++ b/src/bindings/org/freedesktop/cairo/Context.java @@ -1,418 +1,418 @@ /* * Context.java * * Copyright (c) 2007-2008 Operational Dynamics Consulting Pty Ltd * * The code in this file, and the library it is a part of, are made available * to you by the authors under the terms of the "GNU General Public Licence, * version 2" plus the "Classpath Exception" (you may link to this code as a * library into other programs provided you don't make a derivation of it). * See the LICENCE file for the terms governing usage and redistribution. */ package org.freedesktop.cairo; import org.gnome.gdk.Drawable; /** * Carry out drawing operations with the Cairo Graphics library. The current * Context contains the state of the rendering engine, including the * co-ordinates of as yet undrawn elements. * * <h2>Constructing</h2> * * Graphics will be rendered to the Surface specified when you construct the * Context: * <ul> * <li>If creating an image to be written to a file, start with an * {@link ImageSurface}, do your drawing, and then use Surface's writeToPNG() * to output your image. * <li>If drawing to the screen in a user interface application, construct a * Context using the underlying GDK Window in your Widget's * {@link org.gnome.gtk.Widget.ExposeEvent Widget.ExposeEvent}, and do your * drawing there. * </ul> * * See the links above for examples of each use case. * * <h2>Drawing Operations</h2> * * Context has numerous methods allowing you to draw shapes, patterns, and * images to the Surface you are drawing on. These operations are all quite * low level, but give you very fine grained control over what is drawn and * where. * * <p> * It is somewhat traditional to call your Context <code>cr</code>. * * <p> * All of the methods on Context take arguments of type <code>double</code> * to represent co-ordinates, angles, colours, transparency levels, etc. * Colours are represented as values between <code>0.0</code> and * <code>0.1</code>, for example: * * <pre> * cr.setSourceRGB(1.0, 0.0, 0.0); * </pre> * * for solid red. In the case of co-ordinates, you can simply specify the * pixel address you wish to move to or draw to: <img src="Context-line.png" * class="snapshot"> * * <pre> * cr.moveTo(10, 10); * cr.lineTo(90, 50); * cr.stroke(); * </pre> * * where stroke draws the current path with the current line thickness. * * <p> * Various other drawing operations are done by creating a shape and then * filling it in: <img src="Context-rectangle.png" class="snapshot"> * * <pre> * cr.rectangle(30, 20, 60, 60); * cr.fill(); * </pre> * * and so on. * * <p> * <i>Obviously this is only the beginning of our documentation for Cairo.</i> * * @author Andrew Cowie * @author Carl Worth * @author Behdad Esfahbod * @author Vreixo Formoso * @since 4.0.7 * @see <a href="http://www.cairographics.org/documentation/">Cairo Graphics * documentation</a> */ public class Context extends Entity { protected Context(long pointer) { super(pointer); } protected void release() { CairoContext.destroy(this); } /** * Construct a new "Cairo Context". You supply the Surface that you are * drawing to. * * @since 4.0.7 */ public Context(Surface target) { super(CairoContext.createContext(target)); } /** * Check the status of the Cairo Context, and fail with an exception if it * is other than SUCCESS. This should be called by each method in our * Cairo bindings. * * <p> * <i>The the fact that errors are not checked for after each operation is * a C API convenience only.</i> */ void checkStatus() { checkStatus(CairoContext.status(this)); } /** * Construct a new "Cairo Context" related to a Drawable. This is the * magic glue which allows you to link between GTK's Widgets and Cairo's * drawing operations. * * <p> * You may find yourself needing to get at the Surface that is being drawn * on. Use {@link #getTarget() getTarget()}. * * <p> * <i>Strictly speaking, this method is a part of GDK. We expose it here * as we are, from the Java bindings' perspective, constructing a Cairo * Context. So a constructor it is.</i> * * @since 4.0.7 */ /* * The function in GdkDrawable is tempting, but since it is not marked as * a constructor, it wants to return an object, not a long. It's also in * the wrong package. We'll leave that be. */ public Context(Drawable drawable) { super(CairoContextOverride.createContextFromDrawable(drawable)); checkStatus(); } /** * Set the source pattern within this Context to an opaque colour. The * parameters each take the range <code>0.0</code> to <code>1.0</code>. * * @since 4.0.7 */ public void setSourceRGB(double red, double green, double blue) { CairoContext.setSourceRgb(this, red, green, blue); checkStatus(); } /** * Set the source pattern within this Context to a translucent colour. The * parameters each take the range <code>0.0</code> to <code>1.0</code>. * For the <code>alpha</code> parameter, a value of <code>0.0</code> * indicates full transparency, and <code>1.0</code> is full opacity * (ie, normal). * * @since 4.0.7 */ public void setSourceRGBA(double red, double green, double blue, double alpha) { CairoContext.setSourceRgba(this, red, green, blue, alpha); checkStatus(); } /** * Add a line from the current location to <code>x</code>,<code>y</code>. * After the call the current point will be <code>x</code>,<code>y</code>. * * @since 4.0.7 */ public void lineTo(double x, double y) { CairoContext.lineTo(this, x, y); checkStatus(); } /** * Set the line width for this Context. This will have effect in next call * to {@link #stroke()}. Default value is <code>2.0</code>. * * @since 4.0.7 */ public void setLineWidth(double width) { CairoContext.setLineWidth(this, width); checkStatus(); } /** * Set the antialiasing mode of the rasterizer used for drawing shapes. * This value is a hint, and a particular backend may or may not support a * particular value. * * @since 4.0.7 */ public void setAntialias(Antialias antialias) { CairoContext.setAntialias(this, antialias); checkStatus(); } /** * Move to a new location without drawing, beginning a new sub-path. After * the call the current point will be <code>x</code>,<code>y</code>. * * @since 4.0.7 */ public void moveTo(double x, double y) { CairoContext.moveTo(this, x, y); checkStatus(); } /** * Draw the current path as a line. * * @since 4.0.7 */ public void stroke() { CairoContext.stroke(this); checkStatus(); } /** * Get the current source Pattern for this Context. * * @since 4.0.7 */ public Pattern getSource() { final Pattern result; result = CairoContext.getSource(this); checkStatus(); - return result; + return CairoPattern.reference(result); } /** * Get the Surface that this Context is drawing on. * * <p> * <i>Yes, this method has a stupid name. It really should be * <code>getSurface()</code>. So many people have a hard time finding * the generic method that allows you to get to the Surface that they're * considering renaming this to <code>cairo_get_surface</code> in Cairo * itself, but until they do, we'll stick with the algorithmic mapping of * <code>cairo_get_target</code>.</i> * * @since 4.0.7 */ public Surface getTarget() { final Surface result; result = CairoContext.getTarget(this); checkStatus(); return result; } /** * Set the operation that will govern forthcoming compositing actions. * * <p> * One particularly useful sequence is clearing the Surface to all * transparent pixels: * * <pre> * cr.setOperator(Operator.CLEAR); * cr.paint(); * </pre> * * @since 4.0.7 */ public void setOperator(Operator op) { CairoContext.setOperator(this, op); checkStatus(); } /** * Paint the current source everywhere within the current clip region. * * @since 4.0.7 */ public void paint() { CairoContext.paint(this); checkStatus(); } /** * Create a Pattern from a Surface, and then use it in this Context. This * is a convenience method. * * <p> * <code>x</code>,<code>y</code> define where, in user-space * coordinates, that the Pattern should appear. * * <p> * You can get the Pattern that was created internally by calling this * with {@link #getSource() getSource()} and manipulate it further if you * need to change the defaults. * * @since 4.0.7 */ public void setSourceSurface(Surface surface, double x, double y) { CairoContext.setSourceSurface(this, surface, x, y); checkStatus(); } /** * Draw a (closed) rectangular sub-path. The rectangle will be at * <code>x</code>,<code>y</code> in user-space coordinates of the * given <code>width</code> and <code>height</code>. * * @since 4.0.7 */ public void rectangle(double x, double y, double width, double height) { CairoContext.rectangle(this, x, y, width, height); checkStatus(); } /** * Adds a circular arc of the given radius to the current path. The arc is * centered at <code>xc,yc</code>, begins at <code>angle1</code> and * proceeds in the direction of increasing angles to end at * <code>angle2</code>. If <code>angle2</code> is less than * <code>angle1</code> it will be progressively increased by * <code>2&pi;</code> until it is greater than <code>angle1</code>. * * <p> * If there is a current point, an initial line segment will be added to * the path to connect the current point to the beginning of the arc. * * <p> * Angles are measured in radians. An angle of <code>0.0</code> is in * the direction of the positive <i>x</i> axis. An angle of * <code>&pi;/2</code> radians (90&deg;) is in the direction of the * positive <i>y</i> axis. Angles increase in the direction from the * positive <i>x</i> axis toward the positive </i> axis, increasing in a * clockwise direction. * * <p> * This function gives the arc in the direction of increasing angles; see * {@link #arcNegative(double, double, double, double, double) arcNegative()} * to go the other direction. * * @since 4.0.7 */ public void arc(double xc, double yc, double radius, double angle1, double angle2) { CairoContext.arc(this, xc, yc, radius, angle1, angle2); checkStatus(); } /** * Adds a circular arc of the given radius to the current path. The arc is * centered at <code>xc,yc</code>, begins at <code>angle1</code> and * proceeds in the direction of decreasing angles to end at * <code>angle2</code>. If <code>angle2</code> is greater than * <code>angle1</code> it will be progressively decreased by * <code>2&pi;</code> until it is less than <code>angle1</code>. * * <p> * See {@link #arc(double, double, double, double, double) arc()} for * drawing in the positive direction. * * @since 4.0.7 */ public void arcNegative(double xc, double yc, double radius, double angle1, double angle2) { CairoContext.arcNegative(this, xc, yc, radius, angle1, angle2); checkStatus(); } /** * Fill the current path, implicitly closing sub-paths first. The drawing * will be done according to the current FillRule. The path will be * cleared after calling <code>fill()</code>; if you want to keep it * use {@link #fillPreserve() fillPreserve()} instead. * * @since 4.0.7 */ public void fill() { CairoContext.fill(this); checkStatus(); } public void fillPreserve() { CairoContext.fillPreserve(this); checkStatus(); } /** * Set a Pattern to be the source of this Context. * * @since 4.0.7 */ public void setSource(Pattern pattern) { CairoContext.setSource(this, pattern); checkStatus(); } /** * Paint the current source using the alpha channel of * <code>pattern</code> as a mask. This means "opaque areas of the mask * will be painted with the source, whereas transparent areas will not be * painted" * * @since 4.0.7 */ public void mask(Pattern pattern) { CairoContext.mask(this, pattern); checkStatus(); } }
true
true
public Pattern getSource() { final Pattern result; result = CairoContext.getSource(this); checkStatus(); return result; }
public Pattern getSource() { final Pattern result; result = CairoContext.getSource(this); checkStatus(); return CairoPattern.reference(result); }
diff --git a/msv/src/com/sun/msv/reader/relax/core/InlineElementState.java b/msv/src/com/sun/msv/reader/relax/core/InlineElementState.java index 397952e0..dbc91358 100644 --- a/msv/src/com/sun/msv/reader/relax/core/InlineElementState.java +++ b/msv/src/com/sun/msv/reader/relax/core/InlineElementState.java @@ -1,118 +1,118 @@ /* * @(#)$Id$ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.relax.core; import com.sun.msv.datatype.BadTypeException; import com.sun.msv.datatype.DataType; import com.sun.msv.datatype.TypeIncubator; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.SimpleNameClass; import com.sun.msv.grammar.relax.ElementRule; import com.sun.msv.grammar.relax.TagClause; import com.sun.msv.grammar.relax.AttPoolClause; import com.sun.msv.reader.State; import com.sun.msv.reader.ExpressionState; import com.sun.msv.reader.datatype.xsd.FacetStateParent; import com.sun.msv.util.StartTagInfo; /** * parses &lt;element&gt; element. * * @author <a href="mailto:[email protected]">Kohsuke KAWAGUCHI</a> */ public class InlineElementState extends ExpressionState implements FacetStateParent { /** this field is set to null if this element has label attribute. */ protected TypeIncubator incubator; public TypeIncubator getIncubator() { return incubator; } protected State createChildState( StartTagInfo tag ) { if( incubator!=null ) return ((RELAXCoreReader)reader).createFacetState(this,tag); // facets else return null; // nothing is allowed when @label is used. } protected void startSelf() { super.startSelf(); String type = startTag.getAttribute("type"); String label = startTag.getAttribute("label"); if( type!=null && label!=null ) reader.reportError( reader.ERR_CONFLICTING_ATTRIBUTES, "type", "label" ); // recover by ignoring one attribute. if( type==null && label==null ) { reader.reportError( reader.ERR_MISSING_ATTRIBUTE_2, "element", "type", "label" ); type="string"; } if( label!=null ) { incubator = null; } else { incubator = new TypeIncubator( reader.resolveDataType(type) ); } } protected Expression makeExpression() { try { final RELAXCoreReader reader = (RELAXCoreReader)this.reader; final String name = startTag.getAttribute("name"); if( name==null ) { reader.reportError( reader.ERR_MISSING_ATTRIBUTE, "element","name" ); // recover by ignoring this element. return Expression.nullSet; } Expression contentModel; if( incubator!=null ) { // @type is used - if( startTag.getAttribute("type").equals("string") && incubator.isEmpty() ) { + if( "string".equals(startTag.getAttribute("type")) && incubator.isEmpty() ) { // we can use cheaper anyString contentModel = Expression.anyString; } else { contentModel = reader.pool.createTypedString( incubator.derive(null) ); } } else { // @label is used String label = startTag.getAttribute("label"); if(label==null) throw new Error(); contentModel = reader.module.hedgeRules.getOrCreate(label); reader.backwardReference.memorizeLink(contentModel); } TagClause c = new TagClause(); c.nameClass = new SimpleNameClass( ((RELAXCoreReader)reader).module.targetNamespace, name ); final String role = startTag.getAttribute("role"); if( role==null ) c.exp = Expression.epsilon; // no attribute else { // role attribute AttPoolClause att = reader.module.attPools.getOrCreate(role); c.exp = att; reader.backwardReference.memorizeLink(att); } // create anonymous ElementRule. this rule will never be added to // RefContainer. return new ElementRule( reader.pool, c, contentModel ); } catch( BadTypeException e ) { // derivation failed reader.reportError( e, reader.ERR_BAD_TYPE, e.getMessage() ); // recover by using harmless expression. anything will do. return Expression.nullSet; } } }
true
true
protected Expression makeExpression() { try { final RELAXCoreReader reader = (RELAXCoreReader)this.reader; final String name = startTag.getAttribute("name"); if( name==null ) { reader.reportError( reader.ERR_MISSING_ATTRIBUTE, "element","name" ); // recover by ignoring this element. return Expression.nullSet; } Expression contentModel; if( incubator!=null ) { // @type is used if( startTag.getAttribute("type").equals("string") && incubator.isEmpty() ) { // we can use cheaper anyString contentModel = Expression.anyString; } else { contentModel = reader.pool.createTypedString( incubator.derive(null) ); } } else { // @label is used String label = startTag.getAttribute("label"); if(label==null) throw new Error(); contentModel = reader.module.hedgeRules.getOrCreate(label); reader.backwardReference.memorizeLink(contentModel); } TagClause c = new TagClause(); c.nameClass = new SimpleNameClass( ((RELAXCoreReader)reader).module.targetNamespace, name ); final String role = startTag.getAttribute("role"); if( role==null ) c.exp = Expression.epsilon; // no attribute else { // role attribute AttPoolClause att = reader.module.attPools.getOrCreate(role); c.exp = att; reader.backwardReference.memorizeLink(att); } // create anonymous ElementRule. this rule will never be added to // RefContainer. return new ElementRule( reader.pool, c, contentModel ); } catch( BadTypeException e ) { // derivation failed reader.reportError( e, reader.ERR_BAD_TYPE, e.getMessage() ); // recover by using harmless expression. anything will do. return Expression.nullSet; } }
protected Expression makeExpression() { try { final RELAXCoreReader reader = (RELAXCoreReader)this.reader; final String name = startTag.getAttribute("name"); if( name==null ) { reader.reportError( reader.ERR_MISSING_ATTRIBUTE, "element","name" ); // recover by ignoring this element. return Expression.nullSet; } Expression contentModel; if( incubator!=null ) { // @type is used if( "string".equals(startTag.getAttribute("type")) && incubator.isEmpty() ) { // we can use cheaper anyString contentModel = Expression.anyString; } else { contentModel = reader.pool.createTypedString( incubator.derive(null) ); } } else { // @label is used String label = startTag.getAttribute("label"); if(label==null) throw new Error(); contentModel = reader.module.hedgeRules.getOrCreate(label); reader.backwardReference.memorizeLink(contentModel); } TagClause c = new TagClause(); c.nameClass = new SimpleNameClass( ((RELAXCoreReader)reader).module.targetNamespace, name ); final String role = startTag.getAttribute("role"); if( role==null ) c.exp = Expression.epsilon; // no attribute else { // role attribute AttPoolClause att = reader.module.attPools.getOrCreate(role); c.exp = att; reader.backwardReference.memorizeLink(att); } // create anonymous ElementRule. this rule will never be added to // RefContainer. return new ElementRule( reader.pool, c, contentModel ); } catch( BadTypeException e ) { // derivation failed reader.reportError( e, reader.ERR_BAD_TYPE, e.getMessage() ); // recover by using harmless expression. anything will do. return Expression.nullSet; } }
diff --git a/src/org/rscdaemon/client/GameImageMiddleMan.java b/src/org/rscdaemon/client/GameImageMiddleMan.java index fe2fb4e..21c742f 100644 --- a/src/org/rscdaemon/client/GameImageMiddleMan.java +++ b/src/org/rscdaemon/client/GameImageMiddleMan.java @@ -1,33 +1,34 @@ package org.rscdaemon.client; import java.awt.*; public final class GameImageMiddleMan extends GameImage { public GameImageMiddleMan(int width, int height, int k, Component component) { super(width, height, k, component); } public final void method245(int i, int j, int k, int l, int i1, int j1, int k1) { + if (i1 == 39999) i1++; // Seems to fix 'Red Dot Bug' if (i1 >= 50000) { _mudclient.method71(i, j, k, l, i1 - 50000, j1, k1); return; } if (i1 >= 40000) { _mudclient.method68(i, j, k, l, i1 - 40000, j1, k1); return; } if (i1 >= 20000) { _mudclient.method45(i, j, k, l, i1 - 20000, j1, k1); return; } if (i1 >= 5000) { _mudclient.method52(i, j, k, l, i1 - 5000, j1, k1); return; } super.spriteClip1(i, j, k, l, i1); } public mudclient _mudclient; }
true
true
public final void method245(int i, int j, int k, int l, int i1, int j1, int k1) { if (i1 >= 50000) { _mudclient.method71(i, j, k, l, i1 - 50000, j1, k1); return; } if (i1 >= 40000) { _mudclient.method68(i, j, k, l, i1 - 40000, j1, k1); return; } if (i1 >= 20000) { _mudclient.method45(i, j, k, l, i1 - 20000, j1, k1); return; } if (i1 >= 5000) { _mudclient.method52(i, j, k, l, i1 - 5000, j1, k1); return; } super.spriteClip1(i, j, k, l, i1); }
public final void method245(int i, int j, int k, int l, int i1, int j1, int k1) { if (i1 == 39999) i1++; // Seems to fix 'Red Dot Bug' if (i1 >= 50000) { _mudclient.method71(i, j, k, l, i1 - 50000, j1, k1); return; } if (i1 >= 40000) { _mudclient.method68(i, j, k, l, i1 - 40000, j1, k1); return; } if (i1 >= 20000) { _mudclient.method45(i, j, k, l, i1 - 20000, j1, k1); return; } if (i1 >= 5000) { _mudclient.method52(i, j, k, l, i1 - 5000, j1, k1); return; } super.spriteClip1(i, j, k, l, i1); }
diff --git a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/internal/services/ResourceBundleHelper.java b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/internal/services/ResourceBundleHelper.java index 791d76c0e..8b9f33835 100644 --- a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/internal/services/ResourceBundleHelper.java +++ b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/internal/services/ResourceBundleHelper.java @@ -1,620 +1,627 @@ /******************************************************************************* * Copyright (c) 2012 Dirk Fauth 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: * Dirk Fauth <[email protected]> - initial API and implementation ******************************************************************************/ package org.eclipse.e4.core.internal.services; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import java.util.ResourceBundle.Control; import org.eclipse.e4.core.services.translation.ResourceBundleProvider; import org.osgi.framework.Bundle; import org.osgi.service.log.LogService; import org.osgi.service.packageadmin.PackageAdmin; /** * Helper class for retrieving {@link ResourceBundle}s out of OSGi {@link Bundle}s. * * @author Dirk Fauth */ // There is no replacement for PackageAdmin#getBundles() @SuppressWarnings("deprecation") public class ResourceBundleHelper { /** * The schema identifier used for Eclipse platform references */ private static final String PLATFORM_SCHEMA = "platform"; //$NON-NLS-1$ /** * The schema identifier used for Eclipse bundle class references */ private static final String BUNDLECLASS_SCHEMA = "bundleclass"; //$NON-NLS-1$ /** * Identifier part of the Eclipse platform schema to point to a plugin */ private static final String PLUGIN_SEGMENT = "/plugin/"; //$NON-NLS-1$ /** * Identifier part of the Eclipse platform schema to point to a fragment */ private static final String FRAGMENT_SEGMENT = "/fragment/"; //$NON-NLS-1$ /** * The separator character for paths in the platform schema */ private static final String PATH_SEPARATOR = "/"; //$NON-NLS-1$ /** * Parses the specified contributor URI and loads the {@link ResourceBundle} for the specified * {@link Locale} out of an OSGi {@link Bundle}. * <p> * Following URIs are supported: * <ul> * <li>platform:/[plugin|fragment]/[Bundle-SymbolicName]<br> * Load the OSGi resource bundle out of the bundle/fragment named [Bundle-SymbolicName]</li> * <li>platform:/[plugin|fragment]/[Bundle-SymbolicName]/[Path]/[Basename]<br> * Load the resource bundle specified by [Path] and [Basename] out of the bundle/fragment named * [Bundle-SymbolicName].</li> * <li>bundleclass://[plugin|fragment]/[Full-Qualified-Classname]<br> * Instantiate the class specified by [Full-Qualified-Classname] out of the bundle/fragment * named [Bundle-SymbolicName]. Note that the class needs to be a subtype of * {@link ResourceBundle}.</li> * </ul> * </p> * * @param contributorURI * The URI that points to a {@link ResourceBundle} * @param locale * The {@link Locale} to use for loading the {@link ResourceBundle} * @param provider * The service for retrieving a {@link ResourceBundle} for a given {@link Locale} out * of the given {@link Bundle} which is specified by URI. * @return */ public static ResourceBundle getResourceBundleForUri(String contributorURI, Locale locale, ResourceBundleProvider provider) { if (contributorURI == null) return null; LogService logService = ServicesActivator.getDefault().getLogService(); URI uri; try { uri = new URI(contributorURI); } catch (URISyntaxException e) { if (logService != null) logService.log(LogService.LOG_ERROR, "Invalid contributor URI: " + contributorURI); //$NON-NLS-1$ return null; } String bundleName = null; Bundle bundle = null; String resourcePath = null; String classPath = null; // the uri follows the platform schema, so we search for .properties files in the bundle if (PLATFORM_SCHEMA.equals(uri.getScheme())) { bundleName = uri.getPath(); if (bundleName.startsWith(PLUGIN_SEGMENT)) bundleName = bundleName.substring(PLUGIN_SEGMENT.length()); else if (bundleName.startsWith(FRAGMENT_SEGMENT)) bundleName = bundleName.substring(FRAGMENT_SEGMENT.length()); resourcePath = ""; //$NON-NLS-1$ if (bundleName.contains(PATH_SEPARATOR)) { resourcePath = bundleName.substring(bundleName.indexOf(PATH_SEPARATOR) + 1); bundleName = bundleName.substring(0, bundleName.indexOf(PATH_SEPARATOR)); } } else if (BUNDLECLASS_SCHEMA.equals(uri.getScheme())) { if (uri.getAuthority() == null) { if (logService != null) logService.log(LogService.LOG_ERROR, "Failed to get bundle for: " + contributorURI); //$NON-NLS-1$ } bundleName = uri.getAuthority(); // remove the leading / - classPath = uri.getPath().substring(1); + if (uri.getPath() != null && uri.getPath().length() > 0) { + classPath = uri.getPath().substring(1); + } else { + if (logService != null) { + logService.log(LogService.LOG_ERROR, "Called with invalid contributor URI: " + + contributorURI); + } + } } ResourceBundle result = null; if (bundleName != null) { bundle = getBundleForName(bundleName); if (bundle != null) { if (resourcePath == null && classPath != null) { // the URI points to a class within the bundle classpath // therefore we are trying to instantiate the class try { Class<?> resourceBundleClass = bundle.loadClass(classPath); result = getEquinoxResourceBundle(classPath, locale, resourceBundleClass.getClassLoader()); } catch (Exception e) { if (logService != null) logService .log(LogService.LOG_ERROR, "Failed to load specified ResourceBundle: " + contributorURI, e); //$NON-NLS-1$ } - } else if (resourcePath.length() > 0) { + } else if (resourcePath != null && resourcePath.length() > 0) { // the specified URI points to a resource // therefore we try to load the .properties files into a ResourceBundle result = getEquinoxResourceBundle(resourcePath.replace('.', '/'), locale, bundle); } else { // There is no class and no special resource specified within the URI // therefore we load the OSresource bundle out of the specified Bundle // for the current Locale. Typically this will be the OSGi ResourceBundle result = provider.getResourceBundle(bundle, locale.toString()); } } } return result; } /** * This method searches for the {@link ResourceBundle} in a modified way by inspecting the * configuration option <code>equinox.root.locale</code>. * <p> * If the value for this system property is set to an empty String the default search order for * ResourceBundles is used: * <ul> * <li>bn + Ls + "_" + Cs + "_" + Vs</li> * <li>bn + Ls + "_" + Cs</li> * <li>bn + Ls</li> * <li>bn + Ld + "_" + Cd + "_" + Vd</li> * <li>bn + Ld + "_" + Cd</li> * <li>bn + Ld</li> * <li>bn</li> * </ul> * Where bn is this bundle's localization basename, Ls, Cs and Vs are the specified locale * (language, country, variant) and Ld, Cd and Vd are the default locale (language, country, * variant). * </p> * <p> * If Ls equals the value of <code>equinox.root.locale</code> then the following search order is * used: * <ul> * <li>bn + Ls + "_" + Cs + "_" + Vs</li> * <li>bn + Ls + "_" + Cs</li> * <li>bn + Ls</li> * <li>bn</li> * <li>bn + Ld + "_" + Cd + "_" + Vd</li> * <li>bn + Ld + "_" + Cd</li> * <li>bn + Ld</li> * <li>bn</li> * </ul> * </p> * If <code>equinox.root.locale=en</code> and en_XX or en is asked for then this allows the root * file to be used instead of falling back to the default locale. * * @param baseName * the base name of the resource bundle, a fully qualified class name * @param locale * the locale for which a resource bundle is desired * @param loader * the class loader from which to load the resource bundle * @return a resource bundle for the given base name and locale * * @see ResourceBundle#getBundle(String, Locale, ClassLoader) */ public static ResourceBundle getEquinoxResourceBundle(String baseName, Locale locale, ClassLoader loader) { ResourceBundle resourceBundle = null; String equinoxLocale = getEquinoxRootLocale(); // if the equinox.root.locale is not empty and the specified locale equals the // equinox.root.locale // -> use the special search order if (equinoxLocale.length() > 0 && locale.toString().startsWith(equinoxLocale)) { // there is a equinox.root.locale configured that matches the specified locale // so the special search order is used // to achieve this we first search without a fallback to the default locale try { resourceBundle = ResourceBundle.getBundle(baseName, locale, loader, ResourceBundle.Control.getNoFallbackControl(Control.FORMAT_DEFAULT)); } catch (MissingResourceException e) { // do nothing } // if there is no ResourceBundle found for that path, we will now search for the default // locale ResourceBundle if (resourceBundle == null) { try { resourceBundle = ResourceBundle.getBundle(baseName, Locale.getDefault(), loader, ResourceBundle.Control.getNoFallbackControl(Control.FORMAT_DEFAULT)); } catch (MissingResourceException e) { // do nothing } } } else { // there is either no equinox.root.locale configured or it does not match the specified // locale // -> use the default search order try { resourceBundle = ResourceBundle.getBundle(baseName, locale, loader); } catch (MissingResourceException e) { // do nothing } } return resourceBundle; } /** * This method searches for the {@link ResourceBundle} in a modified way by inspecting the * configuration option <code>equinox.root.locale</code>. It uses the * {@link BundleResourceBundleControl} to load the resources out of a {@link Bundle}. * <p> * <b>Note: This method will only search for ResourceBundles based on properties files.</b> * </p> * <p> * If the value for this system property is set to an empty String the default search order for * ResourceBundles is used: * <ul> * <li>bn + Ls + "_" + Cs + "_" + Vs</li> * <li>bn + Ls + "_" + Cs</li> * <li>bn + Ls</li> * <li>bn + Ld + "_" + Cd + "_" + Vd</li> * <li>bn + Ld + "_" + Cd</li> * <li>bn + Ld</li> * <li>bn</li> * </ul> * Where bn is this bundle's localization basename, Ls, Cs and Vs are the specified locale * (language, country, variant) and Ld, Cd and Vd are the default locale (language, country, * variant). * </p> * <p> * If Ls equals the value of <code>equinox.root.locale</code> then the following search order is * used: * <ul> * <li>bn + Ls + "_" + Cs + "_" + Vs</li> * <li>bn + Ls + "_" + Cs</li> * <li>bn + Ls</li> * <li>bn</li> * <li>bn + Ld + "_" + Cd + "_" + Vd</li> * <li>bn + Ld + "_" + Cd</li> * <li>bn + Ld</li> * <li>bn</li> * </ul> * </p> * If <code>equinox.root.locale=en</code> and en_XX or en is asked for then this allows the root * file to be used instead of falling back to the default locale. * * @param baseName * the base name of the resource bundle, a fully qualified class name * @param locale * the locale for which a resource bundle is desired * @param bundle * The OSGi {@link Bundle} to lookup the {@link ResourceBundle} * @return a resource bundle for the given base name and locale * * @see ResourceBundle#getBundle(String, Locale, Control) */ public static ResourceBundle getEquinoxResourceBundle(String baseName, Locale locale, Bundle bundle) { return getEquinoxResourceBundle(baseName, locale, new BundleResourceBundleControl(bundle, true), new BundleResourceBundleControl(bundle, false)); } /** * This method searches for the {@link ResourceBundle} in a modified way by inspecting the * configuration option <code>equinox.root.locale</code>. * <p> * <b>Note: This method will only search for ResourceBundles based on properties files.</b> * </p> * <p> * If the value for this system property is set to an empty String the default search order for * ResourceBundles is used: * <ul> * <li>bn + Ls + "_" + Cs + "_" + Vs</li> * <li>bn + Ls + "_" + Cs</li> * <li>bn + Ls</li> * <li>bn + Ld + "_" + Cd + "_" + Vd</li> * <li>bn + Ld + "_" + Cd</li> * <li>bn + Ld</li> * <li>bn</li> * </ul> * Where bn is this bundle's localization basename, Ls, Cs and Vs are the specified locale * (language, country, variant) and Ld, Cd and Vd are the default locale (language, country, * variant). * </p> * <p> * If Ls equals the value of <code>equinox.root.locale</code> then the following search order is * used: * <ul> * <li>bn + Ls + "_" + Cs + "_" + Vs</li> * <li>bn + Ls + "_" + Cs</li> * <li>bn + Ls</li> * <li>bn</li> * <li>bn + Ld + "_" + Cd + "_" + Vd</li> * <li>bn + Ld + "_" + Cd</li> * <li>bn + Ld</li> * <li>bn</li> * </ul> * </p> * If <code>equinox.root.locale=en</code> and en_XX or en is asked for then this allows the root * file to be used instead of falling back to the default locale. * * @param baseName * the base name of the resource bundle, a fully qualified class name * @param locale * the locale for which a resource bundle is desired * @param withFallback * The {@link Control} that uses the default locale fallback on searching for * resource bundles. * @param withoutFallback * The {@link Control} that doesn't use the default locale fallback on searching for * resource bundles. * @return a resource bundle for the given base name and locale * * @see ResourceBundle#getBundle(String, Locale, Control) */ public static ResourceBundle getEquinoxResourceBundle(String baseName, Locale locale, Control withFallback, Control withoutFallback) { ResourceBundle resourceBundle = null; String equinoxLocale = getEquinoxRootLocale(); // if the equinox.root.locale is not empty and the specified locale equals the // equinox.root.locale // -> use the special search order if (equinoxLocale.length() > 0 && locale.toString().startsWith(equinoxLocale)) { // there is a equinox.root.locale configured that matches the specified locale // so the special search order is used // to achieve this we first search without a fallback to the default locale try { resourceBundle = ResourceBundle.getBundle(baseName, locale, withoutFallback); } catch (MissingResourceException e) { // do nothing } // if there is no ResourceBundle found for that path, we will now search for the default // locale ResourceBundle if (resourceBundle == null) { try { resourceBundle = ResourceBundle.getBundle(baseName, Locale.getDefault(), withoutFallback); } catch (MissingResourceException e) { // do nothing } } } else { // there is either no equinox.root.locale configured or it does not match the specified // locale // -> use the default search order try { resourceBundle = ResourceBundle.getBundle(baseName, locale, withFallback); } catch (MissingResourceException e) { // do nothing } } return resourceBundle; } /** * @return The value for the system property for key <code>equinox.root.locale</code>. If none * is specified than <b>en</b> will be returned as default. */ private static String getEquinoxRootLocale() { // Logic from FrameworkProperties.getProperty("equinox.root.locale", "en") String root = System.getProperties().getProperty("equinox.root.locale"); //$NON-NLS-1$ if (root == null) { root = "en"; //$NON-NLS-1$ } return root; } /** * This method is copied out of org.eclipse.e4.ui.internal.workbench.Activator because as it is * a internal resource, it is not accessible for us. * * @param bundleName * the bundle id * @return A bundle if found, or <code>null</code> */ public static Bundle getBundleForName(String bundleName) { PackageAdmin packageAdmin = ServicesActivator.getDefault().getPackageAdmin(); Bundle[] bundles = packageAdmin.getBundles(bundleName, null); if (bundles == null) return null; // Return the first bundle that is not installed or uninstalled for (int i = 0; i < bundles.length; i++) { if ((bundles[i].getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) { return bundles[i]; } } return null; } /** * <p> * Converts a String to a Locale. * </p> * * <p> * This method takes the string format of a locale and creates the locale object from it. * </p> * * <pre> * MessageFactoryServiceImpl.toLocale("en") = new Locale("en", "") * MessageFactoryServiceImpl.toLocale("en_GB") = new Locale("en", "GB") * MessageFactoryServiceImpl.toLocale("en_GB_xxx") = new Locale("en", "GB", "xxx") * </pre> * * <p> * This method validates the input strictly. The language code must be lowercase. The country * code must be uppercase. The separator must be an underscore. The length must be correct. * </p> * * <p> * This method is inspired by <code>org.apache.commons.lang.LocaleUtils.toLocale(String)</code> * by fixing the parsing error for uncommon Locales like having a language and a variant code * but no country code, or a Locale that only consists of a country code. * </p> * * @param str * the locale String to convert * @return a Locale that matches the specified locale String or <code>null</code> if the * specified String is <code>null</code> * @throws IllegalArgumentException * if the String is an invalid format */ public static Locale toLocale(String str) { if (str == null) { return null; } String language = ""; //$NON-NLS-1$ String country = ""; //$NON-NLS-1$ String variant = ""; //$NON-NLS-1$ String[] localeParts = str.split("_"); //$NON-NLS-1$ if (localeParts.length == 0 || localeParts.length > 3 || (localeParts.length == 1 && localeParts[0].length() == 0)) { throw new IllegalArgumentException("Invalid locale format: " + str); //$NON-NLS-1$ } else { if (localeParts[0].length() == 1 || localeParts[0].length() > 2) { throw new IllegalArgumentException("Invalid locale format: " + str); //$NON-NLS-1$ } else if (localeParts[0].length() == 2) { char ch0 = localeParts[0].charAt(0); char ch1 = localeParts[0].charAt(1); if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { throw new IllegalArgumentException("Invalid locale format: " + str); //$NON-NLS-1$ } } language = localeParts[0]; if (localeParts.length > 1) { if (localeParts[1].length() == 1 || localeParts[1].length() > 2) { throw new IllegalArgumentException("Invalid locale format: " + str); //$NON-NLS-1$ } else if (localeParts[1].length() == 2) { char ch3 = localeParts[1].charAt(0); char ch4 = localeParts[1].charAt(1); if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { throw new IllegalArgumentException("Invalid locale format: " + str); //$NON-NLS-1$ } } country = localeParts[1]; } if (localeParts.length == 3) { if (localeParts[0].length() == 0 && localeParts[1].length() == 0) { throw new IllegalArgumentException("Invalid locale format: " + str); //$NON-NLS-1$ } variant = localeParts[2]; } } return new Locale(language, country, variant); } /** * Specialization of {@link Control} which loads the {@link ResourceBundle} out of an OSGi * {@link Bundle} instead of using a classloader. * * <p> * It only supports properties based {@link ResourceBundle}s. If you want to use source based * {@link ResourceBundle}s you have to use the bundleclass URI with the Message annotation. * * @author Dirk Fauth * */ static class BundleResourceBundleControl extends ResourceBundle.Control { /** * Flag to determine whether the default locale should be used as fallback locale in case * there is no {@link ResourceBundle} found for the specified locale. */ private final boolean useFallback; /** * The OSGi {@link Bundle} to lookup the {@link ResourceBundle} */ private final Bundle osgiBundle; /** * * @param osgiBundle * The OSGi {@link Bundle} to lookup the {@link ResourceBundle} * @param useFallback * <code>true</code> if the default locale should be used as fallback locale in * the search path or <code>false</code> if there should be no fallback. */ public BundleResourceBundleControl(Bundle osgiBundle, boolean useFallback) { this.osgiBundle = osgiBundle; this.useFallback = useFallback; } @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { String bundleName = toBundleName(baseName, locale); ResourceBundle bundle = null; if (format.equals("java.properties")) { //$NON-NLS-1$ final String resourceName = toResourceName(bundleName, "properties"); //$NON-NLS-1$ InputStream stream = null; try { stream = AccessController .doPrivileged(new PrivilegedExceptionAction<InputStream>() { public InputStream run() throws IOException { InputStream is = null; URL url = osgiBundle.getEntry(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { // Disable caches to get fresh data for // reloading. connection.setUseCaches(false); is = connection.getInputStream(); } } return is; } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } if (stream != null) { try { bundle = new PropertyResourceBundle(stream); } finally { stream.close(); } } } else { throw new IllegalArgumentException("unknown format: " + format); //$NON-NLS-1$ } return bundle; } @Override public List<String> getFormats(String baseName) { return FORMAT_PROPERTIES; } @Override public Locale getFallbackLocale(String baseName, Locale locale) { return this.useFallback ? super.getFallbackLocale(baseName, locale) : null; } } }
false
true
public static ResourceBundle getResourceBundleForUri(String contributorURI, Locale locale, ResourceBundleProvider provider) { if (contributorURI == null) return null; LogService logService = ServicesActivator.getDefault().getLogService(); URI uri; try { uri = new URI(contributorURI); } catch (URISyntaxException e) { if (logService != null) logService.log(LogService.LOG_ERROR, "Invalid contributor URI: " + contributorURI); //$NON-NLS-1$ return null; } String bundleName = null; Bundle bundle = null; String resourcePath = null; String classPath = null; // the uri follows the platform schema, so we search for .properties files in the bundle if (PLATFORM_SCHEMA.equals(uri.getScheme())) { bundleName = uri.getPath(); if (bundleName.startsWith(PLUGIN_SEGMENT)) bundleName = bundleName.substring(PLUGIN_SEGMENT.length()); else if (bundleName.startsWith(FRAGMENT_SEGMENT)) bundleName = bundleName.substring(FRAGMENT_SEGMENT.length()); resourcePath = ""; //$NON-NLS-1$ if (bundleName.contains(PATH_SEPARATOR)) { resourcePath = bundleName.substring(bundleName.indexOf(PATH_SEPARATOR) + 1); bundleName = bundleName.substring(0, bundleName.indexOf(PATH_SEPARATOR)); } } else if (BUNDLECLASS_SCHEMA.equals(uri.getScheme())) { if (uri.getAuthority() == null) { if (logService != null) logService.log(LogService.LOG_ERROR, "Failed to get bundle for: " + contributorURI); //$NON-NLS-1$ } bundleName = uri.getAuthority(); // remove the leading / classPath = uri.getPath().substring(1); } ResourceBundle result = null; if (bundleName != null) { bundle = getBundleForName(bundleName); if (bundle != null) { if (resourcePath == null && classPath != null) { // the URI points to a class within the bundle classpath // therefore we are trying to instantiate the class try { Class<?> resourceBundleClass = bundle.loadClass(classPath); result = getEquinoxResourceBundle(classPath, locale, resourceBundleClass.getClassLoader()); } catch (Exception e) { if (logService != null) logService .log(LogService.LOG_ERROR, "Failed to load specified ResourceBundle: " + contributorURI, e); //$NON-NLS-1$ } } else if (resourcePath.length() > 0) { // the specified URI points to a resource // therefore we try to load the .properties files into a ResourceBundle result = getEquinoxResourceBundle(resourcePath.replace('.', '/'), locale, bundle); } else { // There is no class and no special resource specified within the URI // therefore we load the OSresource bundle out of the specified Bundle // for the current Locale. Typically this will be the OSGi ResourceBundle result = provider.getResourceBundle(bundle, locale.toString()); } } } return result; }
public static ResourceBundle getResourceBundleForUri(String contributorURI, Locale locale, ResourceBundleProvider provider) { if (contributorURI == null) return null; LogService logService = ServicesActivator.getDefault().getLogService(); URI uri; try { uri = new URI(contributorURI); } catch (URISyntaxException e) { if (logService != null) logService.log(LogService.LOG_ERROR, "Invalid contributor URI: " + contributorURI); //$NON-NLS-1$ return null; } String bundleName = null; Bundle bundle = null; String resourcePath = null; String classPath = null; // the uri follows the platform schema, so we search for .properties files in the bundle if (PLATFORM_SCHEMA.equals(uri.getScheme())) { bundleName = uri.getPath(); if (bundleName.startsWith(PLUGIN_SEGMENT)) bundleName = bundleName.substring(PLUGIN_SEGMENT.length()); else if (bundleName.startsWith(FRAGMENT_SEGMENT)) bundleName = bundleName.substring(FRAGMENT_SEGMENT.length()); resourcePath = ""; //$NON-NLS-1$ if (bundleName.contains(PATH_SEPARATOR)) { resourcePath = bundleName.substring(bundleName.indexOf(PATH_SEPARATOR) + 1); bundleName = bundleName.substring(0, bundleName.indexOf(PATH_SEPARATOR)); } } else if (BUNDLECLASS_SCHEMA.equals(uri.getScheme())) { if (uri.getAuthority() == null) { if (logService != null) logService.log(LogService.LOG_ERROR, "Failed to get bundle for: " + contributorURI); //$NON-NLS-1$ } bundleName = uri.getAuthority(); // remove the leading / if (uri.getPath() != null && uri.getPath().length() > 0) { classPath = uri.getPath().substring(1); } else { if (logService != null) { logService.log(LogService.LOG_ERROR, "Called with invalid contributor URI: " + contributorURI); } } } ResourceBundle result = null; if (bundleName != null) { bundle = getBundleForName(bundleName); if (bundle != null) { if (resourcePath == null && classPath != null) { // the URI points to a class within the bundle classpath // therefore we are trying to instantiate the class try { Class<?> resourceBundleClass = bundle.loadClass(classPath); result = getEquinoxResourceBundle(classPath, locale, resourceBundleClass.getClassLoader()); } catch (Exception e) { if (logService != null) logService .log(LogService.LOG_ERROR, "Failed to load specified ResourceBundle: " + contributorURI, e); //$NON-NLS-1$ } } else if (resourcePath != null && resourcePath.length() > 0) { // the specified URI points to a resource // therefore we try to load the .properties files into a ResourceBundle result = getEquinoxResourceBundle(resourcePath.replace('.', '/'), locale, bundle); } else { // There is no class and no special resource specified within the URI // therefore we load the OSresource bundle out of the specified Bundle // for the current Locale. Typically this will be the OSGi ResourceBundle result = provider.getResourceBundle(bundle, locale.toString()); } } } return result; }
diff --git a/Server/ChatServer.java b/Server/ChatServer.java index 3ccae80..b247f23 100644 --- a/Server/ChatServer.java +++ b/Server/ChatServer.java @@ -1,26 +1,26 @@ import java.net.ServerSocket; import java.io.IOException; public class ChatServer { private ServerSocket socket; public ChatServer(int port) { try { socket = new ServerSocket(port); } catch(IOException e) { System.err.println("error: " + e); } } public void listen() { while(true) { try { - new ClientHandler(socket.accept()); + new ClientHandler(socket.accept()).start(); } catch(IOException e) { System.err.println("error: " + e); } } } }
true
true
public void listen() { while(true) { try { new ClientHandler(socket.accept()); } catch(IOException e) { System.err.println("error: " + e); } } }
public void listen() { while(true) { try { new ClientHandler(socket.accept()).start(); } catch(IOException e) { System.err.println("error: " + e); } } }
diff --git a/src/tconstruct/blocks/logic/PartBuilderLogic.java b/src/tconstruct/blocks/logic/PartBuilderLogic.java index 07a7924ee..ae643d325 100644 --- a/src/tconstruct/blocks/logic/PartBuilderLogic.java +++ b/src/tconstruct/blocks/logic/PartBuilderLogic.java @@ -1,182 +1,180 @@ package tconstruct.blocks.logic; import tconstruct.inventory.PartCrafterChestContainer; import tconstruct.inventory.PartCrafterContainer; import tconstruct.library.blocks.InventoryLogic; import tconstruct.library.crafting.PatternBuilder; import tconstruct.library.util.IPattern; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; public class PartBuilderLogic extends InventoryLogic implements ISidedInventory { boolean craftedTop; boolean craftedBottom; public PartBuilderLogic() { super(10); craftedTop = false; craftedBottom = false; } @Override public String getDefaultName () { return "toolstation.parts"; } @Override public Container getGuiContainer (InventoryPlayer inventoryplayer, World world, int x, int y, int z) { for (int xPos = x - 1; xPos <= x + 1; xPos++) { for (int zPos = z - 1; zPos <= z + 1; zPos++) { TileEntity tile = world.getBlockTileEntity(xPos, y, zPos); if (tile != null && tile instanceof PatternChestLogic) return new PartCrafterChestContainer(inventoryplayer, this, (PatternChestLogic) tile); } } return new PartCrafterContainer(inventoryplayer, this); } //Called when emptying a slot, not when another item is placed in it public ItemStack decrStackSize (int slotID, int quantity) { ItemStack returnStack = super.decrStackSize(slotID, quantity); tryBuildPart(slotID); return returnStack; } public void tryBuildPart (int slotID) { if (slotID == 4 || slotID == 5) { if (!craftedTop && inventory[0] != null) { int value = PatternBuilder.instance.getPartValue(inventory[2]); - if (value == 0) /* hack to plug up future dups */ - value = 2; IPattern item = (IPattern) inventory[0].getItem(); int cost = item != null ? item.getPatternCost(inventory[0]) : 0; if (value > 0 && cost > 0) { int decrease = cost / value; if (cost % value != 0) decrease++; super.decrStackSize(2, decrease); //Call super to avoid crafting again } } if (inventory[4] != null || inventory[5] != null) craftedTop = true; else craftedTop = false; } if (!craftedTop) buildTopPart(); if (slotID == 6 || slotID == 7) { if (!craftedBottom && inventory[1] != null) { int value = PatternBuilder.instance.getPartValue(inventory[3]); IPattern item = (IPattern) inventory[1].getItem(); int cost = item != null ? item.getPatternCost(inventory[1]) : 0; if (value > 0 && cost > 0) { int decrease = cost / value; if (cost % value != 0) decrease++; super.decrStackSize(3, decrease); //Call super to avoid crafting again } } if (inventory[6] != null || inventory[7] != null) craftedBottom = true; else craftedBottom = false; } if (!craftedBottom) buildBottomPart(); } //Called when a slot has something placed into it. public void setInventorySlotContents (int slot, ItemStack itemstack) { super.setInventorySlotContents(slot, itemstack); if ((slot == 0 || slot == 2) && !craftedTop) buildTopPart(); if ((slot == 1 || slot == 3) && !craftedBottom) buildBottomPart(); } void buildTopPart () { ItemStack[] parts = PatternBuilder.instance.getToolPart(inventory[2], inventory[0], inventory[1]); if (parts != null) { inventory[4] = parts[0]; inventory[5] = parts[1]; } else { inventory[4] = inventory[5] = null; } } void buildBottomPart () { ItemStack[] parts = PatternBuilder.instance.getToolPart(inventory[3], inventory[1], inventory[0]); if (parts != null) { inventory[6] = parts[0]; inventory[7] = parts[1]; } else { inventory[6] = inventory[7] = null; } } /* NBT */ public void readFromNBT (NBTTagCompound tags) { super.readFromNBT(tags); craftedTop = tags.getBoolean("CraftedTop"); craftedBottom = tags.getBoolean("CraftedBottom"); } public void writeToNBT (NBTTagCompound tags) { super.writeToNBT(tags); tags.setBoolean("CraftedTop", craftedTop); tags.setBoolean("CraftedBottom", craftedBottom); } @Override public int[] getAccessibleSlotsFromSide (int side) { return new int[0]; } @Override public boolean canInsertItem (int i, ItemStack itemstack, int j) { return false; } @Override public boolean canExtractItem (int i, ItemStack itemstack, int j) { return false; } }
true
true
public void tryBuildPart (int slotID) { if (slotID == 4 || slotID == 5) { if (!craftedTop && inventory[0] != null) { int value = PatternBuilder.instance.getPartValue(inventory[2]); if (value == 0) /* hack to plug up future dups */ value = 2; IPattern item = (IPattern) inventory[0].getItem(); int cost = item != null ? item.getPatternCost(inventory[0]) : 0; if (value > 0 && cost > 0) { int decrease = cost / value; if (cost % value != 0) decrease++; super.decrStackSize(2, decrease); //Call super to avoid crafting again } } if (inventory[4] != null || inventory[5] != null) craftedTop = true; else craftedTop = false; } if (!craftedTop) buildTopPart(); if (slotID == 6 || slotID == 7) { if (!craftedBottom && inventory[1] != null) { int value = PatternBuilder.instance.getPartValue(inventory[3]); IPattern item = (IPattern) inventory[1].getItem(); int cost = item != null ? item.getPatternCost(inventory[1]) : 0; if (value > 0 && cost > 0) { int decrease = cost / value; if (cost % value != 0) decrease++; super.decrStackSize(3, decrease); //Call super to avoid crafting again } } if (inventory[6] != null || inventory[7] != null) craftedBottom = true; else craftedBottom = false; } if (!craftedBottom) buildBottomPart(); }
public void tryBuildPart (int slotID) { if (slotID == 4 || slotID == 5) { if (!craftedTop && inventory[0] != null) { int value = PatternBuilder.instance.getPartValue(inventory[2]); IPattern item = (IPattern) inventory[0].getItem(); int cost = item != null ? item.getPatternCost(inventory[0]) : 0; if (value > 0 && cost > 0) { int decrease = cost / value; if (cost % value != 0) decrease++; super.decrStackSize(2, decrease); //Call super to avoid crafting again } } if (inventory[4] != null || inventory[5] != null) craftedTop = true; else craftedTop = false; } if (!craftedTop) buildTopPart(); if (slotID == 6 || slotID == 7) { if (!craftedBottom && inventory[1] != null) { int value = PatternBuilder.instance.getPartValue(inventory[3]); IPattern item = (IPattern) inventory[1].getItem(); int cost = item != null ? item.getPatternCost(inventory[1]) : 0; if (value > 0 && cost > 0) { int decrease = cost / value; if (cost % value != 0) decrease++; super.decrStackSize(3, decrease); //Call super to avoid crafting again } } if (inventory[6] != null || inventory[7] != null) craftedBottom = true; else craftedBottom = false; } if (!craftedBottom) buildBottomPart(); }
diff --git a/src/uk/org/whoami/easyban/tasks/UnbanTask.java b/src/uk/org/whoami/easyban/tasks/UnbanTask.java index 467c35a..1758e68 100644 --- a/src/uk/org/whoami/easyban/tasks/UnbanTask.java +++ b/src/uk/org/whoami/easyban/tasks/UnbanTask.java @@ -1,47 +1,47 @@ /* * Copyright 2011 Sebastian Köhler <[email protected]>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.org.whoami.easyban.tasks; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import uk.org.whoami.easyban.ConsoleLogger; import uk.org.whoami.easyban.datasource.DataSource; public class UnbanTask implements Runnable { private DataSource data; public UnbanTask(DataSource data) { this.data = data; } @Override public void run() { Calendar cal = Calendar.getInstance(); HashMap<String,Long> tmpBans = data.getTempBans(); Iterator<String> it = tmpBans.keySet().iterator(); while(it.hasNext()) { String name = it.next(); if(tmpBans.get(name) != 100000 && (cal.getTimeInMillis() > tmpBans.get(name))) { data.unbanNick(name); - ConsoleLogger.info("Temporary for "+ name +" ban has been removed"); + ConsoleLogger.info("Temporary ban for "+ name +" has been removed"); } } } }
true
true
public void run() { Calendar cal = Calendar.getInstance(); HashMap<String,Long> tmpBans = data.getTempBans(); Iterator<String> it = tmpBans.keySet().iterator(); while(it.hasNext()) { String name = it.next(); if(tmpBans.get(name) != 100000 && (cal.getTimeInMillis() > tmpBans.get(name))) { data.unbanNick(name); ConsoleLogger.info("Temporary for "+ name +" ban has been removed"); } } }
public void run() { Calendar cal = Calendar.getInstance(); HashMap<String,Long> tmpBans = data.getTempBans(); Iterator<String> it = tmpBans.keySet().iterator(); while(it.hasNext()) { String name = it.next(); if(tmpBans.get(name) != 100000 && (cal.getTimeInMillis() > tmpBans.get(name))) { data.unbanNick(name); ConsoleLogger.info("Temporary ban for "+ name +" has been removed"); } } }
diff --git a/src/main/java/de/Keyle/MyPet/gui/skilltreecreator/LevelCreator.java b/src/main/java/de/Keyle/MyPet/gui/skilltreecreator/LevelCreator.java index 3687e6c5f..67c03850f 100644 --- a/src/main/java/de/Keyle/MyPet/gui/skilltreecreator/LevelCreator.java +++ b/src/main/java/de/Keyle/MyPet/gui/skilltreecreator/LevelCreator.java @@ -1,656 +1,657 @@ /* * This file is part of MyPet * * Copyright (C) 2011-2013 Keyle * MyPet is licensed under the GNU Lesser General Public License. * * MyPet 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. * * MyPet 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 de.Keyle.MyPet.gui.skilltreecreator; import de.Keyle.MyPet.gui.GuiMain; import de.Keyle.MyPet.skill.*; import de.Keyle.MyPet.skill.skills.info.ISkillInfo; import de.Keyle.MyPet.util.MyPetUtil; import de.Keyle.MyPet.util.MyPetVersion; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.*; import java.util.*; public class LevelCreator { JTree skillTreeTree; JLabel skillTreeNameLabel; JButton deleteLevelSkillButton; JButton addLevelButton; JButton addSkillButton; JComboBox inheritanceComboBox; JCheckBox inheritanceCheckBox; JPanel levelCreatorPanel; JButton backButton; JLabel mobTypeLabel; JTable skillCounterTabel; JLabel skilllevelLabel; JButton copyButton; JTextField permissionDisplayTextField; JCheckBox displayNameCheckbox; JCheckBox permissionCheckbox; JTextField displayNameTextField; JTextField permissionTextField; JFrame levelCreatorFrame; DefaultTableModel skillCounterTabelModel; DefaultTreeModel skillTreeTreeModel; DefaultComboBoxModel inheritanceComboBoxModel; MyPetSkillTree skillTree; MyPetSkillTreeMobType skillTreeMobType; private static String[] skillNames = new String[]{"Beacon", "Behavior", "Control", "Damage", "Fire", "HP", "HPregeneration", "Inventory", "Knockback", "Lightning", "Pickup", "Poison", "Ranged", "Ride", "Slow", "Sprint", "Thorns", "Wither"}; public LevelCreator() { addLevelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String response = JOptionPane.showInputDialog(null, "Enter the number for the new level.", "Create new Level", JOptionPane.QUESTION_MESSAGE); if (response != null) { if (MyPetUtil.isInt(response)) { int newLevel = Integer.parseInt(response); for (int i = 0 ; i < skillTreeTreeModel.getChildCount(skillTreeTreeModel.getRoot()) ; i++) { if (MyPetUtil.isInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString())) { int level = Integer.parseInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString()); if (newLevel == level) { JOptionPane.showMessageDialog(null, response + " already exists!", "Create new Level", JOptionPane.ERROR_MESSAGE); return; } else if (newLevel < 1) { JOptionPane.showMessageDialog(null, response + " is smaller than 1!", "Create new Level", JOptionPane.ERROR_MESSAGE); return; } } } DefaultMutableTreeNode levelNode = new DefaultMutableTreeNode(newLevel); skillTree.addLevel(newLevel); ((SortedDefaultMutableTreeNode) skillTreeTreeModel.getRoot()).add(levelNode); skillTreeTree.expandPath(skillTreeTree.getSelectionPath()); skillTreeTree.updateUI(); } else { JOptionPane.showMessageDialog(null, response + " is not a number!", "Create new Level", JOptionPane.ERROR_MESSAGE); } } countSkillLevels(); } }); addSkillButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int level; if (skillTreeTree.getSelectionPath().getPath().length == 2 || skillTreeTree.getSelectionPath().getPath().length == 3) { if (MyPetUtil.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString())) { level = Integer.parseInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()); } else { return; } } else { return; } String choosenSkill = (String) JOptionPane.showInputDialog(null, "Please select the skill you want to add to level " + level + '.', "", JOptionPane.QUESTION_MESSAGE, null, skillNames, ""); if (choosenSkill != null) { ISkillInfo skill = MyPetSkillsInfo.getNewSkillInfoInstance(choosenSkill); skillTree.addSkillToLevel(level, skill); SkillTreeSkillNode skillNode = new SkillTreeSkillNode(skill); skill.setDefaultProperties(); ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).add(skillNode); skillTreeTree.expandPath(skillTreeTree.getSelectionPath()); skillTreeTree.updateUI(); } countSkillLevels(); } }); deleteLevelSkillButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (skillTreeTree.getSelectionPath().getPath().length == 2) { if (MyPetUtil.isInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString())) { int level = Integer.parseInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString()); skillTree.removeLevel(level); } else { return; } } else if (skillTreeTree.getSelectionPath().getPath().length == 3) { if (MyPetUtil.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString())) { short level = Short.parseShort(skillTreeTree.getSelectionPath().getPathComponent(1).toString()); int index = ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).getIndex(((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(2))); skillTree.getLevel(level).removeSkill(index); } else { return; } } ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getLastPathComponent()).removeFromParent(); skillTreeTree.updateUI(); addSkillButton.setEnabled(false); deleteLevelSkillButton.setEnabled(false); countSkillLevels(); } }); skillTreeTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { if (e.getPath().getPath().length == 1) { addSkillButton.setEnabled(false); deleteLevelSkillButton.setEnabled(false); skillCounterTabelModel.getDataVector().removeAllElements(); skillCounterTabel.updateUI(); skilllevelLabel.setText("Skilllevels for level: -"); } else if (e.getPath().getPath().length == 2) { addSkillButton.setEnabled(true); deleteLevelSkillButton.setEnabled(true); countSkillLevels(); } else if (e.getPath().getPath().length == 3) { addSkillButton.setEnabled(true); deleteLevelSkillButton.setEnabled(true); countSkillLevels(); } } }); inheritanceCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (inheritanceCheckBox.isSelected()) { inheritanceComboBox.setEnabled(true); skillTree.setInheritance(inheritanceComboBox.getSelectedItem().toString()); } else { inheritanceComboBox.setEnabled(false); skillTree.setInheritance(null); } } }); permissionCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (permissionCheckbox.isSelected()) { permissionTextField.setEnabled(true); if (!permissionTextField.getText().equalsIgnoreCase("")) { skillTree.setPermission(permissionTextField.getText()); } else { skillTree.setPermission(null); } } else { permissionTextField.setEnabled(false); skillTree.setPermission(null); } permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission()); } }); displayNameCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (displayNameCheckbox.isSelected()) { displayNameTextField.setEnabled(true); if (!displayNameTextField.getText().equalsIgnoreCase("")) { skillTree.setDisplayName(displayNameTextField.getText()); } else { skillTree.setDisplayName(null); } } else { displayNameTextField.setEnabled(false); skillTree.setDisplayName(null); } } }); backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GuiMain.skilltreeCreator.getFrame().setEnabled(true); levelCreatorFrame.setVisible(false); } }); inheritanceComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED && inheritanceCheckBox.isSelected()) { if (!skillTree.getInheritance().equals(e.getItem().toString())) { skillTree.setInheritance(e.getItem().toString()); countSkillLevels(); } } } }); copyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StringSelection stringSelection = new StringSelection("MyPet.custom.skilltree." + skillTree.getName()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); } }); skillTreeTree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { if (skillTreeTree.getSelectionPath().getPath().length == 3) { if (skillTreeTree.getSelectionPath().getPathComponent(2) instanceof SkillTreeSkillNode) { ISkillInfo skill = ((SkillTreeSkillNode) skillTreeTree.getSelectionPath().getPathComponent(2)).getSkill(); if (skill.getClass().getAnnotation(SkillProperties.class) == null) { JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE); return; } if (MyPetSkillsInfo.isValidSkill(skill.getName())) { if (skill.getGuiPanel() != null) { GuiMain.skillPropertyEditor.setSkill(skill); } else { JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE); return; } } GuiMain.skillPropertyEditor.getFrame().setVisible(true); getFrame().setEnabled(false); + GuiMain.skillPropertyEditor.getFrame().setSize(GuiMain.skillPropertyEditor.getFrame().getWidth(), skill.getGuiPanel().getMainPanel().getHeight() + 90); } } } } }); permissionTextField.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { permissionTextField.setText(permissionTextField.getText().replaceAll("[^a-zA-Z0-9]*", "")); if (permissionCheckbox.isSelected() && !skillTree.getPermission().equals(permissionTextField.getText())) { if (!permissionTextField.getText().equalsIgnoreCase("")) { skillTree.setPermission(permissionTextField.getText()); } else { skillTree.setPermission(null); } permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission()); } } public void keyPressed(KeyEvent arg0) { } }); displayNameTextField.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { if (displayNameCheckbox.isSelected() && !skillTree.getDisplayName().equals(displayNameTextField.getText())) { if (!displayNameTextField.getText().equalsIgnoreCase("")) { skillTree.setDisplayName(displayNameTextField.getText()); } else { skillTree.setDisplayName(null); } } } public void keyPressed(KeyEvent arg0) { } }); } private void countSkillLevels() { int level = 0; if (skillTreeTree.getSelectionPath() != null && skillTreeTree.getSelectionPath().getPathCount() > 1 && MyPetUtil.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString())) { level = Integer.parseInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()); } Map<String, Integer> skillCount = new HashMap<String, Integer>(); for (MyPetSkillTreeLevel skillTreeLevel : this.skillTree.getLevelList()) { if (skillTreeLevel.getLevel() <= level) { for (ISkillInfo skill : skillTreeLevel.getSkills()) { if (skillCount.containsKey(skill.getName())) { skillCount.put(skill.getName(), skillCount.get(skill.getName()) + 1); } else { skillCount.put(skill.getName(), 1); } } } } if (skillTree.getInheritance() != null && skillTreeMobType.getSkillTree(skillTree.getInheritance()) != null) { for (MyPetSkillTreeLevel skillTreeLevel : this.skillTreeMobType.getSkillTree(skillTree.getInheritance()).getLevelList()) { if (skillTreeLevel.getLevel() <= level) { for (ISkillInfo skill : skillTreeLevel.getSkills()) { if (skillCount.containsKey(skill.getName())) { skillCount.put(skill.getName(), skillCount.get(skill.getName()) + 1); } else { skillCount.put(skill.getName(), 1); } } } } } skillCounterTabelModel.getDataVector().removeAllElements(); for (String skillName : skillCount.keySet()) { String[] row = {skillName, "" + skillCount.get(skillName)}; skillCounterTabelModel.addRow(row); } skilllevelLabel.setText("Skilllevels for level: " + level); skillCounterTabel.updateUI(); } public JPanel getMainPanel() { return levelCreatorPanel; } public JFrame getFrame() { if (levelCreatorFrame == null) { levelCreatorFrame = new JFrame("LevelCreator - MyPet " + MyPetVersion.getMyPetVersion()); } return levelCreatorFrame; } public void setSkillTree(MyPetSkillTree skillTree, MyPetSkillTreeMobType skillTreeMobType) { this.skillTree = skillTree; this.skillTreeMobType = skillTreeMobType; if (skillTree.hasDisplayName()) { displayNameTextField.setEnabled(true); displayNameCheckbox.setSelected(true); } else { displayNameTextField.setEnabled(false); displayNameCheckbox.setSelected(false); } displayNameTextField.setText(skillTree.getDisplayName()); if (skillTree.hasCustomPermissions()) { permissionTextField.setEnabled(true); permissionCheckbox.setSelected(true); } else { permissionTextField.setEnabled(false); permissionCheckbox.setSelected(false); } permissionTextField.setText(skillTree.getPermission()); permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission()); mobTypeLabel.setText(skillTreeMobType.getMobTypeName()); this.inheritanceComboBoxModel.removeAllElements(); inheritanceCheckBox.setSelected(false); if (skillTreeMobType.getSkillTreeNames().size() == 1 && MyPetSkillTreeMobType.getMobTypeByName("default").getSkillTreeNames().size() == 0) { inheritanceCheckBox.setEnabled(false); inheritanceComboBox.setEnabled(false); } else { inheritanceCheckBox.setEnabled(true); ArrayList<String> skilltreeNames = new ArrayList<String>(); for (String skillTreeName : skillTreeMobType.getSkillTreeNames()) { if (!skillTreeName.equals(skillTree.getName()) && !skilltreeNames.contains(skillTreeName)) { skilltreeNames.add(skillTreeName); inheritanceComboBoxModel.addElement(skillTreeName); } } for (String skillTreeName : MyPetSkillTreeMobType.getMobTypeByName("default").getSkillTreeNames()) { if (!skillTreeName.equals(skillTree.getName()) && !skilltreeNames.contains(skillTreeName)) { skilltreeNames.add(skillTreeName); inheritanceComboBoxModel.addElement(skillTreeName); } } if (skillTree.getInheritance() != null && skillTreeMobType.getSkillTreeNames().contains(skillTree.getInheritance())) { inheritanceCheckBox.setSelected(true); inheritanceComboBox.setEnabled(true); this.inheritanceComboBoxModel.setSelectedItem(skillTree.getInheritance()); } else { inheritanceComboBox.setEnabled(false); } } skillTreeNameLabel.setText("Skilltree: " + skillTree.getName()); SortedDefaultMutableTreeNode rootNode = new SortedDefaultMutableTreeNode(skillTree.getName()); skillTreeTreeModel.setRoot(rootNode); int skillcount = 0; for (MyPetSkillTreeLevel level : skillTree.getLevelList()) { DefaultMutableTreeNode levelNode = new DefaultMutableTreeNode(level.getLevel()); rootNode.add(levelNode); for (ISkillInfo skill : level.getSkills()) { SkillTreeSkillNode skillNode = new SkillTreeSkillNode(skill); levelNode.add(skillNode); skillcount++; } } if (skillcount <= 15) { for (int i = 0 ; i < skillTreeTree.getRowCount() ; i++) { skillTreeTree.expandRow(i); } } else { skillTreeTree.expandRow(0); } skillTreeTree.updateUI(); skillTreeTree.setSelectionPath(new TreePath(rootNode)); } private void createUIComponents() { DefaultMutableTreeNode root = new DefaultMutableTreeNode(""); skillTreeTreeModel = new DefaultTreeModel(root); skillTreeTree = new JTree(skillTreeTreeModel); skillTreeTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); inheritanceComboBoxModel = new DefaultComboBoxModel(); inheritanceComboBox = new JComboBox(inheritanceComboBoxModel); String[] columnNames = {"Skill", "Level"}; String[][] data = new String[0][0]; skillCounterTabelModel = new DefaultTableModel(data, columnNames); skillCounterTabel = new JTable(skillCounterTabelModel) { public boolean isCellEditable(int rowIndex, int colIndex) { return false; } }; skillCounterTabel.getColumnModel().getColumn(0).setPreferredWidth(160); skillCounterTabel.getColumnModel().getColumn(1).setPreferredWidth(50); } private class SkillTreeSkillNode extends DefaultMutableTreeNode { private ISkillInfo skill; public SkillTreeSkillNode(ISkillInfo skill) { super(skill.getName()); this.skill = skill; } public ISkillInfo getSkill() { return skill; } } private class SortedDefaultMutableTreeNode extends DefaultMutableTreeNode { public SortedDefaultMutableTreeNode(Object userObject) { super(userObject); } @SuppressWarnings("unchecked") public void add(DefaultMutableTreeNode newChild) { super.add(newChild); Collections.sort(this.children, nodeComparator); } protected Comparator nodeComparator = new Comparator() { public int compare(Object o1, Object o2) { if (MyPetUtil.isInt(o1.toString()) && MyPetUtil.isInt(o2.toString())) { int n1 = Integer.parseInt(o1.toString()); int n2 = Integer.parseInt(o2.toString()); if (n1 < n2) { return -1; } else if (n1 == n2) { return 0; } if (n1 > n2) { return 1; } } return o1.toString().compareToIgnoreCase(o2.toString()); } public boolean equals(Object obj) { return false; } }; } }
true
true
public LevelCreator() { addLevelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String response = JOptionPane.showInputDialog(null, "Enter the number for the new level.", "Create new Level", JOptionPane.QUESTION_MESSAGE); if (response != null) { if (MyPetUtil.isInt(response)) { int newLevel = Integer.parseInt(response); for (int i = 0 ; i < skillTreeTreeModel.getChildCount(skillTreeTreeModel.getRoot()) ; i++) { if (MyPetUtil.isInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString())) { int level = Integer.parseInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString()); if (newLevel == level) { JOptionPane.showMessageDialog(null, response + " already exists!", "Create new Level", JOptionPane.ERROR_MESSAGE); return; } else if (newLevel < 1) { JOptionPane.showMessageDialog(null, response + " is smaller than 1!", "Create new Level", JOptionPane.ERROR_MESSAGE); return; } } } DefaultMutableTreeNode levelNode = new DefaultMutableTreeNode(newLevel); skillTree.addLevel(newLevel); ((SortedDefaultMutableTreeNode) skillTreeTreeModel.getRoot()).add(levelNode); skillTreeTree.expandPath(skillTreeTree.getSelectionPath()); skillTreeTree.updateUI(); } else { JOptionPane.showMessageDialog(null, response + " is not a number!", "Create new Level", JOptionPane.ERROR_MESSAGE); } } countSkillLevels(); } }); addSkillButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int level; if (skillTreeTree.getSelectionPath().getPath().length == 2 || skillTreeTree.getSelectionPath().getPath().length == 3) { if (MyPetUtil.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString())) { level = Integer.parseInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()); } else { return; } } else { return; } String choosenSkill = (String) JOptionPane.showInputDialog(null, "Please select the skill you want to add to level " + level + '.', "", JOptionPane.QUESTION_MESSAGE, null, skillNames, ""); if (choosenSkill != null) { ISkillInfo skill = MyPetSkillsInfo.getNewSkillInfoInstance(choosenSkill); skillTree.addSkillToLevel(level, skill); SkillTreeSkillNode skillNode = new SkillTreeSkillNode(skill); skill.setDefaultProperties(); ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).add(skillNode); skillTreeTree.expandPath(skillTreeTree.getSelectionPath()); skillTreeTree.updateUI(); } countSkillLevels(); } }); deleteLevelSkillButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (skillTreeTree.getSelectionPath().getPath().length == 2) { if (MyPetUtil.isInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString())) { int level = Integer.parseInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString()); skillTree.removeLevel(level); } else { return; } } else if (skillTreeTree.getSelectionPath().getPath().length == 3) { if (MyPetUtil.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString())) { short level = Short.parseShort(skillTreeTree.getSelectionPath().getPathComponent(1).toString()); int index = ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).getIndex(((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(2))); skillTree.getLevel(level).removeSkill(index); } else { return; } } ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getLastPathComponent()).removeFromParent(); skillTreeTree.updateUI(); addSkillButton.setEnabled(false); deleteLevelSkillButton.setEnabled(false); countSkillLevels(); } }); skillTreeTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { if (e.getPath().getPath().length == 1) { addSkillButton.setEnabled(false); deleteLevelSkillButton.setEnabled(false); skillCounterTabelModel.getDataVector().removeAllElements(); skillCounterTabel.updateUI(); skilllevelLabel.setText("Skilllevels for level: -"); } else if (e.getPath().getPath().length == 2) { addSkillButton.setEnabled(true); deleteLevelSkillButton.setEnabled(true); countSkillLevels(); } else if (e.getPath().getPath().length == 3) { addSkillButton.setEnabled(true); deleteLevelSkillButton.setEnabled(true); countSkillLevels(); } } }); inheritanceCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (inheritanceCheckBox.isSelected()) { inheritanceComboBox.setEnabled(true); skillTree.setInheritance(inheritanceComboBox.getSelectedItem().toString()); } else { inheritanceComboBox.setEnabled(false); skillTree.setInheritance(null); } } }); permissionCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (permissionCheckbox.isSelected()) { permissionTextField.setEnabled(true); if (!permissionTextField.getText().equalsIgnoreCase("")) { skillTree.setPermission(permissionTextField.getText()); } else { skillTree.setPermission(null); } } else { permissionTextField.setEnabled(false); skillTree.setPermission(null); } permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission()); } }); displayNameCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (displayNameCheckbox.isSelected()) { displayNameTextField.setEnabled(true); if (!displayNameTextField.getText().equalsIgnoreCase("")) { skillTree.setDisplayName(displayNameTextField.getText()); } else { skillTree.setDisplayName(null); } } else { displayNameTextField.setEnabled(false); skillTree.setDisplayName(null); } } }); backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GuiMain.skilltreeCreator.getFrame().setEnabled(true); levelCreatorFrame.setVisible(false); } }); inheritanceComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED && inheritanceCheckBox.isSelected()) { if (!skillTree.getInheritance().equals(e.getItem().toString())) { skillTree.setInheritance(e.getItem().toString()); countSkillLevels(); } } } }); copyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StringSelection stringSelection = new StringSelection("MyPet.custom.skilltree." + skillTree.getName()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); } }); skillTreeTree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { if (skillTreeTree.getSelectionPath().getPath().length == 3) { if (skillTreeTree.getSelectionPath().getPathComponent(2) instanceof SkillTreeSkillNode) { ISkillInfo skill = ((SkillTreeSkillNode) skillTreeTree.getSelectionPath().getPathComponent(2)).getSkill(); if (skill.getClass().getAnnotation(SkillProperties.class) == null) { JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE); return; } if (MyPetSkillsInfo.isValidSkill(skill.getName())) { if (skill.getGuiPanel() != null) { GuiMain.skillPropertyEditor.setSkill(skill); } else { JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE); return; } } GuiMain.skillPropertyEditor.getFrame().setVisible(true); getFrame().setEnabled(false); } } } } }); permissionTextField.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { permissionTextField.setText(permissionTextField.getText().replaceAll("[^a-zA-Z0-9]*", "")); if (permissionCheckbox.isSelected() && !skillTree.getPermission().equals(permissionTextField.getText())) { if (!permissionTextField.getText().equalsIgnoreCase("")) { skillTree.setPermission(permissionTextField.getText()); } else { skillTree.setPermission(null); } permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission()); } } public void keyPressed(KeyEvent arg0) { } }); displayNameTextField.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { if (displayNameCheckbox.isSelected() && !skillTree.getDisplayName().equals(displayNameTextField.getText())) { if (!displayNameTextField.getText().equalsIgnoreCase("")) { skillTree.setDisplayName(displayNameTextField.getText()); } else { skillTree.setDisplayName(null); } } } public void keyPressed(KeyEvent arg0) { } }); }
public LevelCreator() { addLevelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String response = JOptionPane.showInputDialog(null, "Enter the number for the new level.", "Create new Level", JOptionPane.QUESTION_MESSAGE); if (response != null) { if (MyPetUtil.isInt(response)) { int newLevel = Integer.parseInt(response); for (int i = 0 ; i < skillTreeTreeModel.getChildCount(skillTreeTreeModel.getRoot()) ; i++) { if (MyPetUtil.isInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString())) { int level = Integer.parseInt(((DefaultMutableTreeNode) skillTreeTreeModel.getRoot()).getChildAt(i).toString()); if (newLevel == level) { JOptionPane.showMessageDialog(null, response + " already exists!", "Create new Level", JOptionPane.ERROR_MESSAGE); return; } else if (newLevel < 1) { JOptionPane.showMessageDialog(null, response + " is smaller than 1!", "Create new Level", JOptionPane.ERROR_MESSAGE); return; } } } DefaultMutableTreeNode levelNode = new DefaultMutableTreeNode(newLevel); skillTree.addLevel(newLevel); ((SortedDefaultMutableTreeNode) skillTreeTreeModel.getRoot()).add(levelNode); skillTreeTree.expandPath(skillTreeTree.getSelectionPath()); skillTreeTree.updateUI(); } else { JOptionPane.showMessageDialog(null, response + " is not a number!", "Create new Level", JOptionPane.ERROR_MESSAGE); } } countSkillLevels(); } }); addSkillButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int level; if (skillTreeTree.getSelectionPath().getPath().length == 2 || skillTreeTree.getSelectionPath().getPath().length == 3) { if (MyPetUtil.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString())) { level = Integer.parseInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString()); } else { return; } } else { return; } String choosenSkill = (String) JOptionPane.showInputDialog(null, "Please select the skill you want to add to level " + level + '.', "", JOptionPane.QUESTION_MESSAGE, null, skillNames, ""); if (choosenSkill != null) { ISkillInfo skill = MyPetSkillsInfo.getNewSkillInfoInstance(choosenSkill); skillTree.addSkillToLevel(level, skill); SkillTreeSkillNode skillNode = new SkillTreeSkillNode(skill); skill.setDefaultProperties(); ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).add(skillNode); skillTreeTree.expandPath(skillTreeTree.getSelectionPath()); skillTreeTree.updateUI(); } countSkillLevels(); } }); deleteLevelSkillButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (skillTreeTree.getSelectionPath().getPath().length == 2) { if (MyPetUtil.isInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString())) { int level = Integer.parseInt(skillTreeTree.getSelectionPath().getLastPathComponent().toString()); skillTree.removeLevel(level); } else { return; } } else if (skillTreeTree.getSelectionPath().getPath().length == 3) { if (MyPetUtil.isInt(skillTreeTree.getSelectionPath().getPathComponent(1).toString())) { short level = Short.parseShort(skillTreeTree.getSelectionPath().getPathComponent(1).toString()); int index = ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(1)).getIndex(((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getPathComponent(2))); skillTree.getLevel(level).removeSkill(index); } else { return; } } ((DefaultMutableTreeNode) skillTreeTree.getSelectionPath().getLastPathComponent()).removeFromParent(); skillTreeTree.updateUI(); addSkillButton.setEnabled(false); deleteLevelSkillButton.setEnabled(false); countSkillLevels(); } }); skillTreeTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { if (e.getPath().getPath().length == 1) { addSkillButton.setEnabled(false); deleteLevelSkillButton.setEnabled(false); skillCounterTabelModel.getDataVector().removeAllElements(); skillCounterTabel.updateUI(); skilllevelLabel.setText("Skilllevels for level: -"); } else if (e.getPath().getPath().length == 2) { addSkillButton.setEnabled(true); deleteLevelSkillButton.setEnabled(true); countSkillLevels(); } else if (e.getPath().getPath().length == 3) { addSkillButton.setEnabled(true); deleteLevelSkillButton.setEnabled(true); countSkillLevels(); } } }); inheritanceCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (inheritanceCheckBox.isSelected()) { inheritanceComboBox.setEnabled(true); skillTree.setInheritance(inheritanceComboBox.getSelectedItem().toString()); } else { inheritanceComboBox.setEnabled(false); skillTree.setInheritance(null); } } }); permissionCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (permissionCheckbox.isSelected()) { permissionTextField.setEnabled(true); if (!permissionTextField.getText().equalsIgnoreCase("")) { skillTree.setPermission(permissionTextField.getText()); } else { skillTree.setPermission(null); } } else { permissionTextField.setEnabled(false); skillTree.setPermission(null); } permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission()); } }); displayNameCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (displayNameCheckbox.isSelected()) { displayNameTextField.setEnabled(true); if (!displayNameTextField.getText().equalsIgnoreCase("")) { skillTree.setDisplayName(displayNameTextField.getText()); } else { skillTree.setDisplayName(null); } } else { displayNameTextField.setEnabled(false); skillTree.setDisplayName(null); } } }); backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GuiMain.skilltreeCreator.getFrame().setEnabled(true); levelCreatorFrame.setVisible(false); } }); inheritanceComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED && inheritanceCheckBox.isSelected()) { if (!skillTree.getInheritance().equals(e.getItem().toString())) { skillTree.setInheritance(e.getItem().toString()); countSkillLevels(); } } } }); copyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StringSelection stringSelection = new StringSelection("MyPet.custom.skilltree." + skillTree.getName()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); } }); skillTreeTree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { if (skillTreeTree.getSelectionPath().getPath().length == 3) { if (skillTreeTree.getSelectionPath().getPathComponent(2) instanceof SkillTreeSkillNode) { ISkillInfo skill = ((SkillTreeSkillNode) skillTreeTree.getSelectionPath().getPathComponent(2)).getSkill(); if (skill.getClass().getAnnotation(SkillProperties.class) == null) { JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE); return; } if (MyPetSkillsInfo.isValidSkill(skill.getName())) { if (skill.getGuiPanel() != null) { GuiMain.skillPropertyEditor.setSkill(skill); } else { JOptionPane.showMessageDialog(null, skill.getName() + " has no options.", "Skill options", JOptionPane.INFORMATION_MESSAGE); return; } } GuiMain.skillPropertyEditor.getFrame().setVisible(true); getFrame().setEnabled(false); GuiMain.skillPropertyEditor.getFrame().setSize(GuiMain.skillPropertyEditor.getFrame().getWidth(), skill.getGuiPanel().getMainPanel().getHeight() + 90); } } } } }); permissionTextField.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { permissionTextField.setText(permissionTextField.getText().replaceAll("[^a-zA-Z0-9]*", "")); if (permissionCheckbox.isSelected() && !skillTree.getPermission().equals(permissionTextField.getText())) { if (!permissionTextField.getText().equalsIgnoreCase("")) { skillTree.setPermission(permissionTextField.getText()); } else { skillTree.setPermission(null); } permissionDisplayTextField.setText("MyPet.custom.skilltree." + skillTree.getPermission()); } } public void keyPressed(KeyEvent arg0) { } }); displayNameTextField.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { if (displayNameCheckbox.isSelected() && !skillTree.getDisplayName().equals(displayNameTextField.getText())) { if (!displayNameTextField.getText().equalsIgnoreCase("")) { skillTree.setDisplayName(displayNameTextField.getText()); } else { skillTree.setDisplayName(null); } } } public void keyPressed(KeyEvent arg0) { } }); }
diff --git a/Malaria/src/main/java/com/cajama/malaria/NewReportActivity.java b/Malaria/src/main/java/com/cajama/malaria/NewReportActivity.java index 70d5366..c3a0035 100644 --- a/Malaria/src/main/java/com/cajama/malaria/NewReportActivity.java +++ b/Malaria/src/main/java/com/cajama/malaria/NewReportActivity.java @@ -1,300 +1,300 @@ package com.cajama.malaria; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.Spinner; import android.widget.ViewFlipper; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.app.SherlockActivity; import com.cajama.android.customviews.SquareImageView; import com.actionbarsherlock.view.MenuItem; import java.io.File; import java.text.SimpleDateFormat; import java.util.Vector; import java.util.Date; public class NewReportActivity extends SherlockActivity { ViewFlipper VF; GridView new_report_photos_layout; ImageAdapter images; private static final int CAMERA_REQUEST = 1888; private static final int PHOTO_REQUEST = 4214; private Uri fileUri; private String imageFilePath; private int displayedchild; private Resources res; private String[] step_subtitles; private class myBitmap { String path; Bitmap image; } private class ImageAdapter extends BaseAdapter { private Context mContext; private Vector<myBitmap> images = new Vector<myBitmap>(); public ImageAdapter(Context c) { mContext = c; } public void AddImage(myBitmap b) { images.add(b); } public void remove(int pos) { images.remove(pos); } @Override public int getCount() { return images.size(); } @Override public myBitmap getItem(int arg0) { return images.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { SquareImageView img; if(convertView ==null) { img = new SquareImageView(mContext); } else { img = (SquareImageView)convertView; } img.setImageBitmap(images.get(position).image); img.setScaleType(SquareImageView.ScaleType.CENTER_CROP); return img; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_report); Spinner spinner = (Spinner) findViewById(R.id.gender_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.gender_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); VF = (ViewFlipper) findViewById(R.id.viewFlipper); getSupportActionBar().setSubtitle("Step 1 of " + VF.getChildCount()); images = new ImageAdapter(this); new_report_photos_layout = (GridView) findViewById(R.id.new_report_photos_layout); new_report_photos_layout.setEmptyView(findViewById(R.id.empty_list_view)); new_report_photos_layout.setAdapter(images); new_report_photos_layout.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Intent intent = new Intent(getApplicationContext(), FullscreenPhotoActivity.class); intent.putExtra("pos", position); intent.putExtra("path", images.getItem(position).path); startActivityForResult(intent, PHOTO_REQUEST); } }); res = getResources(); step_subtitles = new String[]{ res.getString(R.string.patient_details), res.getString(R.string.slide_photos), res.getString(R.string.diagnosis), res.getString(R.string.summary), res.getString(R.string.submit) }; } @Override public boolean onPrepareOptionsMenu(Menu menu) { displayedchild = VF.getDisplayedChild(); getSupportActionBar().setSubtitle(String.format("Step %d of %d - %s", displayedchild + 1, VF.getChildCount(), step_subtitles[displayedchild])); switch(displayedchild) { case 0: menu.findItem(R.id.action_prev).setTitle(R.string.cancel); menu.findItem(R.id.action_photo).setVisible(false); menu.findItem(R.id.action_next).setTitle(R.string.next); break; case 1: menu.findItem(R.id.action_prev).setTitle(R.string.back); menu.findItem(R.id.action_photo).setVisible(true); menu.findItem(R.id.action_next).setTitle(R.string.next); break; case 2: menu.findItem(R.id.action_prev).setTitle(R.string.back); menu.findItem(R.id.action_photo).setVisible(false); menu.findItem(R.id.action_next).setTitle(R.string.next); break; case 3: menu.findItem(R.id.action_prev).setTitle(R.string.back); menu.findItem(R.id.action_photo).setVisible(false); menu.findItem(R.id.action_next).setTitle(R.string.next); break; case 4: menu.findItem(R.id.action_prev).setTitle(R.string.back); menu.findItem(R.id.action_photo).setVisible(false); menu.findItem(R.id.action_next).setTitle(R.string.submit); break; default: break; } return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.new_report, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_prev: - invalidateOptionsMenu(); if (VF.getDisplayedChild() == 0) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setTitle(R.string.warning) .setMessage(R.string.new_report_cancel_warning) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { for (int c=0; c<images.getCount(); c++) { File file = new File(images.getItem(c).path); file.delete(); } finish(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } else { VF.showPrevious(); } + invalidateOptionsMenu(); return true; case R.id.action_next: - invalidateOptionsMenu(); if(VF.getDisplayedChild() != VF.getChildCount()-1) { VF.showNext(); } + invalidateOptionsMenu(); return true; case R.id.action_photo: Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); imageFilePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/" + timeStamp + "_slide.jpg"; File imageFile = new File(imageFilePath); fileUri = Uri.fromFile(imageFile); cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(cameraIntent, CAMERA_REQUEST); return true; default: return super.onOptionsItemSelected(item); } } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions); myBitmap bmpp = new myBitmap(); bmpp.image = bmp; bmpp.path = imageFilePath; images.AddImage(bmpp); images.notifyDataSetChanged(); } else if (requestCode == PHOTO_REQUEST && resultCode == RESULT_OK) { int pos = data.getIntExtra("pos", -1); if (pos != -1 ){ File file = new File(images.getItem(pos).path); file.delete(); images.remove(pos); images.notifyDataSetChanged(); } } } @Override public void onBackPressed() { invalidateOptionsMenu(); if (VF.getDisplayedChild() == 0) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setTitle(R.string.warning) .setMessage(R.string.new_report_cancel_warning) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { for (int c=0; c<images.getCount(); c++) { File file = new File(images.getItem(c).path); file.delete(); } finish(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } else { VF.showPrevious(); } } }
false
true
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_prev: invalidateOptionsMenu(); if (VF.getDisplayedChild() == 0) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setTitle(R.string.warning) .setMessage(R.string.new_report_cancel_warning) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { for (int c=0; c<images.getCount(); c++) { File file = new File(images.getItem(c).path); file.delete(); } finish(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } else { VF.showPrevious(); } return true; case R.id.action_next: invalidateOptionsMenu(); if(VF.getDisplayedChild() != VF.getChildCount()-1) { VF.showNext(); } return true; case R.id.action_photo: Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); imageFilePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/" + timeStamp + "_slide.jpg"; File imageFile = new File(imageFilePath); fileUri = Uri.fromFile(imageFile); cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(cameraIntent, CAMERA_REQUEST); return true; default: return super.onOptionsItemSelected(item); } }
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_prev: if (VF.getDisplayedChild() == 0) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setTitle(R.string.warning) .setMessage(R.string.new_report_cancel_warning) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { for (int c=0; c<images.getCount(); c++) { File file = new File(images.getItem(c).path); file.delete(); } finish(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } else { VF.showPrevious(); } invalidateOptionsMenu(); return true; case R.id.action_next: if(VF.getDisplayedChild() != VF.getChildCount()-1) { VF.showNext(); } invalidateOptionsMenu(); return true; case R.id.action_photo: Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); imageFilePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/" + timeStamp + "_slide.jpg"; File imageFile = new File(imageFilePath); fileUri = Uri.fromFile(imageFile); cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(cameraIntent, CAMERA_REQUEST); return true; default: return super.onOptionsItemSelected(item); } }
diff --git a/flume-ng-core/src/main/java/org/apache/flume/sink/DefaultSinkFactory.java b/flume-ng-core/src/main/java/org/apache/flume/sink/DefaultSinkFactory.java index c2a09cbc..641626fb 100644 --- a/flume-ng-core/src/main/java/org/apache/flume/sink/DefaultSinkFactory.java +++ b/flume-ng-core/src/main/java/org/apache/flume/sink/DefaultSinkFactory.java @@ -1,85 +1,85 @@ package org.apache.flume.sink; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.flume.Sink; import org.apache.flume.SinkFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; public class DefaultSinkFactory implements SinkFactory { private static final Logger logger = LoggerFactory .getLogger(DefaultSinkFactory.class); public Map<String, Class<? extends Sink>> sinkRegistry; public DefaultSinkFactory() { sinkRegistry = new HashMap<String, Class<? extends Sink>>(); } @Override public boolean register(String name, Class<? extends Sink> sinkClass) { logger.info("Register sink name:{} class:{}", name, sinkClass); if (sinkRegistry.containsKey(name)) { return false; } sinkRegistry.put(name, sinkClass); return true; } @Override public boolean unregister(String name) { logger.info("Unregister source class:{}", name); return sinkRegistry.remove(name) != null; } @Override public Set<String> getSinkNames() { return sinkRegistry.keySet(); } @Override public Sink create(String name) throws InstantiationException { Preconditions.checkNotNull(name); - logger.debug("Creating instance of source {}", name); + logger.debug("Creating instance of sink {}", name); if (!sinkRegistry.containsKey(name)) { return null; } Sink sink = null; try { sink = sinkRegistry.get(name).newInstance(); } catch (IllegalAccessException e) { throw new InstantiationException("Unable to create sink " + name + " due to " + e.getMessage()); } return sink; } @Override public String toString() { return "{ sinkRegistry:" + sinkRegistry + " }"; } public Map<String, Class<? extends Sink>> getSinkRegistry() { return sinkRegistry; } public void setSinkRegistry( Map<String, Class<? extends Sink>> sinkRegistry) { this.sinkRegistry = sinkRegistry; } }
true
true
public Sink create(String name) throws InstantiationException { Preconditions.checkNotNull(name); logger.debug("Creating instance of source {}", name); if (!sinkRegistry.containsKey(name)) { return null; } Sink sink = null; try { sink = sinkRegistry.get(name).newInstance(); } catch (IllegalAccessException e) { throw new InstantiationException("Unable to create sink " + name + " due to " + e.getMessage()); } return sink; }
public Sink create(String name) throws InstantiationException { Preconditions.checkNotNull(name); logger.debug("Creating instance of sink {}", name); if (!sinkRegistry.containsKey(name)) { return null; } Sink sink = null; try { sink = sinkRegistry.get(name).newInstance(); } catch (IllegalAccessException e) { throw new InstantiationException("Unable to create sink " + name + " due to " + e.getMessage()); } return sink; }
diff --git a/src/com/github/gittodo/rcp/GitToDo.java b/src/com/github/gittodo/rcp/GitToDo.java index 118e193..d7f5425 100644 --- a/src/com/github/gittodo/rcp/GitToDo.java +++ b/src/com/github/gittodo/rcp/GitToDo.java @@ -1,119 +1,130 @@ package com.github.gittodo.rcp; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.openscience.gittodo.sort.ItemSorter; import com.github.gittodo.rcp.views.GitToDoTree; import com.github.gittodo.rcp.views.ItemEditShell; import com.github.gittodo.rcp.views.ItemFilterShell; public class GitToDo { public static void main( String[] args ) { final Display display = new Display(); final Shell shell = new Shell(display); FillLayout layout = new FillLayout(); shell.setLayout(layout); final GitToDoTree tableViewer = new GitToDoTree(shell); Menu menuBar = new Menu(shell, SWT.BAR); shell.setMenuBar( menuBar ); MenuItem fileMenuItem = new MenuItem(menuBar, SWT.CASCADE); fileMenuItem.setText( "&File" ); Menu fileMenu = new Menu(shell, SWT.DROP_DOWN); fileMenuItem.setMenu(fileMenu); MenuItem newItemMenu = new MenuItem(fileMenu, SWT.DROP_DOWN); newItemMenu.setText("&New Item\tCtlr+N"); newItemMenu.setAccelerator(SWT.CTRL + 'N'); newItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { ItemEditShell child = new ItemEditShell(shell, null, tableViewer); child.open(); } catch ( Exception e ) { e.printStackTrace(); } } } ); MenuItem exitItemMenu = new MenuItem(fileMenu, SWT.DROP_DOWN); exitItemMenu.setText("&Exit\tCtlr+Q"); exitItemMenu.setAccelerator(SWT.CTRL + 'Q'); exitItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { shell.dispose(); } } ); MenuItem sortMenuItem = new MenuItem(menuBar, SWT.CASCADE); sortMenuItem.setText( "&Sort" ); Menu sortMenu = new Menu(shell, SWT.DROP_DOWN); sortMenuItem.setMenu(sortMenu); MenuItem priorityItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); priorityItemMenu.setText("Priority\tCtlr+R"); priorityItemMenu.setAccelerator(SWT.CTRL + 'R'); priorityItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.setContent(ItemSorter.sortByPriority(tableViewer.getItems())); } } ); MenuItem contextItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); contextItemMenu.setText("Context\tCtlr+C"); contextItemMenu.setAccelerator(SWT.CTRL + 'C'); contextItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.setContent(ItemSorter.sortByContext(tableViewer.getItems())); } } ); MenuItem projectItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); projectItemMenu.setText("Project\tCtlr+P"); projectItemMenu.setAccelerator(SWT.CTRL + 'P'); projectItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.setContent(ItemSorter.sortByProject(tableViewer.getItems())); } } ); MenuItem filterMenuItem = new MenuItem(menuBar, SWT.CASCADE); - filterMenuItem.setText( "&Filter" ); + filterMenuItem.setText( "Fi&lter" ); Menu filterMenu = new Menu(shell, SWT.DROP_DOWN); filterMenuItem.setMenu(filterMenu); - MenuItem advancedItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); + MenuItem advancedItemMenu = new MenuItem(filterMenu, SWT.DROP_DOWN); advancedItemMenu.setText("&Advanced\tCtlr+F"); advancedItemMenu.setAccelerator(SWT.CTRL + 'F'); advancedItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { ItemFilterShell child = new ItemFilterShell(shell, tableViewer); child.open(); } catch ( Exception e ) { e.printStackTrace(); } } } ); + MenuItem resetItemMenu = new MenuItem(filterMenu, SWT.DROP_DOWN); + resetItemMenu.setText("&Reset\tCtlr+X"); + resetItemMenu.setAccelerator(SWT.CTRL + 'X'); + resetItemMenu.addSelectionListener( + new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + tableViewer.getFilter().reset(); + tableViewer.update(); + } + } + ); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
false
true
public static void main( String[] args ) { final Display display = new Display(); final Shell shell = new Shell(display); FillLayout layout = new FillLayout(); shell.setLayout(layout); final GitToDoTree tableViewer = new GitToDoTree(shell); Menu menuBar = new Menu(shell, SWT.BAR); shell.setMenuBar( menuBar ); MenuItem fileMenuItem = new MenuItem(menuBar, SWT.CASCADE); fileMenuItem.setText( "&File" ); Menu fileMenu = new Menu(shell, SWT.DROP_DOWN); fileMenuItem.setMenu(fileMenu); MenuItem newItemMenu = new MenuItem(fileMenu, SWT.DROP_DOWN); newItemMenu.setText("&New Item\tCtlr+N"); newItemMenu.setAccelerator(SWT.CTRL + 'N'); newItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { ItemEditShell child = new ItemEditShell(shell, null, tableViewer); child.open(); } catch ( Exception e ) { e.printStackTrace(); } } } ); MenuItem exitItemMenu = new MenuItem(fileMenu, SWT.DROP_DOWN); exitItemMenu.setText("&Exit\tCtlr+Q"); exitItemMenu.setAccelerator(SWT.CTRL + 'Q'); exitItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { shell.dispose(); } } ); MenuItem sortMenuItem = new MenuItem(menuBar, SWT.CASCADE); sortMenuItem.setText( "&Sort" ); Menu sortMenu = new Menu(shell, SWT.DROP_DOWN); sortMenuItem.setMenu(sortMenu); MenuItem priorityItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); priorityItemMenu.setText("Priority\tCtlr+R"); priorityItemMenu.setAccelerator(SWT.CTRL + 'R'); priorityItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.setContent(ItemSorter.sortByPriority(tableViewer.getItems())); } } ); MenuItem contextItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); contextItemMenu.setText("Context\tCtlr+C"); contextItemMenu.setAccelerator(SWT.CTRL + 'C'); contextItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.setContent(ItemSorter.sortByContext(tableViewer.getItems())); } } ); MenuItem projectItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); projectItemMenu.setText("Project\tCtlr+P"); projectItemMenu.setAccelerator(SWT.CTRL + 'P'); projectItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.setContent(ItemSorter.sortByProject(tableViewer.getItems())); } } ); MenuItem filterMenuItem = new MenuItem(menuBar, SWT.CASCADE); filterMenuItem.setText( "&Filter" ); Menu filterMenu = new Menu(shell, SWT.DROP_DOWN); filterMenuItem.setMenu(filterMenu); MenuItem advancedItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); advancedItemMenu.setText("&Advanced\tCtlr+F"); advancedItemMenu.setAccelerator(SWT.CTRL + 'F'); advancedItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { ItemFilterShell child = new ItemFilterShell(shell, tableViewer); child.open(); } catch ( Exception e ) { e.printStackTrace(); } } } ); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
public static void main( String[] args ) { final Display display = new Display(); final Shell shell = new Shell(display); FillLayout layout = new FillLayout(); shell.setLayout(layout); final GitToDoTree tableViewer = new GitToDoTree(shell); Menu menuBar = new Menu(shell, SWT.BAR); shell.setMenuBar( menuBar ); MenuItem fileMenuItem = new MenuItem(menuBar, SWT.CASCADE); fileMenuItem.setText( "&File" ); Menu fileMenu = new Menu(shell, SWT.DROP_DOWN); fileMenuItem.setMenu(fileMenu); MenuItem newItemMenu = new MenuItem(fileMenu, SWT.DROP_DOWN); newItemMenu.setText("&New Item\tCtlr+N"); newItemMenu.setAccelerator(SWT.CTRL + 'N'); newItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { ItemEditShell child = new ItemEditShell(shell, null, tableViewer); child.open(); } catch ( Exception e ) { e.printStackTrace(); } } } ); MenuItem exitItemMenu = new MenuItem(fileMenu, SWT.DROP_DOWN); exitItemMenu.setText("&Exit\tCtlr+Q"); exitItemMenu.setAccelerator(SWT.CTRL + 'Q'); exitItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { shell.dispose(); } } ); MenuItem sortMenuItem = new MenuItem(menuBar, SWT.CASCADE); sortMenuItem.setText( "&Sort" ); Menu sortMenu = new Menu(shell, SWT.DROP_DOWN); sortMenuItem.setMenu(sortMenu); MenuItem priorityItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); priorityItemMenu.setText("Priority\tCtlr+R"); priorityItemMenu.setAccelerator(SWT.CTRL + 'R'); priorityItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.setContent(ItemSorter.sortByPriority(tableViewer.getItems())); } } ); MenuItem contextItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); contextItemMenu.setText("Context\tCtlr+C"); contextItemMenu.setAccelerator(SWT.CTRL + 'C'); contextItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.setContent(ItemSorter.sortByContext(tableViewer.getItems())); } } ); MenuItem projectItemMenu = new MenuItem(sortMenu, SWT.DROP_DOWN); projectItemMenu.setText("Project\tCtlr+P"); projectItemMenu.setAccelerator(SWT.CTRL + 'P'); projectItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.setContent(ItemSorter.sortByProject(tableViewer.getItems())); } } ); MenuItem filterMenuItem = new MenuItem(menuBar, SWT.CASCADE); filterMenuItem.setText( "Fi&lter" ); Menu filterMenu = new Menu(shell, SWT.DROP_DOWN); filterMenuItem.setMenu(filterMenu); MenuItem advancedItemMenu = new MenuItem(filterMenu, SWT.DROP_DOWN); advancedItemMenu.setText("&Advanced\tCtlr+F"); advancedItemMenu.setAccelerator(SWT.CTRL + 'F'); advancedItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { ItemFilterShell child = new ItemFilterShell(shell, tableViewer); child.open(); } catch ( Exception e ) { e.printStackTrace(); } } } ); MenuItem resetItemMenu = new MenuItem(filterMenu, SWT.DROP_DOWN); resetItemMenu.setText("&Reset\tCtlr+X"); resetItemMenu.setAccelerator(SWT.CTRL + 'X'); resetItemMenu.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { tableViewer.getFilter().reset(); tableViewer.update(); } } ); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
diff --git a/src/core/java/org/wyona/yanel/core/map/Realm.java b/src/core/java/org/wyona/yanel/core/map/Realm.java index 7f22a7d44..905cd81ba 100644 --- a/src/core/java/org/wyona/yanel/core/map/Realm.java +++ b/src/core/java/org/wyona/yanel/core/map/Realm.java @@ -1,466 +1,466 @@ /* * Copyright 2006 Wyona * * 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.wyona.org/licenses/APACHE-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.wyona.yanel.core.map; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import org.wyona.commons.io.FileUtil; import org.wyona.commons.io.Path; import org.wyona.security.core.IdentityManagerFactory; import org.wyona.security.core.PolicyManagerFactory; import org.wyona.security.core.api.IdentityManager; import org.wyona.security.core.api.PolicyManager; import org.wyona.yanel.core.LanguageHandler; import org.wyona.yanel.core.Yanel; import org.wyona.yanel.core.attributes.translatable.DefaultTranslationManager; import org.wyona.yanel.core.attributes.translatable.TranslationManager; import org.wyona.yanel.core.util.ConfigurationUtil; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.RepositoryFactory; import org.xml.sax.SAXException; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; import org.apache.log4j.Category; /** * */ public class Realm { private Category log = Category.getInstance(Realm.class); private String name; private String id; private String mountPoint; private String defaultLanguage; private Repository repository; private Repository rtiRepository; private PolicyManager privatePolicyManager; private IdentityManager privateIdentityManager; private TranslationManager translationManager; private LanguageHandler languageHandler; private File configFile; private File rootDir; private String[] languages; private boolean proxySet = false; private String proxyHostName; private int proxyPort = -1; private int proxySSLPort = -1; private String proxyPrefix; /** * */ public Realm(String name, String id, String mountPoint, File configFile) throws Exception { this.name = name; this.id = id; this.mountPoint = mountPoint; this.configFile = configFile; proxySet = false; if (configFile != null) { DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(true); Configuration config; try { config = builder.buildFromFile(configFile); configure(config); } catch (SAXException e) { // TODO: CascadingSAXException cse = new CascadingSAXException(e); String errorMsg = "Could not read config file: " + configFile + ": " + e.getMessage(); log.error(errorMsg, e); throw new Exception(errorMsg, e); } catch (Exception e) { String errorMsg = "Could not configure realm [" + id + "] with config file: " + configFile + ": " + e.toString(); throw new Exception(errorMsg, e); } } } /** * */ protected void configure(Configuration config) throws Exception { Yanel yanel = Yanel.getInstance(); File repoConfig = null; // Set PolicyManager for this realm Configuration repoConfigElement = config.getChild("ac-policies", false); if (repoConfigElement != null) { PolicyManagerFactory pmFactory = null; PolicyManager policyManager = null; try { String customPolicyManagerFactoryImplClassName = repoConfigElement.getAttribute("class"); pmFactory = (PolicyManagerFactory) Class.forName(customPolicyManagerFactoryImplClassName).newInstance(); policyManager = pmFactory.newPolicyManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "policy-manager-config", "http://www.wyona.org/security/1.0"), new RealmConfigPathResolver(this)); } catch (ConfigurationException e) { pmFactory = (PolicyManagerFactory) yanel.getBeanFactory().getBean("PolicyManagerFactory"); log.info("Default PolicyManager will be used for realm: " + getName()); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue())); RepositoryFactory policiesRepoFactory = yanel.getRepositoryFactory("ACPoliciesRepositoryFactory"); Repository policiesRepo = policiesRepoFactory.newRepository(getID(), repoConfig); policyManager = pmFactory.newPolicyManager(policiesRepo); } setPolicyManager(policyManager); } // Set IdentityManager for this realm repoConfigElement = config.getChild("ac-identities", false); if (repoConfigElement != null) { IdentityManagerFactory imFactory = null; IdentityManager identityManager = null; try { String customIdentityManagerFactoryImplClassName = repoConfigElement.getAttribute("class"); imFactory = (IdentityManagerFactory) Class.forName(customIdentityManagerFactoryImplClassName).newInstance(); - identityManager = imFactory.newIdentityManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "identity-manager-config", "http://www.wyona.org/security/1.0"), null); + identityManager = imFactory.newIdentityManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "identity-manager-config", "http://www.wyona.org/security/1.0"), new RealmConfigPathResolver(this)); } catch (ConfigurationException e) { imFactory = (IdentityManagerFactory) yanel.getBeanFactory().getBean("IdentityManagerFactory"); log.info("Default IdentityManager will be used for realm: " + getName()); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue())); RepositoryFactory identitiesRepoFactory = yanel.getRepositoryFactory("ACIdentitiesRepositoryFactory"); Repository identitiesRepo = identitiesRepoFactory.newRepository(getID(), repoConfig); identityManager = imFactory.newIdentityManager(identitiesRepo); } setIdentityManager(identityManager); } RepositoryFactory repoFactory = yanel.getRepositoryFactory("DefaultRepositoryFactory"); RepositoryFactory rtiRepoFactory = yanel.getRepositoryFactory("RTIRepositoryFactory"); RepositoryFactory extraRepoFactory = yanel.getRepositoryFactory("ExtraRepositoryFactory"); String repoConfigSrc = config.getChild("data", false).getValue(); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc)); setRepository(repoFactory.newRepository(getID(), repoConfig)); repoConfigSrc = config.getChild("rti", false).getValue(); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc)); setRTIRepository(rtiRepoFactory.newRepository(getID(), repoConfig)); Configuration configElement = config.getChild("default-language", false); if (configElement != null) { setDefaultLanguage(configElement.getValue()); } else { //Maintain backwards compatibility with realms setDefaultLanguage("en"); } Configuration languagesElement = config.getChild("languages", false); ArrayList languages = new ArrayList(); if (languagesElement != null) { Configuration[] langElements = languagesElement.getChildren("language"); for (int i = 0; i < langElements.length; i++) { String language = langElements[i].getValue(); languages.add(language); } } setLanguages((String[])languages.toArray(new String[languages.size()])); configElement = config.getChild("translation-manager", false); TranslationManager translationManager = null; if (configElement != null) { String className = configElement.getAttribute("class"); translationManager = (TranslationManager)Class.forName(className).newInstance(); } else { translationManager = new DefaultTranslationManager(); } translationManager.init(this); setTranslationManager(translationManager); configElement = config.getChild("language-handler", false); LanguageHandler languageHandler = null; if (configElement != null) { String className = configElement.getAttribute("class"); languageHandler = (LanguageHandler)Class.forName(className).newInstance(); } else { languageHandler = (LanguageHandler)Class.forName("org.wyona.yanel.impl.DefaultLanguageHandler").newInstance(); } setLanguageHandler(languageHandler); Configuration rootDirConfig = config.getChild("root-dir", false); if (rootDirConfig != null) { setRootDir(FileUtil.resolve(getConfigFile(), new File(rootDirConfig.getValue()))); } Configuration reposElement = config.getChild("yarep-repositories", false); ArrayList repos = new ArrayList(); if (reposElement != null) { Configuration[] repoElements = reposElement.getChildren("repository"); for (int i = 0; i < repoElements.length; i++) { String id = repoElements[i].getAttribute("id"); String repoConfigPath = repoElements[i].getAttribute("config"); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigPath)); Repository repo = extraRepoFactory.newRepository(id, repoConfig); } } } /** * Name of realm */ public String getName() { return name; } /** * Id of realm */ public String getID() { return id; } /** * Mount point of realm */ public String getMountPoint() { return mountPoint; } /** * Configuration file of realm. */ public File getConfigFile() { return configFile; } /** * */ public void setProxy(String hostName, int port, int sslPort, String prefix) { proxySet = true; proxyHostName = hostName; proxyPort = port; proxySSLPort = sslPort; proxyPrefix = prefix; } /** * */ public boolean isProxySet() { return proxySet; } /** * */ public String getProxyHostName() { return proxyHostName; } /** * */ public int getProxyPort() { return proxyPort; } /** * */ public int getProxySSLPort() { return proxySSLPort; } /** * */ public String getProxyPrefix() { return proxyPrefix; } /** * */ public String toString() { String descr = "Name: " + name + ", ID: " + id + ", Mount-Point: " + mountPoint; if (isProxySet()) { if (proxyHostName != null) { descr = descr + ", Reverse Proxy Host Name: " + proxyHostName; } if (proxyPort >= 0) { descr = descr + ", Reverse Proxy Port: " + proxyPort; } else { descr = descr + ", Reverse Proxy Port is set to default 80 (resp. -1)"; } if (proxySSLPort >= 0) { descr = descr + ", Reverse Proxy SSL Port: " + proxySSLPort; } else { descr = descr + ", Reverse Proxy SSL Port is set to default 443 (resp. -1)"; } if (proxyPrefix != null) { descr = descr + ", Reverse Proxy Prefix: " + proxyPrefix; } } else { descr = descr + ", No reverse proxy set"; } return descr; } /** * Get data repository of realm */ public Repository getRepository() throws Exception { return repository; } public void setRepository(Repository repository) throws Exception { this.repository = repository; } /** * Get RTI (Resource Type Identifier) repository of realm */ public Repository getRTIRepository() throws Exception { return rtiRepository; } public void setRTIRepository(Repository repository) throws Exception { this.rtiRepository = repository; } public IdentityManager getIdentityManager() { return privateIdentityManager; } public void setIdentityManager(IdentityManager identityManager) { this.privateIdentityManager = identityManager; } public PolicyManager getPolicyManager() { return privatePolicyManager; } public void setPolicyManager(PolicyManager policyManager) { this.privatePolicyManager = policyManager; } public String getDefaultLanguage() { return defaultLanguage; } public void setDefaultLanguage(String language) { this.defaultLanguage = language; } /** * Please note that the root-dir element is optional */ public File getRootDir() { return this.rootDir; } public void setRootDir(File rootDir) { this.rootDir = rootDir; } /** * Please note that the menu element is optional */ public String getMenuClass() { try { Configuration realmConfig = new DefaultConfigurationBuilder().buildFromFile(getConfigFile()); Configuration menuClassConfig = realmConfig.getChild("menu", false); if (menuClassConfig != null) { return menuClassConfig.getAttribute("class"); } } catch (Exception e) { log.error(e.getMessage(), e); } return null; } /** * Gets a list of all languages supported by this realm. * @return list of languages. may be empty. */ public String[] getLanguages() { return languages; } public void setLanguages(String[] languages) { this.languages = (String[])languages.clone(); } public TranslationManager getTranslationManager() { //log.debug("Translation Manager: " + translationManager.getClass().getName()); return translationManager; } public void setTranslationManager(TranslationManager translationManager) { this.translationManager = translationManager; } public Repository getRepository(String id) throws Exception { Yanel yanel = Yanel.getInstance(); RepositoryFactory extraRepoFactory = yanel.getRepositoryFactory("ExtraRepositoryFactory"); if (extraRepoFactory.exists(id)) { return extraRepoFactory.newRepository(id); } else { return null; } } public LanguageHandler getLanguageHandler() { return languageHandler; } public void setLanguageHandler(LanguageHandler languageHandler) { this.languageHandler = languageHandler; } } /** * */ class RealmConfigPathResolver implements javax.xml.transform.URIResolver { private File realmConfigFile; /** * */ public RealmConfigPathResolver(Realm realm) { realmConfigFile = realm.getConfigFile(); } /** * */ public javax.xml.transform.Source resolve(String href, String base) throws javax.xml.transform.TransformerException { javax.xml.transform.Source source = new javax.xml.transform.stream.StreamSource(); source.setSystemId(FileUtil.resolve(realmConfigFile, new File(href)).toString()); return source; } }
true
true
protected void configure(Configuration config) throws Exception { Yanel yanel = Yanel.getInstance(); File repoConfig = null; // Set PolicyManager for this realm Configuration repoConfigElement = config.getChild("ac-policies", false); if (repoConfigElement != null) { PolicyManagerFactory pmFactory = null; PolicyManager policyManager = null; try { String customPolicyManagerFactoryImplClassName = repoConfigElement.getAttribute("class"); pmFactory = (PolicyManagerFactory) Class.forName(customPolicyManagerFactoryImplClassName).newInstance(); policyManager = pmFactory.newPolicyManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "policy-manager-config", "http://www.wyona.org/security/1.0"), new RealmConfigPathResolver(this)); } catch (ConfigurationException e) { pmFactory = (PolicyManagerFactory) yanel.getBeanFactory().getBean("PolicyManagerFactory"); log.info("Default PolicyManager will be used for realm: " + getName()); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue())); RepositoryFactory policiesRepoFactory = yanel.getRepositoryFactory("ACPoliciesRepositoryFactory"); Repository policiesRepo = policiesRepoFactory.newRepository(getID(), repoConfig); policyManager = pmFactory.newPolicyManager(policiesRepo); } setPolicyManager(policyManager); } // Set IdentityManager for this realm repoConfigElement = config.getChild("ac-identities", false); if (repoConfigElement != null) { IdentityManagerFactory imFactory = null; IdentityManager identityManager = null; try { String customIdentityManagerFactoryImplClassName = repoConfigElement.getAttribute("class"); imFactory = (IdentityManagerFactory) Class.forName(customIdentityManagerFactoryImplClassName).newInstance(); identityManager = imFactory.newIdentityManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "identity-manager-config", "http://www.wyona.org/security/1.0"), null); } catch (ConfigurationException e) { imFactory = (IdentityManagerFactory) yanel.getBeanFactory().getBean("IdentityManagerFactory"); log.info("Default IdentityManager will be used for realm: " + getName()); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue())); RepositoryFactory identitiesRepoFactory = yanel.getRepositoryFactory("ACIdentitiesRepositoryFactory"); Repository identitiesRepo = identitiesRepoFactory.newRepository(getID(), repoConfig); identityManager = imFactory.newIdentityManager(identitiesRepo); } setIdentityManager(identityManager); } RepositoryFactory repoFactory = yanel.getRepositoryFactory("DefaultRepositoryFactory"); RepositoryFactory rtiRepoFactory = yanel.getRepositoryFactory("RTIRepositoryFactory"); RepositoryFactory extraRepoFactory = yanel.getRepositoryFactory("ExtraRepositoryFactory"); String repoConfigSrc = config.getChild("data", false).getValue(); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc)); setRepository(repoFactory.newRepository(getID(), repoConfig)); repoConfigSrc = config.getChild("rti", false).getValue(); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc)); setRTIRepository(rtiRepoFactory.newRepository(getID(), repoConfig)); Configuration configElement = config.getChild("default-language", false); if (configElement != null) { setDefaultLanguage(configElement.getValue()); } else { //Maintain backwards compatibility with realms setDefaultLanguage("en"); } Configuration languagesElement = config.getChild("languages", false); ArrayList languages = new ArrayList(); if (languagesElement != null) { Configuration[] langElements = languagesElement.getChildren("language"); for (int i = 0; i < langElements.length; i++) { String language = langElements[i].getValue(); languages.add(language); } } setLanguages((String[])languages.toArray(new String[languages.size()])); configElement = config.getChild("translation-manager", false); TranslationManager translationManager = null; if (configElement != null) { String className = configElement.getAttribute("class"); translationManager = (TranslationManager)Class.forName(className).newInstance(); } else { translationManager = new DefaultTranslationManager(); } translationManager.init(this); setTranslationManager(translationManager); configElement = config.getChild("language-handler", false); LanguageHandler languageHandler = null; if (configElement != null) { String className = configElement.getAttribute("class"); languageHandler = (LanguageHandler)Class.forName(className).newInstance(); } else { languageHandler = (LanguageHandler)Class.forName("org.wyona.yanel.impl.DefaultLanguageHandler").newInstance(); } setLanguageHandler(languageHandler); Configuration rootDirConfig = config.getChild("root-dir", false); if (rootDirConfig != null) { setRootDir(FileUtil.resolve(getConfigFile(), new File(rootDirConfig.getValue()))); } Configuration reposElement = config.getChild("yarep-repositories", false); ArrayList repos = new ArrayList(); if (reposElement != null) { Configuration[] repoElements = reposElement.getChildren("repository"); for (int i = 0; i < repoElements.length; i++) { String id = repoElements[i].getAttribute("id"); String repoConfigPath = repoElements[i].getAttribute("config"); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigPath)); Repository repo = extraRepoFactory.newRepository(id, repoConfig); } } }
protected void configure(Configuration config) throws Exception { Yanel yanel = Yanel.getInstance(); File repoConfig = null; // Set PolicyManager for this realm Configuration repoConfigElement = config.getChild("ac-policies", false); if (repoConfigElement != null) { PolicyManagerFactory pmFactory = null; PolicyManager policyManager = null; try { String customPolicyManagerFactoryImplClassName = repoConfigElement.getAttribute("class"); pmFactory = (PolicyManagerFactory) Class.forName(customPolicyManagerFactoryImplClassName).newInstance(); policyManager = pmFactory.newPolicyManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "policy-manager-config", "http://www.wyona.org/security/1.0"), new RealmConfigPathResolver(this)); } catch (ConfigurationException e) { pmFactory = (PolicyManagerFactory) yanel.getBeanFactory().getBean("PolicyManagerFactory"); log.info("Default PolicyManager will be used for realm: " + getName()); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue())); RepositoryFactory policiesRepoFactory = yanel.getRepositoryFactory("ACPoliciesRepositoryFactory"); Repository policiesRepo = policiesRepoFactory.newRepository(getID(), repoConfig); policyManager = pmFactory.newPolicyManager(policiesRepo); } setPolicyManager(policyManager); } // Set IdentityManager for this realm repoConfigElement = config.getChild("ac-identities", false); if (repoConfigElement != null) { IdentityManagerFactory imFactory = null; IdentityManager identityManager = null; try { String customIdentityManagerFactoryImplClassName = repoConfigElement.getAttribute("class"); imFactory = (IdentityManagerFactory) Class.forName(customIdentityManagerFactoryImplClassName).newInstance(); identityManager = imFactory.newIdentityManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "identity-manager-config", "http://www.wyona.org/security/1.0"), new RealmConfigPathResolver(this)); } catch (ConfigurationException e) { imFactory = (IdentityManagerFactory) yanel.getBeanFactory().getBean("IdentityManagerFactory"); log.info("Default IdentityManager will be used for realm: " + getName()); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue())); RepositoryFactory identitiesRepoFactory = yanel.getRepositoryFactory("ACIdentitiesRepositoryFactory"); Repository identitiesRepo = identitiesRepoFactory.newRepository(getID(), repoConfig); identityManager = imFactory.newIdentityManager(identitiesRepo); } setIdentityManager(identityManager); } RepositoryFactory repoFactory = yanel.getRepositoryFactory("DefaultRepositoryFactory"); RepositoryFactory rtiRepoFactory = yanel.getRepositoryFactory("RTIRepositoryFactory"); RepositoryFactory extraRepoFactory = yanel.getRepositoryFactory("ExtraRepositoryFactory"); String repoConfigSrc = config.getChild("data", false).getValue(); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc)); setRepository(repoFactory.newRepository(getID(), repoConfig)); repoConfigSrc = config.getChild("rti", false).getValue(); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc)); setRTIRepository(rtiRepoFactory.newRepository(getID(), repoConfig)); Configuration configElement = config.getChild("default-language", false); if (configElement != null) { setDefaultLanguage(configElement.getValue()); } else { //Maintain backwards compatibility with realms setDefaultLanguage("en"); } Configuration languagesElement = config.getChild("languages", false); ArrayList languages = new ArrayList(); if (languagesElement != null) { Configuration[] langElements = languagesElement.getChildren("language"); for (int i = 0; i < langElements.length; i++) { String language = langElements[i].getValue(); languages.add(language); } } setLanguages((String[])languages.toArray(new String[languages.size()])); configElement = config.getChild("translation-manager", false); TranslationManager translationManager = null; if (configElement != null) { String className = configElement.getAttribute("class"); translationManager = (TranslationManager)Class.forName(className).newInstance(); } else { translationManager = new DefaultTranslationManager(); } translationManager.init(this); setTranslationManager(translationManager); configElement = config.getChild("language-handler", false); LanguageHandler languageHandler = null; if (configElement != null) { String className = configElement.getAttribute("class"); languageHandler = (LanguageHandler)Class.forName(className).newInstance(); } else { languageHandler = (LanguageHandler)Class.forName("org.wyona.yanel.impl.DefaultLanguageHandler").newInstance(); } setLanguageHandler(languageHandler); Configuration rootDirConfig = config.getChild("root-dir", false); if (rootDirConfig != null) { setRootDir(FileUtil.resolve(getConfigFile(), new File(rootDirConfig.getValue()))); } Configuration reposElement = config.getChild("yarep-repositories", false); ArrayList repos = new ArrayList(); if (reposElement != null) { Configuration[] repoElements = reposElement.getChildren("repository"); for (int i = 0; i < repoElements.length; i++) { String id = repoElements[i].getAttribute("id"); String repoConfigPath = repoElements[i].getAttribute("config"); repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigPath)); Repository repo = extraRepoFactory.newRepository(id, repoConfig); } } }
diff --git a/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/QuestionScoreListener.java b/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/QuestionScoreListener.java index 306018c33..867e4be3c 100644 --- a/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/QuestionScoreListener.java +++ b/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/QuestionScoreListener.java @@ -1,902 +1,904 @@ /********************************************************************************** * $URL: https://source.sakaiproject.org/svn/sam/trunk/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/QuestionScoreListener.java $ * $Id: QuestionScoreListener.java 11438 2006-06-30 20:06:03Z [email protected] $ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.tool.assessment.ui.listener.evaluation; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import javax.faces.event.AbortProcessingException; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import javax.faces.event.ValueChangeEvent; import javax.faces.event.ValueChangeListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.tool.assessment.data.dao.assessment.AssessmentAccessControl; import org.sakaiproject.tool.assessment.data.dao.assessment.EvaluationModel; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedAnswer; import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData; import org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemTextIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc; import org.sakaiproject.tool.assessment.data.ifc.grading.MediaIfc; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.services.GradingService; import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService; import org.sakaiproject.tool.assessment.ui.bean.evaluation.AgentResults; import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramScoresBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.PartData; import org.sakaiproject.tool.assessment.ui.bean.evaluation.QuestionScoresBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.SubmissionStatusBean; import org.sakaiproject.tool.assessment.ui.bean.evaluation.TotalScoresBean; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.tool.assessment.util.BeanSort; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ResourceLoader; // end testing /** * <p> * This handles the selection of the Question Score entry page. * </p> * <p> * Description: Action Listener for Evaluation Question Score front door * </p> * <p> * Copyright: Copyright (c) 2004 * </p> * <p> * Organization: Sakai Project * </p> * * @author Ed Smiley * @version $Id: QuestionScoreListener.java 11438 2006-06-30 20:06:03Z * [email protected] $ */ public class QuestionScoreListener implements ActionListener, ValueChangeListener { private static Log log = LogFactory.getLog(QuestionScoreListener.class); // private static EvaluationListenerUtil util; private static BeanSort bs; private static final String noAnswer = (String) ContextUtil .getLocalizedString( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages", "no_answer"); /** * Standard process action method. * * @param event * ActionEvent * @throws AbortProcessingException */ public void processAction(ActionEvent event) throws AbortProcessingException { log.debug("QuestionScore LISTENER."); QuestionScoresBean bean = (QuestionScoresBean) ContextUtil .lookupBean("questionScores"); // Reset the search field String defaultSearchString = ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages", "search_default_student_search_string"); bean.setSearchString(defaultSearchString); // we probably want to change the poster to be consistent String publishedId = ContextUtil.lookupParam("publishedId"); if (!questionScores(publishedId, bean, false)) { throw new RuntimeException("failed to call questionScores."); } } /** * Process a value change. */ public void processValueChange(ValueChangeEvent event) { log.debug("QuestionScore CHANGE LISTENER."); QuestionScoresBean bean = (QuestionScoresBean) ContextUtil.lookupBean("questionScores"); TotalScoresBean totalBean = (TotalScoresBean) ContextUtil.lookupBean("totalScores"); HistogramScoresBean histogramBean = (HistogramScoresBean) ContextUtil.lookupBean("histogramScores"); SubmissionStatusBean submissionbean = (SubmissionStatusBean) ContextUtil.lookupBean("submissionStatus"); // we probably want to change the poster to be consistent String publishedId = ContextUtil.lookupParam("publishedId"); boolean toggleSubmissionSelection = false; String selectedvalue = (String) event.getNewValue(); if ((selectedvalue != null) && (!selectedvalue.equals(""))) { if (event.getComponent().getId().indexOf("sectionpicker") > -1) { bean.setSelectedSectionFilterValue(selectedvalue); // changed totalBean.setSelectedSectionFilterValue(selectedvalue); submissionbean.setSelectedSectionFilterValue(selectedvalue); } else if (event.getComponent().getId().indexOf("allSubmissions") > -1) { bean.setAllSubmissions(selectedvalue); // changed submission // pulldown totalBean.setAllSubmissions(selectedvalue); // changed for total // score bean histogramBean.setAllSubmissions(selectedvalue); // changed for // histogram // score bean toggleSubmissionSelection = true; } else // inline or popup { bean.setSelectedSARationaleView(selectedvalue); // changed // submission // pulldown } } if (!questionScores(publishedId, bean, toggleSubmissionSelection)) { throw new RuntimeException("failed to call questionScores."); } } /** * This will populate the QuestionScoresBean with the data associated with * the particular versioned assessment based on the publishedId. * * @todo Some of this code will change when we move this to Hibernate * persistence. * @param publishedId * String * @param bean * QuestionScoresBean * @return boolean */ public boolean questionScores(String publishedId, QuestionScoresBean bean, boolean isValueChange) { log.debug("questionScores()"); try { PublishedAssessmentService pubService = new PublishedAssessmentService(); // get the PublishedAssessment based on publishedId QuestionScoresBean questionBean = (QuestionScoresBean) ContextUtil .lookupBean("questionScores"); PublishedAssessmentIfc publishedAssessment = questionBean .getPublishedAssessment(); if (publishedAssessment == null) { publishedAssessment = pubService .getPublishedAssessment(publishedId); questionBean.setPublishedAssessment(publishedAssessment); } // build a hashMap (publishedItemId, publishedItem) HashMap publishedItemHash = pubService .preparePublishedItemHash(publishedAssessment); log.debug("questionScores(): publishedItemHash.size = " + publishedItemHash.size()); // build a hashMap (publishedItemTextId, publishedItemText) HashMap publishedItemTextHash = pubService .preparePublishedItemTextHash(publishedAssessment); log.debug("questionScores(): publishedItemTextHash.size = " + publishedItemTextHash.size()); HashMap publishedAnswerHash = pubService .preparePublishedAnswerHash(publishedAssessment); log.debug("questionScores(): publishedAnswerHash.size = " + publishedAnswerHash.size()); HashMap agentResultsByItemGradingIdMap = new HashMap(); GradingService delegate = new GradingService(); TotalScoresBean totalBean = (TotalScoresBean) ContextUtil .lookupBean("totalScores"); if (ContextUtil.lookupParam("sortBy") != null && !ContextUtil.lookupParam("sortBy").trim().equals("")) bean.setSortType(ContextUtil.lookupParam("sortBy")); String itemId = ContextUtil.lookupParam("itemId"); if (ContextUtil.lookupParam("newItemId") != null && !ContextUtil.lookupParam("newItemId").trim().equals("")) itemId = ContextUtil.lookupParam("newItemId"); if (ContextUtil.lookupParam("sortAscending") != null && !ContextUtil.lookupParam("sortAscending").trim().equals( "")) { bean.setSortAscending(Boolean.valueOf( ContextUtil.lookupParam("sortAscending")) .booleanValue()); } String which = bean.getAllSubmissions(); if (which == null && totalBean.getAllSubmissions() != null) { // use totalscore's selection which = totalBean.getAllSubmissions(); bean.setAllSubmissions(which); } totalBean.setSelectedSectionFilterValue(bean .getSelectedSectionFilterValue()); // set section pulldown if (bean.getSelectedSARationaleView() == null) { // if bean.showSARationaleInLine is null, then set inline to be // the default bean .setSelectedSARationaleView(QuestionScoresBean.SHOW_SA_RATIONALE_RESPONSES_POPUP); } if ("true".equalsIgnoreCase(totalBean.getAnonymous())) { // reset sectionaware pulldown to -1 all sections //totalBean // .setSelectedSectionFilterValue(TotalScoresBean.ALL_SECTIONS_SELECT_VALUE); // changed from above by gopalrc - Jan 2008 //PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService(); //boolean groupRelease = publishedAssessmentService.isReleasedToGroups(publishedId); boolean groupRelease = publishedAssessment.getAssessmentAccessControl().getReleaseTo().equals(AssessmentAccessControl.RELEASE_TO_SELECTED_GROUPS); if (groupRelease) { totalBean.setSelectedSectionFilterValue(TotalScoresBean.RELEASED_SECTIONS_GROUPS_SELECT_VALUE); } else { totalBean.setSelectedSectionFilterValue(TotalScoresBean.ALL_SECTIONS_SELECT_VALUE); } } bean.setPublishedId(publishedId); Date dueDate = null; HashMap map = getItemScores(Long.valueOf(publishedId), Long .valueOf(itemId), which, isValueChange); log.debug("questionScores(): map .size = " + map.size()); ResourceLoader rb = null; ArrayList allscores = new ArrayList(); Iterator keyiter = map.keySet().iterator(); while (keyiter.hasNext()) { allscores.addAll((ArrayList) map.get(keyiter.next())); } log.debug("questionScores(): allscores.size = " + allscores.size()); // / // now we need filter by sections selected ArrayList scores = new ArrayList(); // filtered list Map useridMap = totalBean.getUserIdMap(TotalScoresBean.CALLED_FROM_QUESTION_SCORE_LISTENER); bean.setUserIdMap(useridMap); log.debug("questionScores(): useridMap.size = " + useridMap.size()); /* * if ("true".equalsIgnoreCase(totalBean.getAnonymous())){ // skip * section filter if it is anonymous grading, SAK-4395, * scores.addAll(allscores); } */ if (totalBean.getReleaseToAnonymous()) { // skip section filter if it's published to anonymous users scores.addAll(allscores); } else { Iterator allscores_iter = allscores.iterator(); // get the Map of all users(keyed on userid) belong to the // selected sections while (allscores_iter.hasNext()) { // AssessmentGradingData data = (AssessmentGradingData) // allscores_iter.next(); ItemGradingData idata = (ItemGradingData) allscores_iter .next(); // String agentid = // idata.getAssessmentGrading().getAgentId(); String agentid = idata.getAgentId(); // now we only include scores of users belong to the // selected sections if (useridMap.containsKey(agentid)) { scores.add(idata); } } } log.debug("questionScores(): scores.size = " + scores.size()); Iterator iter = scores.iterator(); ArrayList agents = new ArrayList(); log.debug("questionScores(): calling populateSections "); populateSections(publishedAssessment, bean, totalBean, scores, pubService); // set up the Q1, Q2... links if (!iter.hasNext()) { // this section has no students log.debug("questionScores(): this section has no students"); bean.setAgents(agents); bean.setAllAgents(agents); bean.setTotalPeople(Integer.toString(bean.getAgents().size())); bean.setAnonymous(totalBean.getAnonymous()); //return true; } // List them by item and assessmentgradingid, so we can // group answers by item and save them for update use. HashMap scoresByItem = new HashMap(); while (iter.hasNext()) { ItemGradingData idata = (ItemGradingData) iter.next(); ItemTextIfc pubItemText = (ItemTextIfc) publishedItemTextHash .get(idata.getPublishedItemTextId()); AnswerIfc pubAnswer = (AnswerIfc) publishedAnswerHash.get(idata .getPublishedAnswerId()); ArrayList temp = (ArrayList) scoresByItem.get(idata .getAssessmentGradingId() + ":" + idata.getPublishedItemId()); if (temp == null) temp = new ArrayList(); // Very small numbers, so bubblesort is fast Iterator iter2 = temp.iterator(); ArrayList newList = new ArrayList(); boolean added = false; while (iter2.hasNext()) { ItemGradingData tmpData = (ItemGradingData) iter2.next(); ItemTextIfc tmpPublishedText = (ItemTextIfc) publishedItemTextHash .get(tmpData.getPublishedItemTextId()); AnswerIfc tmpAnswer = (AnswerIfc) publishedAnswerHash .get(tmpData.getPublishedAnswerId()); if (pubAnswer != null && tmpAnswer != null && !added && (pubItemText.getSequence().intValue() < tmpPublishedText .getSequence().intValue() || (pubItemText .getSequence().intValue() == tmpPublishedText .getSequence().intValue() && pubAnswer .getSequence().intValue() < tmpAnswer .getSequence().intValue()))) { newList.add(idata); added = true; } newList.add(tmpData); } if (!added) newList.add(idata); scoresByItem.put(idata.getAssessmentGradingId() + ":" + idata.getPublishedItemId(), newList); } log.debug("questionScores(): scoresByItem.size = " + scoresByItem.size()); bean.setScoresByItem(scoresByItem); try { bean.setAnonymous(publishedAssessment.getEvaluationModel() .getAnonymousGrading().equals( EvaluationModel.ANONYMOUS_GRADING) ? "true" : "false"); } catch (RuntimeException e) { // log.info("No evaluation model."); bean.setAnonymous("false"); } // below properties don't seem to be used in jsf pages, try { bean.setLateHandling(publishedAssessment .getAssessmentAccessControl().getLateHandling() .toString()); } catch (Exception e) { // log.info("No access control model."); bean .setLateHandling(AssessmentAccessControl.NOT_ACCEPT_LATE_SUBMISSION .toString()); } try { bean.setDueDate(publishedAssessment .getAssessmentAccessControl().getDueDate().toString()); dueDate = publishedAssessment.getAssessmentAccessControl() .getDueDate(); } catch (RuntimeException e) { // log.info("No due date."); bean.setDueDate(new Date().toString()); } try { bean.setMaxScore(publishedAssessment.getEvaluationModel() .getFixedTotalScore().toString()); } catch (RuntimeException e) { float score = (float) 0.0; Iterator iter2 = publishedAssessment.getSectionArraySorted() .iterator(); while (iter2.hasNext()) { SectionDataIfc sdata = (SectionDataIfc) iter2.next(); Iterator iter3 = sdata.getItemArraySortedForGrading() .iterator(); while (iter3.hasNext()) { ItemDataIfc idata = (ItemDataIfc) iter3.next(); if (idata.getItemId().equals(Long.valueOf(itemId))) score = idata.getScore().floatValue(); } } bean.setMaxScore(Float.toString(score)); } // need to get id from somewhere else, not from data. data only // contains answered items , we want to return all items. // ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(data.getPublishedItemId()); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(Long.valueOf(itemId)); if (item != null) { log.debug("item!=null steting type id = " + item.getTypeId().toString()); bean.setTypeId(item.getTypeId().toString()); bean.setItemId(item.getItemId().toString()); bean.setPartName(item.getSection().getSequence().toString()); bean.setItemName(item.getSequence().toString()); item.setHint("***"); // Keyword to not show student answer // for short answer/ essey question, if there is a model short // answer for this question // set haveModelShortAnswer to true if (item.getTypeId().equals(Long.valueOf(5))) { Iterator iterator = publishedAnswerHash.values().iterator(); while (iterator.hasNext()) { PublishedAnswer publishedAnswer = (PublishedAnswer) iterator .next(); if (publishedAnswer.getItem().getItemId().equals( item.getItemId())) { if (publishedAnswer.getText() == null || publishedAnswer.getText().equals("")) { bean.setHaveModelShortAnswer(false); } else { bean.setHaveModelShortAnswer(true); } break; } } } } else { log.debug("item==null "); } ArrayList deliveryItems = new ArrayList(); // so we can use the var if (item != null) deliveryItems.add(item); bean.setDeliveryItem(deliveryItems); if (ContextUtil.lookupParam("roleSelection") != null) { bean.setRoleSelection(ContextUtil.lookupParam("roleSelection")); } if (bean.getSortType() == null) { if (bean.getAnonymous().equals("true")) { bean.setSortType("totalAutoScore"); } else { bean.setSortType("lastName"); } } // recordingData encapsulates the inbeanation needed for recording. // set recording agent, agent assessmentId, // set course_assignment_context value // set max tries (0=unlimited), and 30 seconds max length // String courseContext = bean.getAssessmentName() + " total "; // Note this is HTTP-centric right now, we can't use in Faces // AuthoringHelper authoringHelper = new AuthoringHelper(); // authoringHelper.getRemoteUserID() needs servlet stuff // authoringHelper.getRemoteUserName() needs servlet stuff /* Dump the grading and agent information into AgentResults */ // ArrayList agents = new ArrayList(); iter = scoresByItem.values().iterator(); while (iter.hasNext()) { AgentResults results = new AgentResults(); // Get all the answers for this question to put in one grading // row ArrayList answerList = (ArrayList) iter.next(); results.setItemGradingArrayList(answerList); Iterator iter2 = answerList.iterator(); ArrayList itemGradingAttachmentList = new ArrayList(); while (iter2.hasNext()) { ItemGradingData gdata = (ItemGradingData) iter2.next(); results.setItemGrading(gdata); itemGradingAttachmentList.addAll(gdata.getItemGradingAttachmentList()); agentResultsByItemGradingIdMap.put(gdata.getItemGradingId(), results); ItemTextIfc gdataPubItemText = (ItemTextIfc) publishedItemTextHash .get(gdata.getPublishedItemTextId()); AnswerIfc gdataAnswer = (AnswerIfc) publishedAnswerHash .get(gdata.getPublishedAnswerId()); // This all just gets the text of the answer to display String answerText = noAnswer; String rationale = ""; String fullAnswerText = noAnswer; // if question type = MC, MR, Survey, TF, Matching, if user // has not submit an answer // answerText = noAnswer. These question type do not use the // itemGrading.answerText field for // storing answers, thye use temGrading.publishedAnswerId to // make their selection if (bean.getTypeId().equals("1") || bean.getTypeId().equals("2") || bean.getTypeId().equals("12") || bean.getTypeId().equals("3") || bean.getTypeId().equals("4") || bean.getTypeId().equals("9") || bean.getTypeId().equals("13")) { if (gdataAnswer != null) answerText = gdataAnswer.getText(); } else { // this handles the other question types: SAQ, File // upload, Audio, FIB, Fill in Numeric // These question type use itemGrading.answetText to // store information about their answer if ((bean.getTypeId().equals("8") || bean.getTypeId().equals("11")) && gdataAnswer == null) { answerText = ""; } else { answerText = gdata.getAnswerText(); } } if ("4".equals(bean.getTypeId())) { if (rb == null) { rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); } if ("true".equals(answerText)) { answerText = rb.getString("true_msg"); } else if ("false".equals(answerText)) { answerText = rb.getString("false_msg"); } } if (bean.getTypeId().equals("9")) { if (gdataPubItemText == null) { // the matching pair is deleted answerText = ""; } else { answerText = gdataPubItemText.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("8")) { if (gdataAnswer != null && gdataAnswer.getSequence() != null) { answerText = gdataAnswer.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("11")) { if (gdataAnswer != null && gdataAnswer.getSequence() != null) { answerText = gdataAnswer.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("13")) { if (gdataPubItemText == null) { // the matching pair is deleted answerText = ""; } else { int answerNo = gdataPubItemText.getSequence().intValue() + 1; answerText = answerNo + ":" + answerText; } } // file upload if (bean.getTypeId().equals("6")) { gdata.setMediaArray(delegate.getMediaArray2(gdata .getItemGradingId().toString())); } // audio recording if (bean.getTypeId().equals("7")) { ArrayList mediaList = delegate.getMediaArray2(gdata .getItemGradingId().toString()); setDurationIsOver(item, mediaList); gdata.setMediaArray(mediaList); } if (answerText == null) answerText = noAnswer; else { if (gdata.getRationale() != null && !gdata.getRationale().trim().equals("")) rationale = "\nRationale: " + gdata.getRationale(); } // Huong's temp commandout // answerText = answerText.replaceAll("<.*?>", ""); answerText = answerText.replaceAll("(\r\n|\r)", "<br/>"); rationale = rationale.replaceAll("<.*?>", ""); rationale = rationale.replaceAll("(\r\n|\r)", "<br/>"); fullAnswerText = answerText; // this is the // non-abbreviated answers // for essay questions // Fix for SAK-6932: Strip out all HTML tags except image // tags if (answerText.length() > 35) { String noHTMLAnswerText; noHTMLAnswerText = answerText.replaceAll( "<((..?)|([^iI][^mM][^gG].*?))>", ""); int index = noHTMLAnswerText.toLowerCase().indexOf( "<img"); if (index != -1) { answerText = noHTMLAnswerText; } else { if (noHTMLAnswerText.length() > 35) { answerText = noHTMLAnswerText.substring(0, 35) + "..."; } else { answerText = noHTMLAnswerText; } } } /* * // no need to shorten it if (rationale.length() > 35) * rationale = rationale.substring(0, 35) + "..."; */ //SAM-755-"checkmark" indicates right, add "X" to indicate wrong if (gdataAnswer != null) { - if (bean.getTypeId().equals("8") || bean.getTypeId().equals("11") || bean.getTypeId().equals("14")) { + if (bean.getTypeId().equals("8") || bean.getTypeId().equals("11") + || bean.getTypeId().equals("15") // CALCULATED_QUESTION + ) { //need to do something here for fill in the blanks if(gdataAnswer.getScore() > 0){ //if score is 0, there is no way to tell if user got the correct answer //by using "autoscore"... wish there was a better way to tell if its correct or not Float autoscore = gdata.getAutoScore(); if (!(Float.valueOf(0)).equals(autoscore)) { answerText = "<img src='/samigo-app/images/delivery/checkmark.gif'>" + answerText; }else if(Float.valueOf(0).equals(autoscore)){ answerText = "<img src='/samigo-app/images/crossmark.gif'>" + answerText; } } } else if(!bean.getTypeId().equals("3")){ if((gdataAnswer.getIsCorrect() != null && gdataAnswer.getIsCorrect()) || (gdataAnswer.getPartialCredit() != null && gdataAnswer.getPartialCredit() > 0)){ answerText = "<img src='/samigo-app/images/delivery/checkmark.gif'>" + answerText; }else if(gdataAnswer.getIsCorrect() != null && !gdataAnswer.getIsCorrect()){ answerText = "<img src='/samigo-app/images/crossmark.gif'>" + answerText; } } } // -- Got the answer text -- if (!answerList.get(0).equals(gdata)) { // We already have // an agentResults // for this one results.setAnswer(results.getAnswer() + "<br/>" + answerText); if (gdata.getAutoScore() != null) { results.setTotalAutoScore(Float.toString((Float.valueOf( results.getExactTotalAutoScore())).floatValue() + gdata.getAutoScore().floatValue())); } else { results.setTotalAutoScore(Float.toString((Float.valueOf( results.getExactTotalAutoScore())).floatValue())); } results.setItemGradingAttachmentList(itemGradingAttachmentList); } else { results.setItemGradingId(gdata.getItemGradingId()); results.setAssessmentGradingId(gdata .getAssessmentGradingId()); if (gdata.getAutoScore() != null) { // for example, if an assessment has one fileupload // question, the autoscore = null results.setTotalAutoScore(gdata.getAutoScore() .toString()); } else { results.setTotalAutoScore(Float.toString(0)); } results.setComments(FormattedText.convertFormattedTextToPlaintext(gdata.getComments())); results.setAnswer(answerText); results.setFullAnswer(fullAnswerText); results.setRationale(rationale); results.setSubmittedDate(gdata.getSubmittedDate()); AgentFacade agent = new AgentFacade(gdata.getAgentId()); // log.info("Rachel: agentid = " + gdata.getAgentId()); results.setLastName(agent.getLastName()); results.setFirstName(agent.getFirstName()); results.setEmail(agent.getEmail()); if (results.getLastName() != null && results.getLastName().length() > 0) results.setLastInitial(results.getLastName() .substring(0, 1)); else if (results.getFirstName() != null && results.getFirstName().length() > 0) results.setLastInitial(results.getFirstName() .substring(0, 1)); else results.setLastInitial("Anonymous"); results.setIdString(agent.getIdString()); results.setAgentEid(agent.getEidString()); log.debug("testing agent getEid agent.getFirstname= " + agent.getFirstName()); log.debug("testing agent getEid agent.getid= " + agent.getIdString()); log.debug("testing agent getEid agent.geteid = " + agent.getEidString()); results.setRole(agent.getRole()); results.setItemGradingAttachmentList(itemGradingAttachmentList); agents.add(results); } } } // log.info("Sort type is " + bean.getSortType() + "."); bs = new BeanSort(agents, bean.getSortType()); if ((bean.getSortType()).equals("assessmentGradingId") || (bean.getSortType()).equals("totalAutoScore") || (bean.getSortType()).equals("totalOverrideScore") || (bean.getSortType()).equals("finalScore")) { bs.toNumericSort(); } else { bs.toStringSort(); } if (bean.isSortAscending()) { log.debug("sortAscending"); agents = (ArrayList) bs.sort(); } else { log.debug("!sortAscending"); agents = (ArrayList) bs.sortDesc(); } // log.info("Listing agents."); bean.setAgents(agents); bean.setAllAgents(agents); bean .setTotalPeople(Integer.valueOf(bean.getAgents().size()) .toString()); bean.setAgentResultsByItemGradingId(agentResultsByItemGradingIdMap); } catch (RuntimeException e) { e.printStackTrace(); return false; } return true; } /** * getting a list of itemGrading for a publishedItemId is a lot of work, * read the code in GradingService.getItemScores() after we get the list, we * are saving it in QuestionScoreBean.itemScoresMap itemScoresMap = * (publishedItemId, HashMap) = (Long publishedItemId, (Long * publishedItemId, Array itemGradings)) itemScoresMap will be refreshed * when the next QuestionScore link is click */ private HashMap getItemScores(Long publishedId, Long itemId, String which, boolean isValueChange) { log.debug("getItemScores"); GradingService delegate = new GradingService(); QuestionScoresBean questionScoresBean = (QuestionScoresBean) ContextUtil .lookupBean("questionScores"); HashMap itemScoresMap = questionScoresBean.getItemScoresMap(); log.debug("getItemScores: itemScoresMap ==null ?" + itemScoresMap); log.debug("getItemScores: isValueChange ?" + isValueChange); if (itemScoresMap == null || isValueChange || questionScoresBean.getIsAnyItemGradingAttachmentListModified()) { log .debug("getItemScores: itemScoresMap == null or isValueChange == true "); log.debug("getItemScores: isValueChange = " + isValueChange); itemScoresMap = new HashMap(); questionScoresBean.setItemScoresMap(itemScoresMap); // reset this anyway (because the itemScoresMap will be refreshed as well as the // attachment list) questionScoresBean.setIsAnyItemGradingAttachmentListModified(false); } log .debug("getItemScores: itemScoresMap.size() " + itemScoresMap.size()); HashMap map = (HashMap) itemScoresMap.get(itemId); if (map == null) { log.debug("getItemScores: map == null "); map = delegate.getItemScores(publishedId, itemId, which); log.debug("getItemScores: map size " + map.size()); itemScoresMap.put(itemId, map); } return map; } private void setDurationIsOver(ItemDataIfc item, ArrayList mediaList) { try { int maxDurationAllowed = item.getDuration().intValue(); for (int i = 0; i < mediaList.size(); i++) { MediaIfc m = (MediaIfc) mediaList.get(i); float duration = (Float.valueOf(m.getDuration())).floatValue(); if (duration > maxDurationAllowed) { m.setDurationIsOver(true); m.setTimeAllowed(String.valueOf(maxDurationAllowed)); } else m.setDurationIsOver(false); } } catch (Exception e) { log.warn("**duration recorded is not an integer value=" + e.getMessage()); } } private void populateSections(PublishedAssessmentIfc publishedAssessment, QuestionScoresBean bean, TotalScoresBean totalBean, ArrayList scores, PublishedAssessmentService pubService) { ArrayList sections = new ArrayList(); log .debug("questionScores(): populate sctions publishedAssessment.getSectionArraySorted size = " + publishedAssessment.getSectionArraySorted().size()); Iterator iter = publishedAssessment.getSectionArraySorted().iterator(); int i = 1; while (iter.hasNext()) { SectionDataIfc section = (SectionDataIfc) iter.next(); ArrayList items = new ArrayList(); PartData part = new PartData(); boolean isRandomDrawPart = pubService.isRandomDrawPart( publishedAssessment.getPublishedAssessmentId(), section .getSectionId()); part.setIsRandomDrawPart(isRandomDrawPart); part.setPartNumber("" + i); part.setId(section.getSectionId().toString()); if (isRandomDrawPart) { if (section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN) !=null ) { int numberToBeDrawn = Integer.parseInt(section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN)); part.setNumberQuestionsDraw(numberToBeDrawn); } PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService(); HashSet itemSet = publishedAssessmentService.getPublishedItemSet(publishedAssessment .getPublishedAssessmentId(), section.getSectionId()); section.setItemSet(itemSet); } else { GradingService gradingService = new GradingService(); HashSet itemSet = gradingService.getItemSet(publishedAssessment .getPublishedAssessmentId(), section.getSectionId()); section.setItemSet(itemSet); } Iterator iter2 = section.getItemArraySortedForGrading().iterator(); int j = 1; while (iter2.hasNext()) { ItemDataIfc item = (ItemDataIfc) iter2.next(); PartData partitem = new PartData(); partitem.setPartNumber("" + j); partitem.setId(item.getItemId().toString()); log.debug("* item.getId = " + item.getItemId()); partitem.setLinked(true); // Iterator iter3 = scores.iterator(); items.add(partitem); j++; } log.debug("questionScores(): items size = " + items.size()); part.setQuestionNumberList(items); sections.add(part); i++; } log.debug("questionScores(): sections size = " + sections.size()); bean.setSections(sections); } }
true
true
public boolean questionScores(String publishedId, QuestionScoresBean bean, boolean isValueChange) { log.debug("questionScores()"); try { PublishedAssessmentService pubService = new PublishedAssessmentService(); // get the PublishedAssessment based on publishedId QuestionScoresBean questionBean = (QuestionScoresBean) ContextUtil .lookupBean("questionScores"); PublishedAssessmentIfc publishedAssessment = questionBean .getPublishedAssessment(); if (publishedAssessment == null) { publishedAssessment = pubService .getPublishedAssessment(publishedId); questionBean.setPublishedAssessment(publishedAssessment); } // build a hashMap (publishedItemId, publishedItem) HashMap publishedItemHash = pubService .preparePublishedItemHash(publishedAssessment); log.debug("questionScores(): publishedItemHash.size = " + publishedItemHash.size()); // build a hashMap (publishedItemTextId, publishedItemText) HashMap publishedItemTextHash = pubService .preparePublishedItemTextHash(publishedAssessment); log.debug("questionScores(): publishedItemTextHash.size = " + publishedItemTextHash.size()); HashMap publishedAnswerHash = pubService .preparePublishedAnswerHash(publishedAssessment); log.debug("questionScores(): publishedAnswerHash.size = " + publishedAnswerHash.size()); HashMap agentResultsByItemGradingIdMap = new HashMap(); GradingService delegate = new GradingService(); TotalScoresBean totalBean = (TotalScoresBean) ContextUtil .lookupBean("totalScores"); if (ContextUtil.lookupParam("sortBy") != null && !ContextUtil.lookupParam("sortBy").trim().equals("")) bean.setSortType(ContextUtil.lookupParam("sortBy")); String itemId = ContextUtil.lookupParam("itemId"); if (ContextUtil.lookupParam("newItemId") != null && !ContextUtil.lookupParam("newItemId").trim().equals("")) itemId = ContextUtil.lookupParam("newItemId"); if (ContextUtil.lookupParam("sortAscending") != null && !ContextUtil.lookupParam("sortAscending").trim().equals( "")) { bean.setSortAscending(Boolean.valueOf( ContextUtil.lookupParam("sortAscending")) .booleanValue()); } String which = bean.getAllSubmissions(); if (which == null && totalBean.getAllSubmissions() != null) { // use totalscore's selection which = totalBean.getAllSubmissions(); bean.setAllSubmissions(which); } totalBean.setSelectedSectionFilterValue(bean .getSelectedSectionFilterValue()); // set section pulldown if (bean.getSelectedSARationaleView() == null) { // if bean.showSARationaleInLine is null, then set inline to be // the default bean .setSelectedSARationaleView(QuestionScoresBean.SHOW_SA_RATIONALE_RESPONSES_POPUP); } if ("true".equalsIgnoreCase(totalBean.getAnonymous())) { // reset sectionaware pulldown to -1 all sections //totalBean // .setSelectedSectionFilterValue(TotalScoresBean.ALL_SECTIONS_SELECT_VALUE); // changed from above by gopalrc - Jan 2008 //PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService(); //boolean groupRelease = publishedAssessmentService.isReleasedToGroups(publishedId); boolean groupRelease = publishedAssessment.getAssessmentAccessControl().getReleaseTo().equals(AssessmentAccessControl.RELEASE_TO_SELECTED_GROUPS); if (groupRelease) { totalBean.setSelectedSectionFilterValue(TotalScoresBean.RELEASED_SECTIONS_GROUPS_SELECT_VALUE); } else { totalBean.setSelectedSectionFilterValue(TotalScoresBean.ALL_SECTIONS_SELECT_VALUE); } } bean.setPublishedId(publishedId); Date dueDate = null; HashMap map = getItemScores(Long.valueOf(publishedId), Long .valueOf(itemId), which, isValueChange); log.debug("questionScores(): map .size = " + map.size()); ResourceLoader rb = null; ArrayList allscores = new ArrayList(); Iterator keyiter = map.keySet().iterator(); while (keyiter.hasNext()) { allscores.addAll((ArrayList) map.get(keyiter.next())); } log.debug("questionScores(): allscores.size = " + allscores.size()); // / // now we need filter by sections selected ArrayList scores = new ArrayList(); // filtered list Map useridMap = totalBean.getUserIdMap(TotalScoresBean.CALLED_FROM_QUESTION_SCORE_LISTENER); bean.setUserIdMap(useridMap); log.debug("questionScores(): useridMap.size = " + useridMap.size()); /* * if ("true".equalsIgnoreCase(totalBean.getAnonymous())){ // skip * section filter if it is anonymous grading, SAK-4395, * scores.addAll(allscores); } */ if (totalBean.getReleaseToAnonymous()) { // skip section filter if it's published to anonymous users scores.addAll(allscores); } else { Iterator allscores_iter = allscores.iterator(); // get the Map of all users(keyed on userid) belong to the // selected sections while (allscores_iter.hasNext()) { // AssessmentGradingData data = (AssessmentGradingData) // allscores_iter.next(); ItemGradingData idata = (ItemGradingData) allscores_iter .next(); // String agentid = // idata.getAssessmentGrading().getAgentId(); String agentid = idata.getAgentId(); // now we only include scores of users belong to the // selected sections if (useridMap.containsKey(agentid)) { scores.add(idata); } } } log.debug("questionScores(): scores.size = " + scores.size()); Iterator iter = scores.iterator(); ArrayList agents = new ArrayList(); log.debug("questionScores(): calling populateSections "); populateSections(publishedAssessment, bean, totalBean, scores, pubService); // set up the Q1, Q2... links if (!iter.hasNext()) { // this section has no students log.debug("questionScores(): this section has no students"); bean.setAgents(agents); bean.setAllAgents(agents); bean.setTotalPeople(Integer.toString(bean.getAgents().size())); bean.setAnonymous(totalBean.getAnonymous()); //return true; } // List them by item and assessmentgradingid, so we can // group answers by item and save them for update use. HashMap scoresByItem = new HashMap(); while (iter.hasNext()) { ItemGradingData idata = (ItemGradingData) iter.next(); ItemTextIfc pubItemText = (ItemTextIfc) publishedItemTextHash .get(idata.getPublishedItemTextId()); AnswerIfc pubAnswer = (AnswerIfc) publishedAnswerHash.get(idata .getPublishedAnswerId()); ArrayList temp = (ArrayList) scoresByItem.get(idata .getAssessmentGradingId() + ":" + idata.getPublishedItemId()); if (temp == null) temp = new ArrayList(); // Very small numbers, so bubblesort is fast Iterator iter2 = temp.iterator(); ArrayList newList = new ArrayList(); boolean added = false; while (iter2.hasNext()) { ItemGradingData tmpData = (ItemGradingData) iter2.next(); ItemTextIfc tmpPublishedText = (ItemTextIfc) publishedItemTextHash .get(tmpData.getPublishedItemTextId()); AnswerIfc tmpAnswer = (AnswerIfc) publishedAnswerHash .get(tmpData.getPublishedAnswerId()); if (pubAnswer != null && tmpAnswer != null && !added && (pubItemText.getSequence().intValue() < tmpPublishedText .getSequence().intValue() || (pubItemText .getSequence().intValue() == tmpPublishedText .getSequence().intValue() && pubAnswer .getSequence().intValue() < tmpAnswer .getSequence().intValue()))) { newList.add(idata); added = true; } newList.add(tmpData); } if (!added) newList.add(idata); scoresByItem.put(idata.getAssessmentGradingId() + ":" + idata.getPublishedItemId(), newList); } log.debug("questionScores(): scoresByItem.size = " + scoresByItem.size()); bean.setScoresByItem(scoresByItem); try { bean.setAnonymous(publishedAssessment.getEvaluationModel() .getAnonymousGrading().equals( EvaluationModel.ANONYMOUS_GRADING) ? "true" : "false"); } catch (RuntimeException e) { // log.info("No evaluation model."); bean.setAnonymous("false"); } // below properties don't seem to be used in jsf pages, try { bean.setLateHandling(publishedAssessment .getAssessmentAccessControl().getLateHandling() .toString()); } catch (Exception e) { // log.info("No access control model."); bean .setLateHandling(AssessmentAccessControl.NOT_ACCEPT_LATE_SUBMISSION .toString()); } try { bean.setDueDate(publishedAssessment .getAssessmentAccessControl().getDueDate().toString()); dueDate = publishedAssessment.getAssessmentAccessControl() .getDueDate(); } catch (RuntimeException e) { // log.info("No due date."); bean.setDueDate(new Date().toString()); } try { bean.setMaxScore(publishedAssessment.getEvaluationModel() .getFixedTotalScore().toString()); } catch (RuntimeException e) { float score = (float) 0.0; Iterator iter2 = publishedAssessment.getSectionArraySorted() .iterator(); while (iter2.hasNext()) { SectionDataIfc sdata = (SectionDataIfc) iter2.next(); Iterator iter3 = sdata.getItemArraySortedForGrading() .iterator(); while (iter3.hasNext()) { ItemDataIfc idata = (ItemDataIfc) iter3.next(); if (idata.getItemId().equals(Long.valueOf(itemId))) score = idata.getScore().floatValue(); } } bean.setMaxScore(Float.toString(score)); } // need to get id from somewhere else, not from data. data only // contains answered items , we want to return all items. // ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(data.getPublishedItemId()); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(Long.valueOf(itemId)); if (item != null) { log.debug("item!=null steting type id = " + item.getTypeId().toString()); bean.setTypeId(item.getTypeId().toString()); bean.setItemId(item.getItemId().toString()); bean.setPartName(item.getSection().getSequence().toString()); bean.setItemName(item.getSequence().toString()); item.setHint("***"); // Keyword to not show student answer // for short answer/ essey question, if there is a model short // answer for this question // set haveModelShortAnswer to true if (item.getTypeId().equals(Long.valueOf(5))) { Iterator iterator = publishedAnswerHash.values().iterator(); while (iterator.hasNext()) { PublishedAnswer publishedAnswer = (PublishedAnswer) iterator .next(); if (publishedAnswer.getItem().getItemId().equals( item.getItemId())) { if (publishedAnswer.getText() == null || publishedAnswer.getText().equals("")) { bean.setHaveModelShortAnswer(false); } else { bean.setHaveModelShortAnswer(true); } break; } } } } else { log.debug("item==null "); } ArrayList deliveryItems = new ArrayList(); // so we can use the var if (item != null) deliveryItems.add(item); bean.setDeliveryItem(deliveryItems); if (ContextUtil.lookupParam("roleSelection") != null) { bean.setRoleSelection(ContextUtil.lookupParam("roleSelection")); } if (bean.getSortType() == null) { if (bean.getAnonymous().equals("true")) { bean.setSortType("totalAutoScore"); } else { bean.setSortType("lastName"); } } // recordingData encapsulates the inbeanation needed for recording. // set recording agent, agent assessmentId, // set course_assignment_context value // set max tries (0=unlimited), and 30 seconds max length // String courseContext = bean.getAssessmentName() + " total "; // Note this is HTTP-centric right now, we can't use in Faces // AuthoringHelper authoringHelper = new AuthoringHelper(); // authoringHelper.getRemoteUserID() needs servlet stuff // authoringHelper.getRemoteUserName() needs servlet stuff /* Dump the grading and agent information into AgentResults */ // ArrayList agents = new ArrayList(); iter = scoresByItem.values().iterator(); while (iter.hasNext()) { AgentResults results = new AgentResults(); // Get all the answers for this question to put in one grading // row ArrayList answerList = (ArrayList) iter.next(); results.setItemGradingArrayList(answerList); Iterator iter2 = answerList.iterator(); ArrayList itemGradingAttachmentList = new ArrayList(); while (iter2.hasNext()) { ItemGradingData gdata = (ItemGradingData) iter2.next(); results.setItemGrading(gdata); itemGradingAttachmentList.addAll(gdata.getItemGradingAttachmentList()); agentResultsByItemGradingIdMap.put(gdata.getItemGradingId(), results); ItemTextIfc gdataPubItemText = (ItemTextIfc) publishedItemTextHash .get(gdata.getPublishedItemTextId()); AnswerIfc gdataAnswer = (AnswerIfc) publishedAnswerHash .get(gdata.getPublishedAnswerId()); // This all just gets the text of the answer to display String answerText = noAnswer; String rationale = ""; String fullAnswerText = noAnswer; // if question type = MC, MR, Survey, TF, Matching, if user // has not submit an answer // answerText = noAnswer. These question type do not use the // itemGrading.answerText field for // storing answers, thye use temGrading.publishedAnswerId to // make their selection if (bean.getTypeId().equals("1") || bean.getTypeId().equals("2") || bean.getTypeId().equals("12") || bean.getTypeId().equals("3") || bean.getTypeId().equals("4") || bean.getTypeId().equals("9") || bean.getTypeId().equals("13")) { if (gdataAnswer != null) answerText = gdataAnswer.getText(); } else { // this handles the other question types: SAQ, File // upload, Audio, FIB, Fill in Numeric // These question type use itemGrading.answetText to // store information about their answer if ((bean.getTypeId().equals("8") || bean.getTypeId().equals("11")) && gdataAnswer == null) { answerText = ""; } else { answerText = gdata.getAnswerText(); } } if ("4".equals(bean.getTypeId())) { if (rb == null) { rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); } if ("true".equals(answerText)) { answerText = rb.getString("true_msg"); } else if ("false".equals(answerText)) { answerText = rb.getString("false_msg"); } } if (bean.getTypeId().equals("9")) { if (gdataPubItemText == null) { // the matching pair is deleted answerText = ""; } else { answerText = gdataPubItemText.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("8")) { if (gdataAnswer != null && gdataAnswer.getSequence() != null) { answerText = gdataAnswer.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("11")) { if (gdataAnswer != null && gdataAnswer.getSequence() != null) { answerText = gdataAnswer.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("13")) { if (gdataPubItemText == null) { // the matching pair is deleted answerText = ""; } else { int answerNo = gdataPubItemText.getSequence().intValue() + 1; answerText = answerNo + ":" + answerText; } } // file upload if (bean.getTypeId().equals("6")) { gdata.setMediaArray(delegate.getMediaArray2(gdata .getItemGradingId().toString())); } // audio recording if (bean.getTypeId().equals("7")) { ArrayList mediaList = delegate.getMediaArray2(gdata .getItemGradingId().toString()); setDurationIsOver(item, mediaList); gdata.setMediaArray(mediaList); } if (answerText == null) answerText = noAnswer; else { if (gdata.getRationale() != null && !gdata.getRationale().trim().equals("")) rationale = "\nRationale: " + gdata.getRationale(); } // Huong's temp commandout // answerText = answerText.replaceAll("<.*?>", ""); answerText = answerText.replaceAll("(\r\n|\r)", "<br/>"); rationale = rationale.replaceAll("<.*?>", ""); rationale = rationale.replaceAll("(\r\n|\r)", "<br/>"); fullAnswerText = answerText; // this is the // non-abbreviated answers // for essay questions // Fix for SAK-6932: Strip out all HTML tags except image // tags if (answerText.length() > 35) { String noHTMLAnswerText; noHTMLAnswerText = answerText.replaceAll( "<((..?)|([^iI][^mM][^gG].*?))>", ""); int index = noHTMLAnswerText.toLowerCase().indexOf( "<img"); if (index != -1) { answerText = noHTMLAnswerText; } else { if (noHTMLAnswerText.length() > 35) { answerText = noHTMLAnswerText.substring(0, 35) + "..."; } else { answerText = noHTMLAnswerText; } } } /* * // no need to shorten it if (rationale.length() > 35) * rationale = rationale.substring(0, 35) + "..."; */ //SAM-755-"checkmark" indicates right, add "X" to indicate wrong if (gdataAnswer != null) { if (bean.getTypeId().equals("8") || bean.getTypeId().equals("11") || bean.getTypeId().equals("14")) { //need to do something here for fill in the blanks if(gdataAnswer.getScore() > 0){ //if score is 0, there is no way to tell if user got the correct answer //by using "autoscore"... wish there was a better way to tell if its correct or not Float autoscore = gdata.getAutoScore(); if (!(Float.valueOf(0)).equals(autoscore)) { answerText = "<img src='/samigo-app/images/delivery/checkmark.gif'>" + answerText; }else if(Float.valueOf(0).equals(autoscore)){ answerText = "<img src='/samigo-app/images/crossmark.gif'>" + answerText; } } } else if(!bean.getTypeId().equals("3")){ if((gdataAnswer.getIsCorrect() != null && gdataAnswer.getIsCorrect()) || (gdataAnswer.getPartialCredit() != null && gdataAnswer.getPartialCredit() > 0)){ answerText = "<img src='/samigo-app/images/delivery/checkmark.gif'>" + answerText; }else if(gdataAnswer.getIsCorrect() != null && !gdataAnswer.getIsCorrect()){ answerText = "<img src='/samigo-app/images/crossmark.gif'>" + answerText; } } } // -- Got the answer text -- if (!answerList.get(0).equals(gdata)) { // We already have // an agentResults // for this one results.setAnswer(results.getAnswer() + "<br/>" + answerText); if (gdata.getAutoScore() != null) { results.setTotalAutoScore(Float.toString((Float.valueOf( results.getExactTotalAutoScore())).floatValue() + gdata.getAutoScore().floatValue())); } else { results.setTotalAutoScore(Float.toString((Float.valueOf( results.getExactTotalAutoScore())).floatValue())); } results.setItemGradingAttachmentList(itemGradingAttachmentList); } else { results.setItemGradingId(gdata.getItemGradingId()); results.setAssessmentGradingId(gdata .getAssessmentGradingId()); if (gdata.getAutoScore() != null) { // for example, if an assessment has one fileupload // question, the autoscore = null results.setTotalAutoScore(gdata.getAutoScore() .toString()); } else { results.setTotalAutoScore(Float.toString(0)); } results.setComments(FormattedText.convertFormattedTextToPlaintext(gdata.getComments())); results.setAnswer(answerText); results.setFullAnswer(fullAnswerText); results.setRationale(rationale); results.setSubmittedDate(gdata.getSubmittedDate()); AgentFacade agent = new AgentFacade(gdata.getAgentId()); // log.info("Rachel: agentid = " + gdata.getAgentId()); results.setLastName(agent.getLastName()); results.setFirstName(agent.getFirstName()); results.setEmail(agent.getEmail()); if (results.getLastName() != null && results.getLastName().length() > 0) results.setLastInitial(results.getLastName() .substring(0, 1)); else if (results.getFirstName() != null && results.getFirstName().length() > 0) results.setLastInitial(results.getFirstName() .substring(0, 1)); else results.setLastInitial("Anonymous"); results.setIdString(agent.getIdString()); results.setAgentEid(agent.getEidString()); log.debug("testing agent getEid agent.getFirstname= " + agent.getFirstName()); log.debug("testing agent getEid agent.getid= " + agent.getIdString()); log.debug("testing agent getEid agent.geteid = " + agent.getEidString()); results.setRole(agent.getRole()); results.setItemGradingAttachmentList(itemGradingAttachmentList); agents.add(results); } } } // log.info("Sort type is " + bean.getSortType() + "."); bs = new BeanSort(agents, bean.getSortType()); if ((bean.getSortType()).equals("assessmentGradingId") || (bean.getSortType()).equals("totalAutoScore") || (bean.getSortType()).equals("totalOverrideScore") || (bean.getSortType()).equals("finalScore")) { bs.toNumericSort(); } else { bs.toStringSort(); } if (bean.isSortAscending()) { log.debug("sortAscending"); agents = (ArrayList) bs.sort(); } else { log.debug("!sortAscending"); agents = (ArrayList) bs.sortDesc(); } // log.info("Listing agents."); bean.setAgents(agents); bean.setAllAgents(agents); bean .setTotalPeople(Integer.valueOf(bean.getAgents().size()) .toString()); bean.setAgentResultsByItemGradingId(agentResultsByItemGradingIdMap); } catch (RuntimeException e) { e.printStackTrace(); return false; } return true; }
public boolean questionScores(String publishedId, QuestionScoresBean bean, boolean isValueChange) { log.debug("questionScores()"); try { PublishedAssessmentService pubService = new PublishedAssessmentService(); // get the PublishedAssessment based on publishedId QuestionScoresBean questionBean = (QuestionScoresBean) ContextUtil .lookupBean("questionScores"); PublishedAssessmentIfc publishedAssessment = questionBean .getPublishedAssessment(); if (publishedAssessment == null) { publishedAssessment = pubService .getPublishedAssessment(publishedId); questionBean.setPublishedAssessment(publishedAssessment); } // build a hashMap (publishedItemId, publishedItem) HashMap publishedItemHash = pubService .preparePublishedItemHash(publishedAssessment); log.debug("questionScores(): publishedItemHash.size = " + publishedItemHash.size()); // build a hashMap (publishedItemTextId, publishedItemText) HashMap publishedItemTextHash = pubService .preparePublishedItemTextHash(publishedAssessment); log.debug("questionScores(): publishedItemTextHash.size = " + publishedItemTextHash.size()); HashMap publishedAnswerHash = pubService .preparePublishedAnswerHash(publishedAssessment); log.debug("questionScores(): publishedAnswerHash.size = " + publishedAnswerHash.size()); HashMap agentResultsByItemGradingIdMap = new HashMap(); GradingService delegate = new GradingService(); TotalScoresBean totalBean = (TotalScoresBean) ContextUtil .lookupBean("totalScores"); if (ContextUtil.lookupParam("sortBy") != null && !ContextUtil.lookupParam("sortBy").trim().equals("")) bean.setSortType(ContextUtil.lookupParam("sortBy")); String itemId = ContextUtil.lookupParam("itemId"); if (ContextUtil.lookupParam("newItemId") != null && !ContextUtil.lookupParam("newItemId").trim().equals("")) itemId = ContextUtil.lookupParam("newItemId"); if (ContextUtil.lookupParam("sortAscending") != null && !ContextUtil.lookupParam("sortAscending").trim().equals( "")) { bean.setSortAscending(Boolean.valueOf( ContextUtil.lookupParam("sortAscending")) .booleanValue()); } String which = bean.getAllSubmissions(); if (which == null && totalBean.getAllSubmissions() != null) { // use totalscore's selection which = totalBean.getAllSubmissions(); bean.setAllSubmissions(which); } totalBean.setSelectedSectionFilterValue(bean .getSelectedSectionFilterValue()); // set section pulldown if (bean.getSelectedSARationaleView() == null) { // if bean.showSARationaleInLine is null, then set inline to be // the default bean .setSelectedSARationaleView(QuestionScoresBean.SHOW_SA_RATIONALE_RESPONSES_POPUP); } if ("true".equalsIgnoreCase(totalBean.getAnonymous())) { // reset sectionaware pulldown to -1 all sections //totalBean // .setSelectedSectionFilterValue(TotalScoresBean.ALL_SECTIONS_SELECT_VALUE); // changed from above by gopalrc - Jan 2008 //PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService(); //boolean groupRelease = publishedAssessmentService.isReleasedToGroups(publishedId); boolean groupRelease = publishedAssessment.getAssessmentAccessControl().getReleaseTo().equals(AssessmentAccessControl.RELEASE_TO_SELECTED_GROUPS); if (groupRelease) { totalBean.setSelectedSectionFilterValue(TotalScoresBean.RELEASED_SECTIONS_GROUPS_SELECT_VALUE); } else { totalBean.setSelectedSectionFilterValue(TotalScoresBean.ALL_SECTIONS_SELECT_VALUE); } } bean.setPublishedId(publishedId); Date dueDate = null; HashMap map = getItemScores(Long.valueOf(publishedId), Long .valueOf(itemId), which, isValueChange); log.debug("questionScores(): map .size = " + map.size()); ResourceLoader rb = null; ArrayList allscores = new ArrayList(); Iterator keyiter = map.keySet().iterator(); while (keyiter.hasNext()) { allscores.addAll((ArrayList) map.get(keyiter.next())); } log.debug("questionScores(): allscores.size = " + allscores.size()); // / // now we need filter by sections selected ArrayList scores = new ArrayList(); // filtered list Map useridMap = totalBean.getUserIdMap(TotalScoresBean.CALLED_FROM_QUESTION_SCORE_LISTENER); bean.setUserIdMap(useridMap); log.debug("questionScores(): useridMap.size = " + useridMap.size()); /* * if ("true".equalsIgnoreCase(totalBean.getAnonymous())){ // skip * section filter if it is anonymous grading, SAK-4395, * scores.addAll(allscores); } */ if (totalBean.getReleaseToAnonymous()) { // skip section filter if it's published to anonymous users scores.addAll(allscores); } else { Iterator allscores_iter = allscores.iterator(); // get the Map of all users(keyed on userid) belong to the // selected sections while (allscores_iter.hasNext()) { // AssessmentGradingData data = (AssessmentGradingData) // allscores_iter.next(); ItemGradingData idata = (ItemGradingData) allscores_iter .next(); // String agentid = // idata.getAssessmentGrading().getAgentId(); String agentid = idata.getAgentId(); // now we only include scores of users belong to the // selected sections if (useridMap.containsKey(agentid)) { scores.add(idata); } } } log.debug("questionScores(): scores.size = " + scores.size()); Iterator iter = scores.iterator(); ArrayList agents = new ArrayList(); log.debug("questionScores(): calling populateSections "); populateSections(publishedAssessment, bean, totalBean, scores, pubService); // set up the Q1, Q2... links if (!iter.hasNext()) { // this section has no students log.debug("questionScores(): this section has no students"); bean.setAgents(agents); bean.setAllAgents(agents); bean.setTotalPeople(Integer.toString(bean.getAgents().size())); bean.setAnonymous(totalBean.getAnonymous()); //return true; } // List them by item and assessmentgradingid, so we can // group answers by item and save them for update use. HashMap scoresByItem = new HashMap(); while (iter.hasNext()) { ItemGradingData idata = (ItemGradingData) iter.next(); ItemTextIfc pubItemText = (ItemTextIfc) publishedItemTextHash .get(idata.getPublishedItemTextId()); AnswerIfc pubAnswer = (AnswerIfc) publishedAnswerHash.get(idata .getPublishedAnswerId()); ArrayList temp = (ArrayList) scoresByItem.get(idata .getAssessmentGradingId() + ":" + idata.getPublishedItemId()); if (temp == null) temp = new ArrayList(); // Very small numbers, so bubblesort is fast Iterator iter2 = temp.iterator(); ArrayList newList = new ArrayList(); boolean added = false; while (iter2.hasNext()) { ItemGradingData tmpData = (ItemGradingData) iter2.next(); ItemTextIfc tmpPublishedText = (ItemTextIfc) publishedItemTextHash .get(tmpData.getPublishedItemTextId()); AnswerIfc tmpAnswer = (AnswerIfc) publishedAnswerHash .get(tmpData.getPublishedAnswerId()); if (pubAnswer != null && tmpAnswer != null && !added && (pubItemText.getSequence().intValue() < tmpPublishedText .getSequence().intValue() || (pubItemText .getSequence().intValue() == tmpPublishedText .getSequence().intValue() && pubAnswer .getSequence().intValue() < tmpAnswer .getSequence().intValue()))) { newList.add(idata); added = true; } newList.add(tmpData); } if (!added) newList.add(idata); scoresByItem.put(idata.getAssessmentGradingId() + ":" + idata.getPublishedItemId(), newList); } log.debug("questionScores(): scoresByItem.size = " + scoresByItem.size()); bean.setScoresByItem(scoresByItem); try { bean.setAnonymous(publishedAssessment.getEvaluationModel() .getAnonymousGrading().equals( EvaluationModel.ANONYMOUS_GRADING) ? "true" : "false"); } catch (RuntimeException e) { // log.info("No evaluation model."); bean.setAnonymous("false"); } // below properties don't seem to be used in jsf pages, try { bean.setLateHandling(publishedAssessment .getAssessmentAccessControl().getLateHandling() .toString()); } catch (Exception e) { // log.info("No access control model."); bean .setLateHandling(AssessmentAccessControl.NOT_ACCEPT_LATE_SUBMISSION .toString()); } try { bean.setDueDate(publishedAssessment .getAssessmentAccessControl().getDueDate().toString()); dueDate = publishedAssessment.getAssessmentAccessControl() .getDueDate(); } catch (RuntimeException e) { // log.info("No due date."); bean.setDueDate(new Date().toString()); } try { bean.setMaxScore(publishedAssessment.getEvaluationModel() .getFixedTotalScore().toString()); } catch (RuntimeException e) { float score = (float) 0.0; Iterator iter2 = publishedAssessment.getSectionArraySorted() .iterator(); while (iter2.hasNext()) { SectionDataIfc sdata = (SectionDataIfc) iter2.next(); Iterator iter3 = sdata.getItemArraySortedForGrading() .iterator(); while (iter3.hasNext()) { ItemDataIfc idata = (ItemDataIfc) iter3.next(); if (idata.getItemId().equals(Long.valueOf(itemId))) score = idata.getScore().floatValue(); } } bean.setMaxScore(Float.toString(score)); } // need to get id from somewhere else, not from data. data only // contains answered items , we want to return all items. // ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(data.getPublishedItemId()); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(Long.valueOf(itemId)); if (item != null) { log.debug("item!=null steting type id = " + item.getTypeId().toString()); bean.setTypeId(item.getTypeId().toString()); bean.setItemId(item.getItemId().toString()); bean.setPartName(item.getSection().getSequence().toString()); bean.setItemName(item.getSequence().toString()); item.setHint("***"); // Keyword to not show student answer // for short answer/ essey question, if there is a model short // answer for this question // set haveModelShortAnswer to true if (item.getTypeId().equals(Long.valueOf(5))) { Iterator iterator = publishedAnswerHash.values().iterator(); while (iterator.hasNext()) { PublishedAnswer publishedAnswer = (PublishedAnswer) iterator .next(); if (publishedAnswer.getItem().getItemId().equals( item.getItemId())) { if (publishedAnswer.getText() == null || publishedAnswer.getText().equals("")) { bean.setHaveModelShortAnswer(false); } else { bean.setHaveModelShortAnswer(true); } break; } } } } else { log.debug("item==null "); } ArrayList deliveryItems = new ArrayList(); // so we can use the var if (item != null) deliveryItems.add(item); bean.setDeliveryItem(deliveryItems); if (ContextUtil.lookupParam("roleSelection") != null) { bean.setRoleSelection(ContextUtil.lookupParam("roleSelection")); } if (bean.getSortType() == null) { if (bean.getAnonymous().equals("true")) { bean.setSortType("totalAutoScore"); } else { bean.setSortType("lastName"); } } // recordingData encapsulates the inbeanation needed for recording. // set recording agent, agent assessmentId, // set course_assignment_context value // set max tries (0=unlimited), and 30 seconds max length // String courseContext = bean.getAssessmentName() + " total "; // Note this is HTTP-centric right now, we can't use in Faces // AuthoringHelper authoringHelper = new AuthoringHelper(); // authoringHelper.getRemoteUserID() needs servlet stuff // authoringHelper.getRemoteUserName() needs servlet stuff /* Dump the grading and agent information into AgentResults */ // ArrayList agents = new ArrayList(); iter = scoresByItem.values().iterator(); while (iter.hasNext()) { AgentResults results = new AgentResults(); // Get all the answers for this question to put in one grading // row ArrayList answerList = (ArrayList) iter.next(); results.setItemGradingArrayList(answerList); Iterator iter2 = answerList.iterator(); ArrayList itemGradingAttachmentList = new ArrayList(); while (iter2.hasNext()) { ItemGradingData gdata = (ItemGradingData) iter2.next(); results.setItemGrading(gdata); itemGradingAttachmentList.addAll(gdata.getItemGradingAttachmentList()); agentResultsByItemGradingIdMap.put(gdata.getItemGradingId(), results); ItemTextIfc gdataPubItemText = (ItemTextIfc) publishedItemTextHash .get(gdata.getPublishedItemTextId()); AnswerIfc gdataAnswer = (AnswerIfc) publishedAnswerHash .get(gdata.getPublishedAnswerId()); // This all just gets the text of the answer to display String answerText = noAnswer; String rationale = ""; String fullAnswerText = noAnswer; // if question type = MC, MR, Survey, TF, Matching, if user // has not submit an answer // answerText = noAnswer. These question type do not use the // itemGrading.answerText field for // storing answers, thye use temGrading.publishedAnswerId to // make their selection if (bean.getTypeId().equals("1") || bean.getTypeId().equals("2") || bean.getTypeId().equals("12") || bean.getTypeId().equals("3") || bean.getTypeId().equals("4") || bean.getTypeId().equals("9") || bean.getTypeId().equals("13")) { if (gdataAnswer != null) answerText = gdataAnswer.getText(); } else { // this handles the other question types: SAQ, File // upload, Audio, FIB, Fill in Numeric // These question type use itemGrading.answetText to // store information about their answer if ((bean.getTypeId().equals("8") || bean.getTypeId().equals("11")) && gdataAnswer == null) { answerText = ""; } else { answerText = gdata.getAnswerText(); } } if ("4".equals(bean.getTypeId())) { if (rb == null) { rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages"); } if ("true".equals(answerText)) { answerText = rb.getString("true_msg"); } else if ("false".equals(answerText)) { answerText = rb.getString("false_msg"); } } if (bean.getTypeId().equals("9")) { if (gdataPubItemText == null) { // the matching pair is deleted answerText = ""; } else { answerText = gdataPubItemText.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("8")) { if (gdataAnswer != null && gdataAnswer.getSequence() != null) { answerText = gdataAnswer.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("11")) { if (gdataAnswer != null && gdataAnswer.getSequence() != null) { answerText = gdataAnswer.getSequence() + ":" + answerText; } } if (bean.getTypeId().equals("13")) { if (gdataPubItemText == null) { // the matching pair is deleted answerText = ""; } else { int answerNo = gdataPubItemText.getSequence().intValue() + 1; answerText = answerNo + ":" + answerText; } } // file upload if (bean.getTypeId().equals("6")) { gdata.setMediaArray(delegate.getMediaArray2(gdata .getItemGradingId().toString())); } // audio recording if (bean.getTypeId().equals("7")) { ArrayList mediaList = delegate.getMediaArray2(gdata .getItemGradingId().toString()); setDurationIsOver(item, mediaList); gdata.setMediaArray(mediaList); } if (answerText == null) answerText = noAnswer; else { if (gdata.getRationale() != null && !gdata.getRationale().trim().equals("")) rationale = "\nRationale: " + gdata.getRationale(); } // Huong's temp commandout // answerText = answerText.replaceAll("<.*?>", ""); answerText = answerText.replaceAll("(\r\n|\r)", "<br/>"); rationale = rationale.replaceAll("<.*?>", ""); rationale = rationale.replaceAll("(\r\n|\r)", "<br/>"); fullAnswerText = answerText; // this is the // non-abbreviated answers // for essay questions // Fix for SAK-6932: Strip out all HTML tags except image // tags if (answerText.length() > 35) { String noHTMLAnswerText; noHTMLAnswerText = answerText.replaceAll( "<((..?)|([^iI][^mM][^gG].*?))>", ""); int index = noHTMLAnswerText.toLowerCase().indexOf( "<img"); if (index != -1) { answerText = noHTMLAnswerText; } else { if (noHTMLAnswerText.length() > 35) { answerText = noHTMLAnswerText.substring(0, 35) + "..."; } else { answerText = noHTMLAnswerText; } } } /* * // no need to shorten it if (rationale.length() > 35) * rationale = rationale.substring(0, 35) + "..."; */ //SAM-755-"checkmark" indicates right, add "X" to indicate wrong if (gdataAnswer != null) { if (bean.getTypeId().equals("8") || bean.getTypeId().equals("11") || bean.getTypeId().equals("15") // CALCULATED_QUESTION ) { //need to do something here for fill in the blanks if(gdataAnswer.getScore() > 0){ //if score is 0, there is no way to tell if user got the correct answer //by using "autoscore"... wish there was a better way to tell if its correct or not Float autoscore = gdata.getAutoScore(); if (!(Float.valueOf(0)).equals(autoscore)) { answerText = "<img src='/samigo-app/images/delivery/checkmark.gif'>" + answerText; }else if(Float.valueOf(0).equals(autoscore)){ answerText = "<img src='/samigo-app/images/crossmark.gif'>" + answerText; } } } else if(!bean.getTypeId().equals("3")){ if((gdataAnswer.getIsCorrect() != null && gdataAnswer.getIsCorrect()) || (gdataAnswer.getPartialCredit() != null && gdataAnswer.getPartialCredit() > 0)){ answerText = "<img src='/samigo-app/images/delivery/checkmark.gif'>" + answerText; }else if(gdataAnswer.getIsCorrect() != null && !gdataAnswer.getIsCorrect()){ answerText = "<img src='/samigo-app/images/crossmark.gif'>" + answerText; } } } // -- Got the answer text -- if (!answerList.get(0).equals(gdata)) { // We already have // an agentResults // for this one results.setAnswer(results.getAnswer() + "<br/>" + answerText); if (gdata.getAutoScore() != null) { results.setTotalAutoScore(Float.toString((Float.valueOf( results.getExactTotalAutoScore())).floatValue() + gdata.getAutoScore().floatValue())); } else { results.setTotalAutoScore(Float.toString((Float.valueOf( results.getExactTotalAutoScore())).floatValue())); } results.setItemGradingAttachmentList(itemGradingAttachmentList); } else { results.setItemGradingId(gdata.getItemGradingId()); results.setAssessmentGradingId(gdata .getAssessmentGradingId()); if (gdata.getAutoScore() != null) { // for example, if an assessment has one fileupload // question, the autoscore = null results.setTotalAutoScore(gdata.getAutoScore() .toString()); } else { results.setTotalAutoScore(Float.toString(0)); } results.setComments(FormattedText.convertFormattedTextToPlaintext(gdata.getComments())); results.setAnswer(answerText); results.setFullAnswer(fullAnswerText); results.setRationale(rationale); results.setSubmittedDate(gdata.getSubmittedDate()); AgentFacade agent = new AgentFacade(gdata.getAgentId()); // log.info("Rachel: agentid = " + gdata.getAgentId()); results.setLastName(agent.getLastName()); results.setFirstName(agent.getFirstName()); results.setEmail(agent.getEmail()); if (results.getLastName() != null && results.getLastName().length() > 0) results.setLastInitial(results.getLastName() .substring(0, 1)); else if (results.getFirstName() != null && results.getFirstName().length() > 0) results.setLastInitial(results.getFirstName() .substring(0, 1)); else results.setLastInitial("Anonymous"); results.setIdString(agent.getIdString()); results.setAgentEid(agent.getEidString()); log.debug("testing agent getEid agent.getFirstname= " + agent.getFirstName()); log.debug("testing agent getEid agent.getid= " + agent.getIdString()); log.debug("testing agent getEid agent.geteid = " + agent.getEidString()); results.setRole(agent.getRole()); results.setItemGradingAttachmentList(itemGradingAttachmentList); agents.add(results); } } } // log.info("Sort type is " + bean.getSortType() + "."); bs = new BeanSort(agents, bean.getSortType()); if ((bean.getSortType()).equals("assessmentGradingId") || (bean.getSortType()).equals("totalAutoScore") || (bean.getSortType()).equals("totalOverrideScore") || (bean.getSortType()).equals("finalScore")) { bs.toNumericSort(); } else { bs.toStringSort(); } if (bean.isSortAscending()) { log.debug("sortAscending"); agents = (ArrayList) bs.sort(); } else { log.debug("!sortAscending"); agents = (ArrayList) bs.sortDesc(); } // log.info("Listing agents."); bean.setAgents(agents); bean.setAllAgents(agents); bean .setTotalPeople(Integer.valueOf(bean.getAgents().size()) .toString()); bean.setAgentResultsByItemGradingId(agentResultsByItemGradingIdMap); } catch (RuntimeException e) { e.printStackTrace(); return false; } return true; }
diff --git a/src/main/java/org/mozilla/gecko/sync/setup/SyncAuthenticatorService.java b/src/main/java/org/mozilla/gecko/sync/setup/SyncAuthenticatorService.java index 1227564b7..6a47e279a 100644 --- a/src/main/java/org/mozilla/gecko/sync/setup/SyncAuthenticatorService.java +++ b/src/main/java/org/mozilla/gecko/sync/setup/SyncAuthenticatorService.java @@ -1,198 +1,199 @@ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 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 a copy of the License at * http://www.mozilla.org/MPL/ * * 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 Android Sync Client. * * The Initial Developer of the Original Code is * the Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Chenxia Liu <[email protected]> * Richard Newman <[email protected]> * * 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"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * 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. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.gecko.sync.setup; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import org.mozilla.gecko.sync.Logger; import org.mozilla.gecko.sync.crypto.KeyBundle; import org.mozilla.gecko.sync.setup.activities.SetupSyncActivity; import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.accounts.NetworkErrorException; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; public class SyncAuthenticatorService extends Service { private static final String LOG_TAG = "SyncAuthService"; private SyncAccountAuthenticator sAccountAuthenticator = null; @Override public void onCreate() { Logger.debug(LOG_TAG, "onCreate"); sAccountAuthenticator = getAuthenticator(); } @Override public IBinder onBind(Intent intent) { if (intent.getAction().equals(android.accounts.AccountManager.ACTION_AUTHENTICATOR_INTENT)) { return getAuthenticator().getIBinder(); } return null; } private SyncAccountAuthenticator getAuthenticator() { if (sAccountAuthenticator == null) { sAccountAuthenticator = new SyncAccountAuthenticator(this); } return sAccountAuthenticator; } private static class SyncAccountAuthenticator extends AbstractAccountAuthenticator { private Context mContext; public SyncAccountAuthenticator(Context context) { super(context); mContext = context; } @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { Logger.debug(LOG_TAG, "addAccount()"); final Intent intent = new Intent(mContext, SetupSyncActivity.class); intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); intent.putExtra("accountType", Constants.ACCOUNTTYPE_SYNC); intent.putExtra(Constants.INTENT_EXTRA_IS_SETUP, true); final Bundle result = new Bundle(); result.putParcelable(AccountManager.KEY_INTENT, intent); return result; } @Override public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException { Logger.debug(LOG_TAG, "confirmCredentials()"); return null; } @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { Logger.debug(LOG_TAG, "editProperties"); return null; } @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { Logger.debug(LOG_TAG, "getAuthToken()"); if (!authTokenType.equals(Constants.AUTHTOKEN_TYPE_PLAIN)) { final Bundle result = new Bundle(); result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType"); return result; } // Extract the username and password from the Account Manager, and ask // the server for an appropriate AuthToken. Logger.info(LOG_TAG, "AccountManager.get(" + mContext + ")"); final AccountManager am = AccountManager.get(mContext); final String password = am.getPassword(account); if (password != null) { final Bundle result = new Bundle(); // This is a Sync account. result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNTTYPE_SYNC); // Server. String serverURL = am.getUserData(account, Constants.OPTION_SERVER); result.putString(Constants.OPTION_SERVER, serverURL); // Full username, before hashing. result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); // Username after hashing. try { String username = KeyBundle.usernameFromAccount(account.name); - Log.i("rnewman", "Account " + account.name + " hashes to " + username); + Logger.pii(LOG_TAG, "Account " + account.name + " hashes to " + username); + Logger.info(LOG_TAG, "Setting username. Null?" + (username == null)); result.putString(Constants.OPTION_USERNAME, username); } catch (NoSuchAlgorithmException e) { // Do nothing. Calling code must check for missing value. } catch (UnsupportedEncodingException e) { // Do nothing. Calling code must check for missing value. } // Sync key. final String syncKey = am.getUserData(account, Constants.OPTION_SYNCKEY); - Log.i("rnewman", "Setting Sync Key to " + syncKey); + Logger.info(LOG_TAG, "Setting Sync Key. Null? " + (syncKey == null)); result.putString(Constants.OPTION_SYNCKEY, syncKey); // Password. result.putString(AccountManager.KEY_AUTHTOKEN, password); return result; } Logger.warn(LOG_TAG, "Returning null bundle for getAuthToken."); return null; } @Override public String getAuthTokenLabel(String authTokenType) { Logger.debug(LOG_TAG, "getAuthTokenLabel()"); return null; } @Override public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException { Logger.debug(LOG_TAG, "hasFeatures()"); return null; } @Override public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { Logger.debug(LOG_TAG, "updateCredentials()"); return null; } } }
false
true
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { Logger.debug(LOG_TAG, "getAuthToken()"); if (!authTokenType.equals(Constants.AUTHTOKEN_TYPE_PLAIN)) { final Bundle result = new Bundle(); result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType"); return result; } // Extract the username and password from the Account Manager, and ask // the server for an appropriate AuthToken. Logger.info(LOG_TAG, "AccountManager.get(" + mContext + ")"); final AccountManager am = AccountManager.get(mContext); final String password = am.getPassword(account); if (password != null) { final Bundle result = new Bundle(); // This is a Sync account. result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNTTYPE_SYNC); // Server. String serverURL = am.getUserData(account, Constants.OPTION_SERVER); result.putString(Constants.OPTION_SERVER, serverURL); // Full username, before hashing. result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); // Username after hashing. try { String username = KeyBundle.usernameFromAccount(account.name); Log.i("rnewman", "Account " + account.name + " hashes to " + username); result.putString(Constants.OPTION_USERNAME, username); } catch (NoSuchAlgorithmException e) { // Do nothing. Calling code must check for missing value. } catch (UnsupportedEncodingException e) { // Do nothing. Calling code must check for missing value. } // Sync key. final String syncKey = am.getUserData(account, Constants.OPTION_SYNCKEY); Log.i("rnewman", "Setting Sync Key to " + syncKey); result.putString(Constants.OPTION_SYNCKEY, syncKey); // Password. result.putString(AccountManager.KEY_AUTHTOKEN, password); return result; } Logger.warn(LOG_TAG, "Returning null bundle for getAuthToken."); return null; }
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { Logger.debug(LOG_TAG, "getAuthToken()"); if (!authTokenType.equals(Constants.AUTHTOKEN_TYPE_PLAIN)) { final Bundle result = new Bundle(); result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType"); return result; } // Extract the username and password from the Account Manager, and ask // the server for an appropriate AuthToken. Logger.info(LOG_TAG, "AccountManager.get(" + mContext + ")"); final AccountManager am = AccountManager.get(mContext); final String password = am.getPassword(account); if (password != null) { final Bundle result = new Bundle(); // This is a Sync account. result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNTTYPE_SYNC); // Server. String serverURL = am.getUserData(account, Constants.OPTION_SERVER); result.putString(Constants.OPTION_SERVER, serverURL); // Full username, before hashing. result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); // Username after hashing. try { String username = KeyBundle.usernameFromAccount(account.name); Logger.pii(LOG_TAG, "Account " + account.name + " hashes to " + username); Logger.info(LOG_TAG, "Setting username. Null?" + (username == null)); result.putString(Constants.OPTION_USERNAME, username); } catch (NoSuchAlgorithmException e) { // Do nothing. Calling code must check for missing value. } catch (UnsupportedEncodingException e) { // Do nothing. Calling code must check for missing value. } // Sync key. final String syncKey = am.getUserData(account, Constants.OPTION_SYNCKEY); Logger.info(LOG_TAG, "Setting Sync Key. Null? " + (syncKey == null)); result.putString(Constants.OPTION_SYNCKEY, syncKey); // Password. result.putString(AccountManager.KEY_AUTHTOKEN, password); return result; } Logger.warn(LOG_TAG, "Returning null bundle for getAuthToken."); return null; }
diff --git a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/bugs/java/BugzillaHyperLinkDetector.java b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/bugs/java/BugzillaHyperLinkDetector.java index c01874f5c..05c1b936a 100644 --- a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/bugs/java/BugzillaHyperLinkDetector.java +++ b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/bugs/java/BugzillaHyperLinkDetector.java @@ -1,203 +1,203 @@ /******************************************************************************* * 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 *******************************************************************************/ package org.eclipse.mylar.bugs.java; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.Comment; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.TextElement; import org.eclipse.jdt.internal.corext.dom.NodeFinder; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.mylar.core.MylarPlugin; import org.eclipse.mylar.java.ui.editor.AbstractMylarHyperlinkDetector; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.texteditor.ITextEditor; /** * @author Shawn Minto * */ public class BugzillaHyperLinkDetector extends AbstractMylarHyperlinkDetector { public BugzillaHyperLinkDetector() { super(); } @SuppressWarnings("unchecked") public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { ITextEditor textEditor = getEditor(); if (region == null || textEditor == null || canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor)) return null; IEditorSite site= textEditor.getEditorSite(); if (site == null) return null; IJavaElement javaElement= getInputJavaElement(textEditor); if (javaElement == null) return null; CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(javaElement, ASTProvider.WAIT_NO, null); if (ast == null) return null; ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1); if (node == null || !(node instanceof TextElement || node instanceof Block)) return null; String comment = null; int commentStart = -1; if(node instanceof TextElement){ TextElement element = (TextElement)node; comment = element.getText(); commentStart = element.getStartPosition(); } else if(node instanceof Block){ Comment c = findComment(ast.getCommentList(), region.getOffset(), 1); if(c != null){ try{ IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); String commentString = document.get(c.getStartPosition(), c.getLength()); comment = getStringFromComment(c, region.getOffset(), commentString); commentStart = getLocationFromComment(c, comment, commentString) + c.getStartPosition(); } catch (BadLocationException e){ MylarPlugin.log(e, "Failed to get text for comment"); } } } if(comment == null) return null; int startOffset= region.getOffset(); int endOffset= startOffset + region.getLength(); Pattern p = Pattern.compile("^.*bug\\s+\\d+.*"); Matcher m = p.matcher(comment.toLowerCase().trim()); boolean b = m.matches(); p = Pattern.compile("^.*bug#\\s+\\d+.*"); m = p.matcher(comment.toLowerCase().trim()); boolean b2 = m.matches(); p = Pattern.compile("^.*bug\\s#\\d+.*"); m = p.matcher(comment.toLowerCase().trim()); boolean b3 = m.matches(); p = Pattern.compile("^.*bug#\\d+.*"); m = p.matcher(comment.toLowerCase().trim()); boolean b4 = m.matches(); // XXX walk forward from where we are if(b || b2 || b3 || b4){ int start = comment.toLowerCase().indexOf("bug"); int ahead = 4; if(b2 || b3 || b4){ int pound = comment.toLowerCase().indexOf("#", start); ahead = pound - start + 1; } String endComment = comment.substring(start+ahead, comment.length()); endComment = endComment.trim(); int endCommentStart = comment.indexOf(endComment); int end = comment.indexOf(" ", endCommentStart); int end2 = comment.indexOf(":", endCommentStart); - if(end2 < end || (end == -1 && end2 != -1)){ + if((end2 < end && end2 != -1) || (end == -1 && end2 != -1)){ end = end2; } if(end == -1) end = comment.length(); try{ int bugId = Integer.parseInt(comment.substring(endCommentStart, end).trim()); start += commentStart; end += commentStart; if(startOffset >= start && endOffset <= end){ IRegion sregion= new Region(start, end-start); return new IHyperlink[] {new BugzillaHyperLink(sregion, bugId)}; } } catch (NumberFormatException e){ return null; } } return null; } private int getLocationFromComment(Comment c, String commentLine, String commentString) { if(commentLine == null){ return -1; } else { return commentString.indexOf(commentLine); } } private String getStringFromComment(Comment comment, int desiredOffset, String commentString) { String [] parts = commentString.split("\n"); if(parts.length > 1){ int offset = comment.getStartPosition(); for(String part: parts){ int newOffset = offset + part.length() + 1; if(desiredOffset >= offset && desiredOffset <= newOffset){ return part; } } } else { return commentString; } return null; } private Comment findComment(List<Comment> commentList, int offset, int i) { for(Comment comment: commentList){ if(comment.getStartPosition() <= offset && (comment.getStartPosition() + comment.getLength() >= offset + i)){ return comment; } } return null; } private IJavaElement getInputJavaElement(ITextEditor editor) { IEditorInput editorInput= editor.getEditorInput(); if (editorInput instanceof IClassFileEditorInput) return ((IClassFileEditorInput)editorInput).getClassFile(); if (editor instanceof CompilationUnitEditor) return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editorInput); return null; } }
true
true
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { ITextEditor textEditor = getEditor(); if (region == null || textEditor == null || canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor)) return null; IEditorSite site= textEditor.getEditorSite(); if (site == null) return null; IJavaElement javaElement= getInputJavaElement(textEditor); if (javaElement == null) return null; CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(javaElement, ASTProvider.WAIT_NO, null); if (ast == null) return null; ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1); if (node == null || !(node instanceof TextElement || node instanceof Block)) return null; String comment = null; int commentStart = -1; if(node instanceof TextElement){ TextElement element = (TextElement)node; comment = element.getText(); commentStart = element.getStartPosition(); } else if(node instanceof Block){ Comment c = findComment(ast.getCommentList(), region.getOffset(), 1); if(c != null){ try{ IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); String commentString = document.get(c.getStartPosition(), c.getLength()); comment = getStringFromComment(c, region.getOffset(), commentString); commentStart = getLocationFromComment(c, comment, commentString) + c.getStartPosition(); } catch (BadLocationException e){ MylarPlugin.log(e, "Failed to get text for comment"); } } } if(comment == null) return null; int startOffset= region.getOffset(); int endOffset= startOffset + region.getLength(); Pattern p = Pattern.compile("^.*bug\\s+\\d+.*"); Matcher m = p.matcher(comment.toLowerCase().trim()); boolean b = m.matches(); p = Pattern.compile("^.*bug#\\s+\\d+.*"); m = p.matcher(comment.toLowerCase().trim()); boolean b2 = m.matches(); p = Pattern.compile("^.*bug\\s#\\d+.*"); m = p.matcher(comment.toLowerCase().trim()); boolean b3 = m.matches(); p = Pattern.compile("^.*bug#\\d+.*"); m = p.matcher(comment.toLowerCase().trim()); boolean b4 = m.matches(); // XXX walk forward from where we are if(b || b2 || b3 || b4){ int start = comment.toLowerCase().indexOf("bug"); int ahead = 4; if(b2 || b3 || b4){ int pound = comment.toLowerCase().indexOf("#", start); ahead = pound - start + 1; } String endComment = comment.substring(start+ahead, comment.length()); endComment = endComment.trim(); int endCommentStart = comment.indexOf(endComment); int end = comment.indexOf(" ", endCommentStart); int end2 = comment.indexOf(":", endCommentStart); if(end2 < end || (end == -1 && end2 != -1)){ end = end2; } if(end == -1) end = comment.length(); try{ int bugId = Integer.parseInt(comment.substring(endCommentStart, end).trim()); start += commentStart; end += commentStart; if(startOffset >= start && endOffset <= end){ IRegion sregion= new Region(start, end-start); return new IHyperlink[] {new BugzillaHyperLink(sregion, bugId)}; } } catch (NumberFormatException e){ return null; } } return null; }
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { ITextEditor textEditor = getEditor(); if (region == null || textEditor == null || canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor)) return null; IEditorSite site= textEditor.getEditorSite(); if (site == null) return null; IJavaElement javaElement= getInputJavaElement(textEditor); if (javaElement == null) return null; CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(javaElement, ASTProvider.WAIT_NO, null); if (ast == null) return null; ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1); if (node == null || !(node instanceof TextElement || node instanceof Block)) return null; String comment = null; int commentStart = -1; if(node instanceof TextElement){ TextElement element = (TextElement)node; comment = element.getText(); commentStart = element.getStartPosition(); } else if(node instanceof Block){ Comment c = findComment(ast.getCommentList(), region.getOffset(), 1); if(c != null){ try{ IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); String commentString = document.get(c.getStartPosition(), c.getLength()); comment = getStringFromComment(c, region.getOffset(), commentString); commentStart = getLocationFromComment(c, comment, commentString) + c.getStartPosition(); } catch (BadLocationException e){ MylarPlugin.log(e, "Failed to get text for comment"); } } } if(comment == null) return null; int startOffset= region.getOffset(); int endOffset= startOffset + region.getLength(); Pattern p = Pattern.compile("^.*bug\\s+\\d+.*"); Matcher m = p.matcher(comment.toLowerCase().trim()); boolean b = m.matches(); p = Pattern.compile("^.*bug#\\s+\\d+.*"); m = p.matcher(comment.toLowerCase().trim()); boolean b2 = m.matches(); p = Pattern.compile("^.*bug\\s#\\d+.*"); m = p.matcher(comment.toLowerCase().trim()); boolean b3 = m.matches(); p = Pattern.compile("^.*bug#\\d+.*"); m = p.matcher(comment.toLowerCase().trim()); boolean b4 = m.matches(); // XXX walk forward from where we are if(b || b2 || b3 || b4){ int start = comment.toLowerCase().indexOf("bug"); int ahead = 4; if(b2 || b3 || b4){ int pound = comment.toLowerCase().indexOf("#", start); ahead = pound - start + 1; } String endComment = comment.substring(start+ahead, comment.length()); endComment = endComment.trim(); int endCommentStart = comment.indexOf(endComment); int end = comment.indexOf(" ", endCommentStart); int end2 = comment.indexOf(":", endCommentStart); if((end2 < end && end2 != -1) || (end == -1 && end2 != -1)){ end = end2; } if(end == -1) end = comment.length(); try{ int bugId = Integer.parseInt(comment.substring(endCommentStart, end).trim()); start += commentStart; end += commentStart; if(startOffset >= start && endOffset <= end){ IRegion sregion= new Region(start, end-start); return new IHyperlink[] {new BugzillaHyperLink(sregion, bugId)}; } } catch (NumberFormatException e){ return null; } } return null; }
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java b/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java index 48d0dc8444..536b1cfe48 100644 --- a/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java +++ b/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java @@ -1,370 +1,371 @@ package org.apache.lucene.index; /* * 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. */ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.TextField; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util._TestUtil; public class TestDocsAndPositions extends LuceneTestCase { private String fieldName; @Override public void setUp() throws Exception { super.setUp(); fieldName = "field" + random().nextInt(); } /** * Simple testcase for {@link DocsAndPositionsEnum} */ public void testPositionsSimple() throws IOException { Directory directory = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), directory, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))); for (int i = 0; i < 39; i++) { Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.setOmitNorms(true); doc.add(newField(fieldName, "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10", customType)); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); int num = atLeast(13); for (int i = 0; i < num; i++) { BytesRef bytes = new BytesRef("1"); IndexReaderContext topReaderContext = reader.getTopReaderContext(); for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader(), bytes, null); assertNotNull(docsAndPosEnum); if (atomicReaderContext.reader().maxDoc() == 0) { continue; } final int advance = docsAndPosEnum.advance(random().nextInt(atomicReaderContext.reader().maxDoc())); do { String msg = "Advanced to: " + advance + " current doc: " + docsAndPosEnum.docID(); // TODO: + " usePayloads: " + usePayload; assertEquals(msg, 4, docsAndPosEnum.freq()); assertEquals(msg, 0, docsAndPosEnum.nextPosition()); assertEquals(msg, 4, docsAndPosEnum.freq()); assertEquals(msg, 10, docsAndPosEnum.nextPosition()); assertEquals(msg, 4, docsAndPosEnum.freq()); assertEquals(msg, 20, docsAndPosEnum.nextPosition()); assertEquals(msg, 4, docsAndPosEnum.freq()); assertEquals(msg, 30, docsAndPosEnum.nextPosition()); } while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); } } reader.close(); directory.close(); } public DocsAndPositionsEnum getDocsAndPositions(AtomicReader reader, BytesRef bytes, Bits liveDocs) throws IOException { return reader.termPositionsEnum(null, fieldName, bytes, false); } /** * this test indexes random numbers within a range into a field and checks * their occurrences by searching for a number from that range selected at * random. All positions for that number are saved up front and compared to * the enums positions. */ public void testRandomPositions() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy())); int numDocs = atLeast(47); int max = 1051; int term = random().nextInt(max); Integer[][] positionsInDoc = new Integer[numDocs][]; FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.setOmitNorms(true); for (int i = 0; i < numDocs; i++) { Document doc = new Document(); ArrayList<Integer> positions = new ArrayList<Integer>(); StringBuilder builder = new StringBuilder(); int num = atLeast(131); for (int j = 0; j < num; j++) { int nextInt = random().nextInt(max); builder.append(nextInt).append(" "); if (nextInt == term) { positions.add(Integer.valueOf(j)); } } if (positions.size() == 0) { builder.append(term); positions.add(num); } doc.add(newField(fieldName, builder.toString(), customType)); positionsInDoc[i] = positions.toArray(new Integer[0]); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); int num = atLeast(13); for (int i = 0; i < num; i++) { BytesRef bytes = new BytesRef("" + term); IndexReaderContext topReaderContext = reader.getTopReaderContext(); for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader(), bytes, null); assertNotNull(docsAndPosEnum); int initDoc = 0; int maxDoc = atomicReaderContext.reader().maxDoc(); // initially advance or do next doc if (random().nextBoolean()) { initDoc = docsAndPosEnum.nextDoc(); } else { initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc)); } // now run through the scorer and check if all positions are there... do { int docID = docsAndPosEnum.docID(); if (docID == DocIdSetIterator.NO_MORE_DOCS) { break; } Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID]; assertEquals(pos.length, docsAndPosEnum.freq()); // number of positions read should be random - don't read all of them // allways final int howMany = random().nextInt(20) == 0 ? pos.length - random().nextInt(pos.length) : pos.length; for (int j = 0; j < howMany; j++) { assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: " + docID + " base: " + atomicReaderContext.docBase + " positions: " + Arrays.toString(pos) /* TODO: + " usePayloads: " + usePayload*/, pos[j].intValue(), docsAndPosEnum.nextPosition()); } if (random().nextInt(10) == 0) { // once is a while advance - docsAndPosEnum - .advance(docID + 1 + random().nextInt((maxDoc - docID))); + if (docsAndPosEnum.advance(docID + 1 + random().nextInt((maxDoc - docID))) == DocIdSetIterator.NO_MORE_DOCS) { + break; + } } } while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); } } reader.close(); dir.close(); } public void testRandomDocs() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy())); int numDocs = atLeast(49); int max = 15678; int term = random().nextInt(max); int[] freqInDoc = new int[numDocs]; FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.setOmitNorms(true); for (int i = 0; i < numDocs; i++) { Document doc = new Document(); StringBuilder builder = new StringBuilder(); for (int j = 0; j < 199; j++) { int nextInt = random().nextInt(max); builder.append(nextInt).append(' '); if (nextInt == term) { freqInDoc[i]++; } } doc.add(newField(fieldName, builder.toString(), customType)); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); int num = atLeast(13); for (int i = 0; i < num; i++) { BytesRef bytes = new BytesRef("" + term); IndexReaderContext topReaderContext = reader.getTopReaderContext(); for (AtomicReaderContext context : topReaderContext.leaves()) { int maxDoc = context.reader().maxDoc(); DocsEnum docsEnum = _TestUtil.docs(random(), context.reader(), fieldName, bytes, null, null, true); if (findNext(freqInDoc, context.docBase, context.docBase + maxDoc) == Integer.MAX_VALUE) { assertNull(docsEnum); continue; } assertNotNull(docsEnum); docsEnum.nextDoc(); for (int j = 0; j < maxDoc; j++) { if (freqInDoc[context.docBase + j] != 0) { assertEquals(j, docsEnum.docID()); assertEquals(docsEnum.freq(), freqInDoc[context.docBase +j]); if (i % 2 == 0 && random().nextInt(10) == 0) { int next = findNext(freqInDoc, context.docBase+j+1, context.docBase + maxDoc) - context.docBase; int advancedTo = docsEnum.advance(next); if (next >= maxDoc) { assertEquals(DocIdSetIterator.NO_MORE_DOCS, advancedTo); } else { assertTrue("advanced to: " +advancedTo + " but should be <= " + next, next >= advancedTo); } } else { docsEnum.nextDoc(); } } } assertEquals("docBase: " + context.docBase + " maxDoc: " + maxDoc + " " + docsEnum.getClass(), DocIdSetIterator.NO_MORE_DOCS, docsEnum.docID()); } } reader.close(); dir.close(); } private static int findNext(int[] docs, int pos, int max) { for (int i = pos; i < max; i++) { if( docs[i] != 0) { return i; } } return Integer.MAX_VALUE; } /** * tests retrieval of positions for terms that have a large number of * occurrences to force test of buffer refill during positions iteration. */ public void testLargeNumberOfPositions() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))); int howMany = 1000; FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.setOmitNorms(true); for (int i = 0; i < 39; i++) { Document doc = new Document(); StringBuilder builder = new StringBuilder(); for (int j = 0; j < howMany; j++) { if (j % 2 == 0) { builder.append("even "); } else { builder.append("odd "); } } doc.add(newField(fieldName, builder.toString(), customType)); writer.addDocument(doc); } // now do searches IndexReader reader = writer.getReader(); writer.close(); int num = atLeast(13); for (int i = 0; i < num; i++) { BytesRef bytes = new BytesRef("even"); IndexReaderContext topReaderContext = reader.getTopReaderContext(); for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader(), bytes, null); assertNotNull(docsAndPosEnum); int initDoc = 0; int maxDoc = atomicReaderContext.reader().maxDoc(); // initially advance or do next doc if (random().nextBoolean()) { initDoc = docsAndPosEnum.nextDoc(); } else { initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc)); } String msg = "Iteration: " + i + " initDoc: " + initDoc; // TODO: + " payloads: " + usePayload; assertEquals(howMany / 2, docsAndPosEnum.freq()); for (int j = 0; j < howMany; j += 2) { assertEquals("position missmatch index: " + j + " with freq: " + docsAndPosEnum.freq() + " -- " + msg, j, docsAndPosEnum.nextPosition()); } } } reader.close(); dir.close(); } public void testDocsEnumStart() throws Exception { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), dir); Document doc = new Document(); doc.add(newStringField("foo", "bar", Field.Store.NO)); writer.addDocument(doc); DirectoryReader reader = writer.getReader(); AtomicReader r = getOnlySegmentReader(reader); DocsEnum disi = _TestUtil.docs(random(), r, "foo", new BytesRef("bar"), null, null, false); int docid = disi.docID(); assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS); assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); // now reuse and check again TermsEnum te = r.terms("foo").iterator(null); assertTrue(te.seekExact(new BytesRef("bar"), true)); disi = _TestUtil.docs(random(), te, null, disi, false); docid = disi.docID(); assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS); assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); writer.close(); r.close(); dir.close(); } public void testDocsAndPositionsEnumStart() throws Exception { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), dir); Document doc = new Document(); doc.add(newTextField("foo", "bar", Field.Store.NO)); writer.addDocument(doc); DirectoryReader reader = writer.getReader(); AtomicReader r = getOnlySegmentReader(reader); DocsAndPositionsEnum disi = r.termPositionsEnum(null, "foo", new BytesRef("bar"), false); int docid = disi.docID(); assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS); assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); // now reuse and check again TermsEnum te = r.terms("foo").iterator(null); assertTrue(te.seekExact(new BytesRef("bar"), true)); disi = te.docsAndPositions(null, disi, false); docid = disi.docID(); assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS); assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); writer.close(); r.close(); dir.close(); } }
true
true
public void testRandomPositions() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy())); int numDocs = atLeast(47); int max = 1051; int term = random().nextInt(max); Integer[][] positionsInDoc = new Integer[numDocs][]; FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.setOmitNorms(true); for (int i = 0; i < numDocs; i++) { Document doc = new Document(); ArrayList<Integer> positions = new ArrayList<Integer>(); StringBuilder builder = new StringBuilder(); int num = atLeast(131); for (int j = 0; j < num; j++) { int nextInt = random().nextInt(max); builder.append(nextInt).append(" "); if (nextInt == term) { positions.add(Integer.valueOf(j)); } } if (positions.size() == 0) { builder.append(term); positions.add(num); } doc.add(newField(fieldName, builder.toString(), customType)); positionsInDoc[i] = positions.toArray(new Integer[0]); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); int num = atLeast(13); for (int i = 0; i < num; i++) { BytesRef bytes = new BytesRef("" + term); IndexReaderContext topReaderContext = reader.getTopReaderContext(); for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader(), bytes, null); assertNotNull(docsAndPosEnum); int initDoc = 0; int maxDoc = atomicReaderContext.reader().maxDoc(); // initially advance or do next doc if (random().nextBoolean()) { initDoc = docsAndPosEnum.nextDoc(); } else { initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc)); } // now run through the scorer and check if all positions are there... do { int docID = docsAndPosEnum.docID(); if (docID == DocIdSetIterator.NO_MORE_DOCS) { break; } Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID]; assertEquals(pos.length, docsAndPosEnum.freq()); // number of positions read should be random - don't read all of them // allways final int howMany = random().nextInt(20) == 0 ? pos.length - random().nextInt(pos.length) : pos.length; for (int j = 0; j < howMany; j++) { assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: " + docID + " base: " + atomicReaderContext.docBase + " positions: " + Arrays.toString(pos) /* TODO: + " usePayloads: " + usePayload*/, pos[j].intValue(), docsAndPosEnum.nextPosition()); } if (random().nextInt(10) == 0) { // once is a while advance docsAndPosEnum .advance(docID + 1 + random().nextInt((maxDoc - docID))); } } while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); } } reader.close(); dir.close(); }
public void testRandomPositions() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy())); int numDocs = atLeast(47); int max = 1051; int term = random().nextInt(max); Integer[][] positionsInDoc = new Integer[numDocs][]; FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.setOmitNorms(true); for (int i = 0; i < numDocs; i++) { Document doc = new Document(); ArrayList<Integer> positions = new ArrayList<Integer>(); StringBuilder builder = new StringBuilder(); int num = atLeast(131); for (int j = 0; j < num; j++) { int nextInt = random().nextInt(max); builder.append(nextInt).append(" "); if (nextInt == term) { positions.add(Integer.valueOf(j)); } } if (positions.size() == 0) { builder.append(term); positions.add(num); } doc.add(newField(fieldName, builder.toString(), customType)); positionsInDoc[i] = positions.toArray(new Integer[0]); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); int num = atLeast(13); for (int i = 0; i < num; i++) { BytesRef bytes = new BytesRef("" + term); IndexReaderContext topReaderContext = reader.getTopReaderContext(); for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader(), bytes, null); assertNotNull(docsAndPosEnum); int initDoc = 0; int maxDoc = atomicReaderContext.reader().maxDoc(); // initially advance or do next doc if (random().nextBoolean()) { initDoc = docsAndPosEnum.nextDoc(); } else { initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc)); } // now run through the scorer and check if all positions are there... do { int docID = docsAndPosEnum.docID(); if (docID == DocIdSetIterator.NO_MORE_DOCS) { break; } Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID]; assertEquals(pos.length, docsAndPosEnum.freq()); // number of positions read should be random - don't read all of them // allways final int howMany = random().nextInt(20) == 0 ? pos.length - random().nextInt(pos.length) : pos.length; for (int j = 0; j < howMany; j++) { assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: " + docID + " base: " + atomicReaderContext.docBase + " positions: " + Arrays.toString(pos) /* TODO: + " usePayloads: " + usePayload*/, pos[j].intValue(), docsAndPosEnum.nextPosition()); } if (random().nextInt(10) == 0) { // once is a while advance if (docsAndPosEnum.advance(docID + 1 + random().nextInt((maxDoc - docID))) == DocIdSetIterator.NO_MORE_DOCS) { break; } } } while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); } } reader.close(); dir.close(); }
diff --git a/src/prettify/lang/LangCss.java b/src/prettify/lang/LangCss.java index f644f2f..ad8b391 100644 --- a/src/prettify/lang/LangCss.java +++ b/src/prettify/lang/LangCss.java @@ -1,112 +1,112 @@ // Copyright (C) 2009 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 prettify.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import prettify.parser.Prettify; /** * This is similar to the lang-css.js in JavaScript Prettify. * * All comments are adapted from the JavaScript Prettify. * * <p> * Registers a language handler for CSS. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-css"></pre> * * * http://www.w3.org/TR/CSS21/grammar.html Section G2 defines the lexical * grammar. This scheme does not recognize keywords containing escapes. * * @author [email protected] */ public class LangCss extends Lang { public LangCss() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // The space production <s> _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^[ \t\r\n\f]+"), null, " \t\r\n\f"})); // Quoted strings. <string1> and <string2> _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\n\r\f\\\\\\\"]|\\\\(?:\r\n?|\n|\f)|\\\\[\\s\\S])*\\\""), null})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\'(?:[^\n\r\f\\\\\\']|\\\\(?:\r\n?|\n|\f)|\\\\[\\s\\S])*\\'"), null})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{"lang-css-str", Pattern.compile("^url\\(([^\\)\\\"\\']+)\\)", Pattern.CASE_INSENSITIVE)})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:url|rgb|\\!important|@import|@page|@media|@charset|inherit)(?=[^\\-\\w]|$)", Pattern.CASE_INSENSITIVE), null})); // A property name -- an identifier followed by a colon. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{"lang-css-kw", Pattern.compile("^(-?(?:[_a-z]|(?:\\\\[0-9a-f]+ ?))(?:[_a-z0-9\\-]|\\\\(?:\\\\[0-9a-f]+ ?))*)\\s*:", Pattern.CASE_INSENSITIVE)})); // A C style block comment. The <comment> production. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^\\/\\*[^*]*\\*+(?:[^\\/*][^*]*\\*+)*\\/")})); // Escaping text spans _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^(?:<!--|-->)")})); // A number possibly containing a suffix. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:\\d+|\\d*\\.\\d+)(?:%|[a-z]+)?", Pattern.CASE_INSENSITIVE)})); // A hex color - _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^#(?:[0-9a-f]{3}){1,2}", Pattern.CASE_INSENSITIVE)})); + _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^#(?:[0-9a-f]{3}){1,2}\\b", Pattern.CASE_INSENSITIVE)})); // An identifier _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^-?(?:[_a-z]|(?:\\\\[\\da-f]+ ?))(?:[_a-z\\d\\-]|\\\\(?:\\\\[\\da-f]+ ?))*", Pattern.CASE_INSENSITIVE)})); // A run of punctuation _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[^\\s\\w\\'\\\"]+", Pattern.CASE_INSENSITIVE)})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); setExtendedLangs(Arrays.asList(new Lang[]{new LangCssKeyword(), new LangCssString()})); } public static List<String> getFileExtensions() { return Arrays.asList(new String[]{"css"}); } protected static class LangCssKeyword extends Lang { public LangCssKeyword() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^-?(?:[_a-z]|(?:\\\\[\\da-f]+ ?))(?:[_a-z\\d\\-]|\\\\(?:\\\\[\\da-f]+ ?))*", Pattern.CASE_INSENSITIVE)})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); } public static List<String> getFileExtensions() { return Arrays.asList(new String[]{"css-kw"}); } } protected static class LangCssString extends Lang { public LangCssString() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^[^\\)\\\"\\']+")})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); } public static List<String> getFileExtensions() { return Arrays.asList(new String[]{"css-str"}); } } }
true
true
public LangCss() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // The space production <s> _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^[ \t\r\n\f]+"), null, " \t\r\n\f"})); // Quoted strings. <string1> and <string2> _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\n\r\f\\\\\\\"]|\\\\(?:\r\n?|\n|\f)|\\\\[\\s\\S])*\\\""), null})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\'(?:[^\n\r\f\\\\\\']|\\\\(?:\r\n?|\n|\f)|\\\\[\\s\\S])*\\'"), null})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{"lang-css-str", Pattern.compile("^url\\(([^\\)\\\"\\']+)\\)", Pattern.CASE_INSENSITIVE)})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:url|rgb|\\!important|@import|@page|@media|@charset|inherit)(?=[^\\-\\w]|$)", Pattern.CASE_INSENSITIVE), null})); // A property name -- an identifier followed by a colon. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{"lang-css-kw", Pattern.compile("^(-?(?:[_a-z]|(?:\\\\[0-9a-f]+ ?))(?:[_a-z0-9\\-]|\\\\(?:\\\\[0-9a-f]+ ?))*)\\s*:", Pattern.CASE_INSENSITIVE)})); // A C style block comment. The <comment> production. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^\\/\\*[^*]*\\*+(?:[^\\/*][^*]*\\*+)*\\/")})); // Escaping text spans _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^(?:<!--|-->)")})); // A number possibly containing a suffix. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:\\d+|\\d*\\.\\d+)(?:%|[a-z]+)?", Pattern.CASE_INSENSITIVE)})); // A hex color _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^#(?:[0-9a-f]{3}){1,2}", Pattern.CASE_INSENSITIVE)})); // An identifier _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^-?(?:[_a-z]|(?:\\\\[\\da-f]+ ?))(?:[_a-z\\d\\-]|\\\\(?:\\\\[\\da-f]+ ?))*", Pattern.CASE_INSENSITIVE)})); // A run of punctuation _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[^\\s\\w\\'\\\"]+", Pattern.CASE_INSENSITIVE)})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); setExtendedLangs(Arrays.asList(new Lang[]{new LangCssKeyword(), new LangCssString()})); }
public LangCss() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // The space production <s> _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^[ \t\r\n\f]+"), null, " \t\r\n\f"})); // Quoted strings. <string1> and <string2> _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\n\r\f\\\\\\\"]|\\\\(?:\r\n?|\n|\f)|\\\\[\\s\\S])*\\\""), null})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\'(?:[^\n\r\f\\\\\\']|\\\\(?:\r\n?|\n|\f)|\\\\[\\s\\S])*\\'"), null})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{"lang-css-str", Pattern.compile("^url\\(([^\\)\\\"\\']+)\\)", Pattern.CASE_INSENSITIVE)})); _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:url|rgb|\\!important|@import|@page|@media|@charset|inherit)(?=[^\\-\\w]|$)", Pattern.CASE_INSENSITIVE), null})); // A property name -- an identifier followed by a colon. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{"lang-css-kw", Pattern.compile("^(-?(?:[_a-z]|(?:\\\\[0-9a-f]+ ?))(?:[_a-z0-9\\-]|\\\\(?:\\\\[0-9a-f]+ ?))*)\\s*:", Pattern.CASE_INSENSITIVE)})); // A C style block comment. The <comment> production. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^\\/\\*[^*]*\\*+(?:[^\\/*][^*]*\\*+)*\\/")})); // Escaping text spans _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^(?:<!--|-->)")})); // A number possibly containing a suffix. _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:\\d+|\\d*\\.\\d+)(?:%|[a-z]+)?", Pattern.CASE_INSENSITIVE)})); // A hex color _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^#(?:[0-9a-f]{3}){1,2}\\b", Pattern.CASE_INSENSITIVE)})); // An identifier _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("^-?(?:[_a-z]|(?:\\\\[\\da-f]+ ?))(?:[_a-z\\d\\-]|\\\\(?:\\\\[\\da-f]+ ?))*", Pattern.CASE_INSENSITIVE)})); // A run of punctuation _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[^\\s\\w\\'\\\"]+", Pattern.CASE_INSENSITIVE)})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); setExtendedLangs(Arrays.asList(new Lang[]{new LangCssKeyword(), new LangCssString()})); }
diff --git a/JMathTextField.java b/JMathTextField.java index 093ac02..6ffd33a 100644 --- a/JMathTextField.java +++ b/JMathTextField.java @@ -1,139 +1,139 @@ package applets.Termumformungen$in$der$Technik_03_Logistik; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.DocumentFilter; import javax.swing.text.PlainDocument; public class JMathTextField extends JTextField { private static final long serialVersionUID = 3991754180692357067L; private OperatorTree operatorTree = new OperatorTree(); public OperatorTree getOperatorTree() { return operatorTree; } protected void updateByOpTree(javax.swing.text.DocumentFilter.FilterBypass fb) { String oldStr = JMathTextField.this.getText(); String newStr = operatorTree.toString(); int commonStart = Utils.equalStartLen(oldStr, newStr); int commonEnd = Utils.equalEndLen(oldStr, newStr); if(commonEnd + commonStart >= Math.min(oldStr.length(), newStr.length())) commonEnd = Math.min(oldStr.length(), newStr.length()) - commonStart; try { fb.replace(commonStart, oldStr.length() - commonEnd - commonStart, newStr.substring(commonStart, newStr.length() - commonEnd), null); } catch (BadLocationException e) { // this should not happen. we should have checked this. this whole function should be safe throw new AssertionError(e); } } @Override protected Document createDefaultModel() { PlainDocument d = (PlainDocument) super.createDefaultModel(); d.setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { replace(fb, offset, 0, string, attr); } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { replace(fb, offset, length, "", null); } @Override public void replace(FilterBypass fb, int replOffset, int replLen, String string, AttributeSet attrs) throws BadLocationException { String s = JMathTextField.this.getText(); boolean insertedDummyChar = false; boolean insertedBrackets = false; String marked = s.substring(replOffset, replOffset + replLen); if(string.matches(" |\\)") && replOffset + 1 < s.length() && s.substring(replOffset, replOffset + 1).equals(string)) { JMathTextField.this.setCaretPosition(replOffset + 1); return; } string = string.replace(" ", ""); if(string.isEmpty() && marked.equals("(")) { int count = 1; while(replOffset + replLen < s.length()) { replLen++; marked = s.substring(replOffset, replOffset + replLen); if(marked.charAt(0) == '(') count++; else if(marked.charAt(0) == ')') count--; if(count == 0) break; } } else if(string.isEmpty() && marked.equals(")")) { int count = -1; while(replOffset > 0) { replOffset--; replLen++; marked = s.substring(replOffset, replOffset + replLen); if(marked.charAt(0) == '(') count++; else if(marked.charAt(0) == ')') count--; if(count == 0) break; } } - if(replLen == 0 && string.matches("\\+|-|\\*|/|^|=")) { - if(s.substring(replOffset).matches(" *(((\\+|-|∙|/|^|=|\\)).*)|)")) { + if(replLen == 0 && string.matches("\\+|-|\\*|/|\\^|=")) { + if(s.substring(replOffset).matches(" *(((\\+|-|∙|/|\\^|=|\\)).*)|)")) { string = string + "_"; insertedDummyChar = true; } else if(s.substring(replOffset).matches(" .*")) { string = "_" + string; insertedDummyChar = true; } } else if(string.matches("\\(")) { if(replLen == 0 || marked.equals("_")) { string = "(_)"; insertedDummyChar = true; } else { string = "(" + marked + ")"; insertedBrackets = true; } } else if(string.matches("\\)")) return; // ignore that // situation: A = B, press DEL -> make it A = _ if(string.isEmpty() && replOffset > 0 && replLen == 1 && s.substring(replOffset - 1, replOffset).equals(" ") && !marked.equals("_")) { string = "_"; insertedDummyChar = true; } setNewString(fb, s.substring(0, replOffset) + string + s.substring(replOffset + replLen)); if(insertedDummyChar) { int p = JMathTextField.this.getText().indexOf('_'); if(p >= 0) { JMathTextField.this.setCaretPosition(p); JMathTextField.this.moveCaretPosition(p + 1); } } else if(insertedBrackets) { // move just before the ')' if(JMathTextField.this.getCaretPosition() > 0) JMathTextField.this.setCaretPosition(JMathTextField.this.getCaretPosition() - 1); } } synchronized void setNewString(FilterBypass fb, String tempStr) throws BadLocationException { operatorTree = OTParser.parse(tempStr, null); JMathTextField.this.updateByOpTree(fb); } }); return d; } }
true
true
protected Document createDefaultModel() { PlainDocument d = (PlainDocument) super.createDefaultModel(); d.setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { replace(fb, offset, 0, string, attr); } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { replace(fb, offset, length, "", null); } @Override public void replace(FilterBypass fb, int replOffset, int replLen, String string, AttributeSet attrs) throws BadLocationException { String s = JMathTextField.this.getText(); boolean insertedDummyChar = false; boolean insertedBrackets = false; String marked = s.substring(replOffset, replOffset + replLen); if(string.matches(" |\\)") && replOffset + 1 < s.length() && s.substring(replOffset, replOffset + 1).equals(string)) { JMathTextField.this.setCaretPosition(replOffset + 1); return; } string = string.replace(" ", ""); if(string.isEmpty() && marked.equals("(")) { int count = 1; while(replOffset + replLen < s.length()) { replLen++; marked = s.substring(replOffset, replOffset + replLen); if(marked.charAt(0) == '(') count++; else if(marked.charAt(0) == ')') count--; if(count == 0) break; } } else if(string.isEmpty() && marked.equals(")")) { int count = -1; while(replOffset > 0) { replOffset--; replLen++; marked = s.substring(replOffset, replOffset + replLen); if(marked.charAt(0) == '(') count++; else if(marked.charAt(0) == ')') count--; if(count == 0) break; } } if(replLen == 0 && string.matches("\\+|-|\\*|/|^|=")) { if(s.substring(replOffset).matches(" *(((\\+|-|∙|/|^|=|\\)).*)|)")) { string = string + "_"; insertedDummyChar = true; } else if(s.substring(replOffset).matches(" .*")) { string = "_" + string; insertedDummyChar = true; } } else if(string.matches("\\(")) { if(replLen == 0 || marked.equals("_")) { string = "(_)"; insertedDummyChar = true; } else { string = "(" + marked + ")"; insertedBrackets = true; } } else if(string.matches("\\)")) return; // ignore that // situation: A = B, press DEL -> make it A = _ if(string.isEmpty() && replOffset > 0 && replLen == 1 && s.substring(replOffset - 1, replOffset).equals(" ") && !marked.equals("_")) { string = "_"; insertedDummyChar = true; } setNewString(fb, s.substring(0, replOffset) + string + s.substring(replOffset + replLen)); if(insertedDummyChar) { int p = JMathTextField.this.getText().indexOf('_'); if(p >= 0) { JMathTextField.this.setCaretPosition(p); JMathTextField.this.moveCaretPosition(p + 1); } } else if(insertedBrackets) { // move just before the ')' if(JMathTextField.this.getCaretPosition() > 0) JMathTextField.this.setCaretPosition(JMathTextField.this.getCaretPosition() - 1); } } synchronized void setNewString(FilterBypass fb, String tempStr) throws BadLocationException { operatorTree = OTParser.parse(tempStr, null); JMathTextField.this.updateByOpTree(fb); } }); return d; }
protected Document createDefaultModel() { PlainDocument d = (PlainDocument) super.createDefaultModel(); d.setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { replace(fb, offset, 0, string, attr); } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { replace(fb, offset, length, "", null); } @Override public void replace(FilterBypass fb, int replOffset, int replLen, String string, AttributeSet attrs) throws BadLocationException { String s = JMathTextField.this.getText(); boolean insertedDummyChar = false; boolean insertedBrackets = false; String marked = s.substring(replOffset, replOffset + replLen); if(string.matches(" |\\)") && replOffset + 1 < s.length() && s.substring(replOffset, replOffset + 1).equals(string)) { JMathTextField.this.setCaretPosition(replOffset + 1); return; } string = string.replace(" ", ""); if(string.isEmpty() && marked.equals("(")) { int count = 1; while(replOffset + replLen < s.length()) { replLen++; marked = s.substring(replOffset, replOffset + replLen); if(marked.charAt(0) == '(') count++; else if(marked.charAt(0) == ')') count--; if(count == 0) break; } } else if(string.isEmpty() && marked.equals(")")) { int count = -1; while(replOffset > 0) { replOffset--; replLen++; marked = s.substring(replOffset, replOffset + replLen); if(marked.charAt(0) == '(') count++; else if(marked.charAt(0) == ')') count--; if(count == 0) break; } } if(replLen == 0 && string.matches("\\+|-|\\*|/|\\^|=")) { if(s.substring(replOffset).matches(" *(((\\+|-|∙|/|\\^|=|\\)).*)|)")) { string = string + "_"; insertedDummyChar = true; } else if(s.substring(replOffset).matches(" .*")) { string = "_" + string; insertedDummyChar = true; } } else if(string.matches("\\(")) { if(replLen == 0 || marked.equals("_")) { string = "(_)"; insertedDummyChar = true; } else { string = "(" + marked + ")"; insertedBrackets = true; } } else if(string.matches("\\)")) return; // ignore that // situation: A = B, press DEL -> make it A = _ if(string.isEmpty() && replOffset > 0 && replLen == 1 && s.substring(replOffset - 1, replOffset).equals(" ") && !marked.equals("_")) { string = "_"; insertedDummyChar = true; } setNewString(fb, s.substring(0, replOffset) + string + s.substring(replOffset + replLen)); if(insertedDummyChar) { int p = JMathTextField.this.getText().indexOf('_'); if(p >= 0) { JMathTextField.this.setCaretPosition(p); JMathTextField.this.moveCaretPosition(p + 1); } } else if(insertedBrackets) { // move just before the ')' if(JMathTextField.this.getCaretPosition() > 0) JMathTextField.this.setCaretPosition(JMathTextField.this.getCaretPosition() - 1); } } synchronized void setNewString(FilterBypass fb, String tempStr) throws BadLocationException { operatorTree = OTParser.parse(tempStr, null); JMathTextField.this.updateByOpTree(fb); } }); return d; }
diff --git a/src/bitstercli/RUBTClient.java b/src/bitstercli/RUBTClient.java index e6fc486..25f1071 100644 --- a/src/bitstercli/RUBTClient.java +++ b/src/bitstercli/RUBTClient.java @@ -1,74 +1,77 @@ package bitstercli; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.*; import libbitster.BencodingException; import libbitster.Manager; import libbitster.TorrentInfo; /** * Driver class for Bitster * @author Martin Miralles-Cordal */ public class RUBTClient { /** * @param args Takes in a torrent file and a destination file name as arguments */ public static void main(String[] args) { Logger log = Logger.getLogger("bitster"); // check if we have a valid number of arguments if(args.length != 2) { log.log(Level.SEVERE, "Error: Invalid number of arguments."); return; } // validate argument 1 File torrentFile = new File(args[0]); if(!torrentFile.exists() || torrentFile.isDirectory()) { log.log(Level.SEVERE, "Error: " + args[0] + " is not a file."); return; } // validate argument 2 File dest = new File(args[1]); if(dest.exists()) + { log.log(Level.SEVERE, "Error: destination file exists."); + return; + } else { try { // try to create file to validate target name dest.createNewFile(); dest.delete(); } catch (IOException e) { log.log(Level.SEVERE, "Error: invalid destination file."); return; } } try { byte[] torrentBytes = new byte[(int) torrentFile.length()]; DataInputStream dis; dis = new DataInputStream(new FileInputStream(torrentFile)); dis.readFully(torrentBytes); dis.close(); TorrentInfo metainfo = new TorrentInfo(torrentBytes); Manager manager = new Manager(metainfo, dest); manager.start(); } catch (IOException e) { log.log(Level.SEVERE, "Error: unable to read torrent file."); return; } catch (BencodingException e) { log.log(Level.SEVERE, "Error: invalid or corrupt torrent file."); return; } } }
false
true
public static void main(String[] args) { Logger log = Logger.getLogger("bitster"); // check if we have a valid number of arguments if(args.length != 2) { log.log(Level.SEVERE, "Error: Invalid number of arguments."); return; } // validate argument 1 File torrentFile = new File(args[0]); if(!torrentFile.exists() || torrentFile.isDirectory()) { log.log(Level.SEVERE, "Error: " + args[0] + " is not a file."); return; } // validate argument 2 File dest = new File(args[1]); if(dest.exists()) log.log(Level.SEVERE, "Error: destination file exists."); else { try { // try to create file to validate target name dest.createNewFile(); dest.delete(); } catch (IOException e) { log.log(Level.SEVERE, "Error: invalid destination file."); return; } } try { byte[] torrentBytes = new byte[(int) torrentFile.length()]; DataInputStream dis; dis = new DataInputStream(new FileInputStream(torrentFile)); dis.readFully(torrentBytes); dis.close(); TorrentInfo metainfo = new TorrentInfo(torrentBytes); Manager manager = new Manager(metainfo, dest); manager.start(); } catch (IOException e) { log.log(Level.SEVERE, "Error: unable to read torrent file."); return; } catch (BencodingException e) { log.log(Level.SEVERE, "Error: invalid or corrupt torrent file."); return; } }
public static void main(String[] args) { Logger log = Logger.getLogger("bitster"); // check if we have a valid number of arguments if(args.length != 2) { log.log(Level.SEVERE, "Error: Invalid number of arguments."); return; } // validate argument 1 File torrentFile = new File(args[0]); if(!torrentFile.exists() || torrentFile.isDirectory()) { log.log(Level.SEVERE, "Error: " + args[0] + " is not a file."); return; } // validate argument 2 File dest = new File(args[1]); if(dest.exists()) { log.log(Level.SEVERE, "Error: destination file exists."); return; } else { try { // try to create file to validate target name dest.createNewFile(); dest.delete(); } catch (IOException e) { log.log(Level.SEVERE, "Error: invalid destination file."); return; } } try { byte[] torrentBytes = new byte[(int) torrentFile.length()]; DataInputStream dis; dis = new DataInputStream(new FileInputStream(torrentFile)); dis.readFully(torrentBytes); dis.close(); TorrentInfo metainfo = new TorrentInfo(torrentBytes); Manager manager = new Manager(metainfo, dest); manager.start(); } catch (IOException e) { log.log(Level.SEVERE, "Error: unable to read torrent file."); return; } catch (BencodingException e) { log.log(Level.SEVERE, "Error: invalid or corrupt torrent file."); return; } }
diff --git a/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/SyntheticAccessorResolver.java b/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/SyntheticAccessorResolver.java index 3494b070..09ac7968 100644 --- a/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/SyntheticAccessorResolver.java +++ b/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/SyntheticAccessorResolver.java @@ -1,138 +1,146 @@ /* * [The "BSD licence"] * Copyright (c) 2011 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.*; import org.jf.dexlib.Code.Format.Instruction22c; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Util.AccessFlags; import java.util.HashMap; public class SyntheticAccessorResolver { public static final int METHOD = 0; public static final int GETTER = 1; public static final int SETTER = 2; private final DexFileClassMap classMap; private final HashMap<MethodIdItem, AccessedMember> resolvedAccessors = new HashMap<MethodIdItem, AccessedMember>(); public SyntheticAccessorResolver(DexFile dexFile) { classMap = new DexFileClassMap(dexFile); } public static boolean looksLikeSyntheticAccessor(MethodIdItem methodIdItem) { return methodIdItem.getMethodName().getStringValue().startsWith("access$"); } public AccessedMember getAccessedMember(MethodIdItem methodIdItem) { AccessedMember accessedMember = resolvedAccessors.get(methodIdItem); if (accessedMember != null) { return accessedMember; } ClassDefItem classDefItem = classMap.getClassDefByType(methodIdItem.getContainingClass()); if (classDefItem == null) { return null; } ClassDataItem classDataItem = classDefItem.getClassData(); if (classDataItem == null) { return null; } ClassDataItem.EncodedMethod encodedMethod = classDataItem.findDirectMethodByMethodId(methodIdItem); if (encodedMethod == null) { return null; } //A synthetic accessor will be marked synthetic if ((encodedMethod.accessFlags & AccessFlags.SYNTHETIC.getValue()) == 0) { return null; } Instruction[] instructions = encodedMethod.codeItem.getInstructions(); //TODO: add support for odexed formats switch (instructions[0].opcode.format) { case Format35c: case Format3rc: { //a synthetic method access should be either 2 or 3 instructions, depending on if the method returns //anything or not if (instructions.length < 2 || instructions.length > 3) { return null; } InstructionWithReference instruction = (InstructionWithReference)instructions[0]; - MethodIdItem referencedMethodIdItem = (MethodIdItem)instruction.getReferencedItem(); + Item referencedItem = instruction.getReferencedItem(); + if (!(referencedItem instanceof MethodIdItem)) { + return null; + } + MethodIdItem referencedMethodIdItem = (MethodIdItem)referencedItem; accessedMember = new AccessedMember(METHOD, referencedMethodIdItem); resolvedAccessors.put(methodIdItem, accessedMember); return accessedMember; } case Format22c: { //a synthetic field access should be exactly 2 instructions. The set/put, and then the return if (instructions.length != 2) { return null; } Instruction22c instruction = (Instruction22c)instructions[0]; - FieldIdItem referencedFieldIdItem = (FieldIdItem)instruction.getReferencedItem(); + Item referencedItem = instruction.getReferencedItem(); + if (!(referencedItem instanceof FieldIdItem)) { + return null; + } + FieldIdItem referencedFieldIdItem = (FieldIdItem)referencedItem; if (instruction.opcode.setsRegister() || instruction.opcode.setsWideRegister()) { accessedMember = new AccessedMember(GETTER, referencedFieldIdItem); } else { accessedMember = new AccessedMember(SETTER, referencedFieldIdItem); } resolvedAccessors.put(methodIdItem, accessedMember); return accessedMember; } default: return null; } } public static class AccessedMember { private final int accessedMemberType; private final Item accessedMember; public AccessedMember(int accessedMemberType, Item accessedMember) { this.accessedMemberType = accessedMemberType; this.accessedMember = accessedMember; } public int getAccessedMemberType() { return accessedMemberType; } public Item getAccessedMember() { return accessedMember; } } }
false
true
public AccessedMember getAccessedMember(MethodIdItem methodIdItem) { AccessedMember accessedMember = resolvedAccessors.get(methodIdItem); if (accessedMember != null) { return accessedMember; } ClassDefItem classDefItem = classMap.getClassDefByType(methodIdItem.getContainingClass()); if (classDefItem == null) { return null; } ClassDataItem classDataItem = classDefItem.getClassData(); if (classDataItem == null) { return null; } ClassDataItem.EncodedMethod encodedMethod = classDataItem.findDirectMethodByMethodId(methodIdItem); if (encodedMethod == null) { return null; } //A synthetic accessor will be marked synthetic if ((encodedMethod.accessFlags & AccessFlags.SYNTHETIC.getValue()) == 0) { return null; } Instruction[] instructions = encodedMethod.codeItem.getInstructions(); //TODO: add support for odexed formats switch (instructions[0].opcode.format) { case Format35c: case Format3rc: { //a synthetic method access should be either 2 or 3 instructions, depending on if the method returns //anything or not if (instructions.length < 2 || instructions.length > 3) { return null; } InstructionWithReference instruction = (InstructionWithReference)instructions[0]; MethodIdItem referencedMethodIdItem = (MethodIdItem)instruction.getReferencedItem(); accessedMember = new AccessedMember(METHOD, referencedMethodIdItem); resolvedAccessors.put(methodIdItem, accessedMember); return accessedMember; } case Format22c: { //a synthetic field access should be exactly 2 instructions. The set/put, and then the return if (instructions.length != 2) { return null; } Instruction22c instruction = (Instruction22c)instructions[0]; FieldIdItem referencedFieldIdItem = (FieldIdItem)instruction.getReferencedItem(); if (instruction.opcode.setsRegister() || instruction.opcode.setsWideRegister()) { accessedMember = new AccessedMember(GETTER, referencedFieldIdItem); } else { accessedMember = new AccessedMember(SETTER, referencedFieldIdItem); } resolvedAccessors.put(methodIdItem, accessedMember); return accessedMember; } default: return null; } }
public AccessedMember getAccessedMember(MethodIdItem methodIdItem) { AccessedMember accessedMember = resolvedAccessors.get(methodIdItem); if (accessedMember != null) { return accessedMember; } ClassDefItem classDefItem = classMap.getClassDefByType(methodIdItem.getContainingClass()); if (classDefItem == null) { return null; } ClassDataItem classDataItem = classDefItem.getClassData(); if (classDataItem == null) { return null; } ClassDataItem.EncodedMethod encodedMethod = classDataItem.findDirectMethodByMethodId(methodIdItem); if (encodedMethod == null) { return null; } //A synthetic accessor will be marked synthetic if ((encodedMethod.accessFlags & AccessFlags.SYNTHETIC.getValue()) == 0) { return null; } Instruction[] instructions = encodedMethod.codeItem.getInstructions(); //TODO: add support for odexed formats switch (instructions[0].opcode.format) { case Format35c: case Format3rc: { //a synthetic method access should be either 2 or 3 instructions, depending on if the method returns //anything or not if (instructions.length < 2 || instructions.length > 3) { return null; } InstructionWithReference instruction = (InstructionWithReference)instructions[0]; Item referencedItem = instruction.getReferencedItem(); if (!(referencedItem instanceof MethodIdItem)) { return null; } MethodIdItem referencedMethodIdItem = (MethodIdItem)referencedItem; accessedMember = new AccessedMember(METHOD, referencedMethodIdItem); resolvedAccessors.put(methodIdItem, accessedMember); return accessedMember; } case Format22c: { //a synthetic field access should be exactly 2 instructions. The set/put, and then the return if (instructions.length != 2) { return null; } Instruction22c instruction = (Instruction22c)instructions[0]; Item referencedItem = instruction.getReferencedItem(); if (!(referencedItem instanceof FieldIdItem)) { return null; } FieldIdItem referencedFieldIdItem = (FieldIdItem)referencedItem; if (instruction.opcode.setsRegister() || instruction.opcode.setsWideRegister()) { accessedMember = new AccessedMember(GETTER, referencedFieldIdItem); } else { accessedMember = new AccessedMember(SETTER, referencedFieldIdItem); } resolvedAccessors.put(methodIdItem, accessedMember); return accessedMember; } default: return null; } }